Spring AI 整合聊天模型之智谱AI

Spring AI 整合聊天模型之智谱AI

Spring AI 支持智谱 AI(ZhiPu AI)的各种人工智能语言模型。可以与智谱 AI 的语言模型进行交互,并基于智谱 AI 的模型创建一个多语言会话助手。

Spring AI 整合聊天模型之智谱AI

在智谱的官方站点: open.bigmodel.cn/ 注册并获取一个API Key。

Spring AI 项目定义了一个名为 spring.ai.zhipuai.api-key 的配置属性,将其设置为从 API 密钥页面获取的 API 密钥的值。

可以在 application.properties 文件中设置这个配置属性:

spring.ai.zhipuai.api-key=<your-zhipuai-api-key>

在处理像 API 密钥这样的敏感信息时,为了增强安全性,可以使用 Spring 表达式语言(SpEL)来引用自定义的环境变量:

# In application.yml spring: ai: zhipuai: api-key: ${ZHIPUAI_API_KEY}

这个变量可以同环境变量设置,比如Linux 设置:

# In your environment or .env file export ZHIPUAI_API_KEY=<your-zhipuai-api-key>

也可以在应用程序代码中以编程方式设置此配置:

// Retrieve API key from a secure source or environment variable String apiKey = System智谱 AI GLM 教程.getenv("ZHIPUAI_API_KEY");

Spring AI 为智谱 AI(ZhiPuAI)聊天客户端提供了 Spring Boot 自动配置功能。要启用此功能,将以下依赖项添加到项目的 Maven pom.xml 文件中:

<dependency> <groupId>org.springframework.ai</groupId> <artifactId>spring-ai-starter-model-zhipuai</artifactId> </dependency>

重试属性(Retry Properties)

前缀 <font style="color:rgb(6, 7, 31);background-color:rgba(27, 31, 35, 0.05);">spring.ai.retry</font> 用作属性前缀,用于为智谱 AI(ZhiPu AI)聊天模型配置重试机制。

属性 描述 默认值
spring.ai.retry.max-attempts 最大重试次数 10
spring.ai.retry.backoff.initial-interval 指数退避策略的初始休眠时长 2秒
spring.ai.retry.backoff.multiplier 退避间隔倍增系数 5
spring.ai.retry.backoff.max-interval 最大退避时长 3分钟
spring.ai.retry.on-client-errors 若为false,遇到4xx客户端错误码时抛出NonTransientAiException且不重试 false
spring.ai.retry.exclude-on-http-codes 不应触发重试的HTTP状态码列表(将抛出NonTransientAiException)
spring.ai.retry.on-http-codes 应触发重试的HTTP状态码列表(将抛出TransientAiException)

前缀 spring.ai.zhiPu 用作属性前缀,可用于连接到智谱 AI(ZhiPuAI)

属性 描述 默认值
spring.ai.zhipuai.base-url 连接的目标URL open.bigmodel.cn/api/pa
spring.ai.zhipuai.api-key API密钥

聊天自动配置的启用和禁用现在可通过带有前缀
spring.ai.model.chat 的顶级属性进行配置。

若要启用,设置
spring.ai.model.chat=zhipuai(默认情况下已启用)

若要禁用,设置
spring.ai.model.chat=none(或设置为任何不匹配
zhipuai 的值)

前缀 spring.ai.zhipuai.chat 是用于配置智谱 AI(ZhiPuAI)聊天模型实现的属性前缀。

