SpringAI调用ZhiPu AI

以下是使用Spring AI请求ZhiPu AI的相关代码示例:

1. 自动配置方式(使用Spring Boot Starter)

  1. 添加依赖
    • 在Maven的pom.xml文件中添加:
    <dependency>
        <groupId>org.springframework.ai</groupId>
        <artifactId>spring-ai-zhipuai-spring-boot-starter</artifactId>
    </dependency>
    
    • 在Gradle的build.gradle文件中添加:
    dependencies {
        implementation 'org.springframework.ai:spring-ai-zhipuai-spring-boot-starter'
    }
    
  2. 配置属性
    • application.properties文件中配置(示例):
    spring.ai.zhipuai.api-key=YOUR_API_KEY
    spring.ai.zhipuai.chat.options.model=glm-4-air
    spring.ai.zhipuai.chat.options.temperature=0.7
    
  3. 使用示例(在控制器中)
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;
    import reactor.core.publisher.Flux;
    import reactor.core.publisher.Mono;
    import java.util.Map;
    
    @RestController
    public class ChatController {
        private final ZhiPuAiChatModel chatModel;
    
        @Autowired
        public ChatController(ZhiPuAiChatModel chatModel) {
            this.chatModel = chatModel;
        }
    
        @GetMapping("/ai/generate")
        public Map generate(@RequestParam(value = "message", defaultValue = "Tell me a joke") String message) {
            return Map.of("generation", chatModel.call(message));
        }
    
        @GetMapping("/ai/generateStream")
        public Flux<ChatResponse> generateStream(@RequestParam(value = "message", defaultValue = "Tell me a joke") String message) {
            var prompt = new Prompt(new UserMessage(message));
            return chatModel.stream(prompt);
        }
    }
    

2. 手动配置方式

  1. 添加依赖
    • 在Maven的pom.xml文件中添加:
    <dependency>
        <groupId>org.springframework.ai</groupId>
        <artifactId>spring-ai-zhipuai</artifactId>
    </dependency>
    
    • 在Gradle的build.gradle文件中添加:
    dependencies {
        implementation 'org.springframework.ai:spring-ai-zhipuai'
    }
    
  2. 创建和使用ZhiPuAiChatModel
    import org.springframework.ai.zhipuai.ZhiPuAiApi;
    import org.springframework.ai.zhipuai.ZhiPuAiChatModel;
    import org.springframework.ai.zhipuai.ZhiPuAiChatOptions;
    import org.springframework.ai.zhipuai.chat.Prompt;
    import reactor.core.publisher.Flux;
    import reactor.core.publisher.Mono;
    import java.util.List;
    import java.util.Map;
    
    public class ManualConfigurationExample {
        public static void main(String[] args) {
            var zhiPuAiApi = new ZhiPuAiApi(System.getenv("ZHIPU_AI_API_KEY"));
    
            var chatModel = new ZhiPuAiChatModel(zhiPuAiApi, ZhiPuAiChatOptions.builder()
                   .withModel(ZhiPuAiApi.ChatModel.GLM_3_Turbo.getValue())
                   .withTemperature(0.4)
                   .withMaxTokens(200)
                   .build());
    
            ChatResponse response = chatModel.call(
                    new Prompt("Generate the names of 5 famous pirates."));
    
            // Or with streaming responses
            Flux<ChatResponse> streamResponse = chatModel.stream(
                    new Prompt("Generate the names of 5 famous pirates."));
        }
    }
    

3. 直接使用ZhiPuAiApi客户端

import org.springframework.ai.zhipuai.ZhiPuAiApi;
import org.springframework.http.ResponseEntity;
import reactor.core.publisher.Flux;
import java.util.List;

public class ZhiPuAiApiExample {
    public static void main(String[] args) {
        ZhiPuAiApi zhiPuAiApi = new ZhiPuAiApi(System.getenv("ZHIPU_AI_API_KEY"));

        ChatCompletionMessage chatCompletionMessage = new ChatCompletionMessage("Hello world", Role.USER);

        // Sync request
        ResponseEntity<ChatCompletion> response = zhiPuAiApi.chatCompletionEntity(
                new ChatCompletionRequest(List.of(chatCompletionMessage), ZhiPuAiApi.ChatModel.GLM_3_Turbo.getValue(), 0.7, false));

        // Streaming request
        Flux<ChatCompletionChunk> streamResponse = zhiPuAiApi.chatCompletionStream(
                new ChatCompletionRequest(List.of(chatCompletionMessage), ZhiPuAiApi.ChatModel.GLM_3_Turbo.getValue(), 0.7, true));
    }
}
### SpringAI 集成智谱 API 方法 为了使应用程序能够集成并调用智谱提供的大模型API,可以通过引入相应的SDK依赖项以及编写必要的配置文件和服务类来完成这一过程。对于Spring AI而言,由于其设计之初就考虑到了多个人工智能服务商的支持,因此在实际操作过程中只需要遵循官方文档指导即可轻松实现与智谱平台之间的对接。 #### 添加 Maven 依赖 首先,在项目的`pom.xml`文件中加入智谱开放平台所提供的Java SDK作为项目依赖: ```xml <dependency> <groupId>cn.zhipu.openapi</groupId> <artifactId>zhipu-oapi-java-sdk</artifactId> <version>latest-version</version> </dependency> ``` 请注意替换上述代码中的`latest-version`为最新版本号[^5]。 #### 创建配置类 接着创建一个新的Java类用于加载来自环境变量或application.properties/yml的应用程序属性,并初始化ZhiPuClient实例以便后续发起请求时使用: ```java @Configuration public class ZhiPuConfig { @Value("${zhipu.api.key}") private String apiKey; @Bean public ZhiPuClient zhiPuClient() { return new ZhiPuClient(apiKey); } } ``` 这里假设已经在外部资源文件里定义好了名为`zhipu.api.key`的关键字对应着有效的API密钥字符串[^2]。 #### 编写服务层逻辑 最后一步就是构建具体业务场景下的处理流程了。比如当需要向用户提供自动回复功能的时候就可以这样做: ```java @Service public class ChatService { private final ZhiPuClient client; @Autowired public ChatService(ZhiPuClient client){ this.client = client; } public String getResponse(String message) throws Exception{ // 构建请求体对象 Map<String, Object> body = new HashMap<>(); body.put("prompt", message); // 发送POST请求给智谱服务器获取响应数据 Response response = client.post("/v1/chat/completions", body); // 解析返回的结果集提取有用的信息部分 JSONObject jsonResult = (JSONObject)new JSONParser().parse(response.body()); return jsonResult.get("choices").toString(); } } ``` 这段简单的例子展示了怎样借助于之前准备好的客户端工具去发送消息至远程主机等待答复再将其展示出来[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值