属性 说明 默认值
spring.ai.zhipuai.chat.enabled (已移除且不再有效) 启用智谱AI聊天模型 true
spring.ai.model.chat 启用智谱AI聊天模型 zhipuai
spring.ai.zhipuai.chat.base-url 可选配置,覆盖spring.ai.zhipuai.base-url以提供聊天专用URL open.bigmodel.cn/api/pa
spring.ai.zhipuai.chat.api-key 可选配置,覆盖spring.ai.zhipuai.api-key以提供聊天专用API密钥
spring.ai.zhipuai.chat.options.model 指定使用的智谱AI聊天模型 GLM-3-Turbo(GLM-3-Turbo、GLM-4、GLM-4-Air、GLM-4-AirX、GLM-4-Flash和GLM-4V均指向最新模型版本)
spring.ai.zhipuai.chat.options.maxTokens 聊天补全生成的最大token数。输入token和生成token的总长度受模型上下文长度限制
spring.ai.zhipuai.chat.options.temperature 采样温度,取值0到1。较高值(如0.8)使输出更随机,较低值(如0.2)使输出更集中和确定。通常建议调整此参数或top_p,但不要同时调整 0.7
spring.ai.zhipuai.chat.options.topP 温度采样的替代方案——核采样,模型仅考虑概率质量前top_p的token。例如0.1表示仅考虑前10%概率质量的token。通常建议调整此参数或temperature,但不要同时调整 1.0
spring.ai.zhipuai.chat.options.stop 模型将停止生成指定的停止字符,当前仅支持单个停止词,格式为[“stop_word1”]
spring.ai.zhipuai.chat.options.user 终端用户的唯一标识符,可帮助智谱AI监控和检测滥用行为
spring.ai.zhipuai.chat.options.requestId 客户端传递的参数,必须确保唯一性,用于区分每个请求的唯一标识符。若客户端未提供,平台将默认生成
spring.ai.zhipuai.chat.options.doSample 当设为true时启用采样策略。若为false,则采样策略参数temperature和top_p不生效 true
spring.ai.zhipuai.chat.options.proxy-tool-calls 若为true,Spring AI将不会内部处理函数调用,而是代理给客户端。客户端需负责处理函数调用、分派到适当函数并返回结果。若为false(默认),Spring AI将内部处理函数调用。仅适用于支持函数调用的聊天模型 false

可以为
ChatModel 实现覆盖通用的
spring.ai.zhipuai.base-url
spring.ai.zhipuai.api-key。如果设置了
spring.ai.zhipuai.chat.base-url
spring.ai.zhipuai.chat.api-key 属性,它们将优先于通用属性。当希望为不同的模型使用不同的智谱 AI(ZhiPuAI)账户以及不同的模型端点时,这一功能非常有用。

所有以
<font style="color:rgb(6, 7, 31);background-color:rgba(27, 31, 35, 0.05);">spring.ai.zhipuai.chat.options</font> 为前缀的属性,都可以在运行时通过向提示调用(Prompt call)中添加特定于请求的运行时选项(Runtime Options)来进行覆盖。

<font style="color:rgb(6, 7, 31);background-color:rgba(27, 31, 35, 0.05);">ZhiPuAiChatOptions.java</font> 类提供了模型配置,例如要使用的模型、温度(temperature)、频率惩罚(frequency penalty)等。

在启动时,可以使用 <font style="color:rgb(6, 7, 31);background-color:rgba(27, 31, 35, 0.05);">ZhiPuAiChatModel(api, options)</font> 构造函数或 <font style="color:rgb(6, 7, 31);background-color:rgba(27, 31, 35, 0.05);">spring.ai.zhipuai.chat.options.*</font> 属性来配置默认选项。

在运行时,您可以通过向提示调用(Prompt call)中添加新的、特定于请求的选项来覆盖默认选项。例如,要为特定请求覆盖默认模型和温度,可以这样做:

ChatResponse response = chatModel.call( new Prompt( "Generate the names of 5 famous pirates.", ZhiPuAiChatOptions.builder() .model(ZhiPuAiApi.ChatModel.GLM_3_Turbo.getValue()) .temperature(0.5) .build() ));

除了针对特定模型的
ZhiPuAiChatOptions 之外,还可以使用一个可移植的
ChatOptions 实例,该实例可以通过
ChatOptionsBuilder#builder() 方法来创建。

创建一个新的 Spring Boot 项目,并将 <font style="color:rgb(6, 7, 31);background-color:rgba(27, 31, 35, 0.05);">spring-ai-starter-model-zhipuai</font> 添加到的 pom(或 gradle)依赖项中。

<font style="color:rgb(6, 7, 31);background-color:rgba(27, 31, 35, 0.05);">src/main/resources</font> 目录下添加一个 <font style="color:rgb(6, 7, 31);background-color:rgba(27, 31, 35, 0.05);">application.properties</font> 文件,以启用并配置智谱 AI(ZhiPuAi)聊天模型:

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

这将创建一个 <font style="color:rgb(6, 7, 31);background-color:rgba(27, 31, 35, 0.05);">ZhiPuAiChatModel</font> 实现,可以将其注入到类中。以下是一个简单的 <font style="color:rgb(6, 7, 31);background-color:rgba(27, 31, 35, 0.05);">@Controller</font> 类示例,该类使用聊天模型进行文本生成。

@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", this.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 this.chatModel.stream(prompt); } }

<font style="color:rgb(6, 7, 31);background-color:rgba(27, 31, 35, 0.05);">ZhiPuAiChatModel</font> 实现了 <font style="color:rgb(6, 7, 31);background-color:rgba(27, 31, 35, 0.05);">ChatModel</font><font style="color:rgb(6, 7, 31);background-color:rgba(27, 31, 35, 0.05);">StreamingChatModel</font> 接口,并使用低级别的 <font style="color:rgb(6, 7, 31);background-color:rgba(27, 31, 35, 0.05);">ZhiPuAiApi</font> 客户端来连接到智谱 AI(ZhiPuAI)服务。

<font style="color:rgb(6, 7, 31);background-color:rgba(27, 31, 35, 0.05);">spring-ai-zhipuai</font> 依赖项添加到项目的 Maven <font style="color:rgb(6, 7, 31);background-color:rgba(27, 31, 35, 0.05);">pom.xml</font> 文件中:

<dependency> <groupId>org.springframework.ai</groupId> <artifactId>spring-ai-zhipuai</artifactId> </dependency>

接下来,创建一个 <font style="color:rgb(6, 7, 31);background-color:rgba(27, 31, 35, 0.05);">ZhiPuAiChatModel</font> 实例,并使用它进行文本生成:

var zhiPuAiApi = new ZhiPuAiApi(System.getenv("ZHIPU_AI_API_KEY")); var chatModel = new ZhiPuAiChatModel(this.zhiPuAiApi, ZhiPuAiChatOptions.builder() .model(ZhiPuAiApi.ChatModel.GLM_3_Turbo.getValue()) .temperature(0.4) .maxTokens(200) .build()); ChatResponse response = this.chatModel.call( new Prompt("Generate the names of 5 famous pirates.")); // Or with streaming responses Flux<ChatResponse> streamResponse = this.chatModel.stream( new Prompt("Generate the names of 5 famous pirates."));

<font style="color:rgb(6, 7, 31);background-color:rgba(27, 31, 35, 0.05);">ZhiPuAiChatOptions</font> 为聊天请求提供了配置信息。<font style="color:rgb(6, 7, 31);background-color:rgba(27, 31, 35, 0.05);">ZhiPuAiChatOptions.Builder</font> 是一个流畅的选项构建器(fluent options builder)。

<font style="color:rgb(6, 7, 31);background-color:rgba(27, 31, 35, 0.05);">ZhiPuAiApi</font> 提供了一个轻量级的 Java 客户端,用于访问智谱 AI 的 API。

以下是一个简单的代码片段,展示了如何以编程方式使用该 API:

ZhiPuAiApi zhiPuAiApi = new ZhiPuAiApi(System.getenv("ZHIPU_AI_API_KEY")); ChatCompletionMessage chatCompletionMessage = new ChatCompletionMessage("Hello world", Role.USER); // Sync request ResponseEntity<ChatCompletion> response = this.zhiPuAiApi.chatCompletionEntity( new ChatCompletionRequest(List.of(this.chatCompletionMessage), ZhiPuAiApi.ChatModel.GLM_3_Turbo.getValue(), 0.7, false)); // Streaming request Flux<ChatCompletionChunk> streamResponse = this.zhiPuAiApi.chatCompletionStream( new ChatCompletionRequest(List.of(this.chatCompletionMessage), ZhiPuAiApi.ChatModel.GLM_3_Turbo.getValue(), 0.7, true));

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/270319.html原文链接:https://javaforall.net

(0)
上一篇 2026年3月12日 下午3:05
下一篇 2026年3月12日 下午3:06


相关推荐

关注全栈程序员社区公众号