智谱 AI 聊天
Spring AI 支持智谱 AI 的各种 AI 语言模型。您可以与智谱 AI 语言模型交互,并基于智谱 AI 模型创建多语言对话助手。
如果您不是中文使用者,可以访问智谱 AI 国际网站 Z.ai
先决条件
您需要创建智谱AI的API以访问智谱AI语言模型。
在 智谱 AI 注册页面(或 Z.ai 注册页面)创建帐户,并在 API 密钥页面(或 Z.ai API 密钥页面)生成令牌。
Spring AI项目定义了一个名为spring.ai.zhipuai.api-key的配置属性,您应该将其设置为从API Keys页面获取的API Key的值。
您可以在 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}
# 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.getenv("ZHIPUAI_API_KEY");
自动配置
|
Spring AI 自动配置、启动模块的工件名称发生了重大变化。请参阅 升级说明 以获取更多信息。 |
Spring AI 为智谱 AI 聊天客户端提供 Spring Boot 自动配置。要启用它,请将以下依赖项添加到项目的 Maven pom.xml 文件中
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-zhipuai</artifactId>
</dependency>
或添加到您的 Gradle build.gradle 构建文件中。
dependencies {
implementation 'org.springframework.ai:spring-ai-starter-model-zhipuai'
}
| 请参阅 依赖项管理 部分,将 Spring AI BOM 添加到您的构建文件中。 |
聊天属性
重试属性
前缀 spring.ai.retry 用作属性前缀,允许您配置智谱 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,则抛出 NonTransientAiException,并且不尝试重试 |
假 |
spring.ai.retry.exclude-on-http-codes |
不应触发重试的 HTTP 状态代码列表(例如,抛出 NonTransientAiException)。 |
空 |
spring.ai.retry.on-http-codes |
应触发重试的 HTTP 状态代码列表(例如,抛出 TransientAiException)。 |
空 |
连接属性
前缀spring.ai.zhipuai用作属性前缀,允许您连接到智谱AI。
| 财产 | 描述 | 默认值 |
|---|---|---|
spring.ai.zhipuai.base-url |
连接智谱 AI API 的 URL。 |
|
spring.ai.zhipuai.api-key |
API 密钥 |
- |
配置属性
|
聊天自动配置的启用和禁用现在通过以 要启用,请设置 spring.ai.model.chat=zhipuai(默认已启用) 要禁用,请设置 spring.ai.model.chat=none(或任何与 zhipuai 不匹配的值) 此更改是为了允许配置多个模型。 |
前缀 spring.ai.zhipuai.chat 是属性前缀,允许您配置智谱 AI 的聊天模型实现。
| 财产 | 描述 | 默认值 |
|---|---|---|
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。 |
|
spring.ai.zhipuai.chat.api-key |
可选地覆盖 spring.ai.zhipuai.api-key 以提供聊天特定的 api-key。 |
- |
spring.ai.zhipuai.chat.options.model |
这是要使用的智谱 AI 聊天模型。您可以选择的模型包括: |
|
spring.ai.zhipuai.chat.options.maxTokens |
在聊天补全中生成的最大令牌数。输入令牌和生成令牌的总长度受模型上下文长度的限制。 |
- |
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 指定的字符处停止生成,目前仅支持 ["stop_word1"] 格式的单个停止词 |
- |
spring.ai.zhipuai.chat.options.user |
表示您的最终用户的唯一标识符,有助于智谱 AI 监控和检测滥用行为。 |
- |
spring.ai.zhipuai.chat.options.requestId |
该参数由客户端传递,必须确保唯一性。它用于区分每个请求的唯一标识符。如果客户端未提供,平台将默认生成。 |
- |
spring.ai.zhipuai.chat.options.doSample |
当 do_sample 设置为 true 时,采样策略被启用。如果 do_sample 为 false,则采样策略参数 temperature 和 top_p 将不生效。 |
true |
spring.ai.zhipuai.chat.options.response-format.type |
控制模型输出的格式。设置为 |
- |
spring.ai.zhipuai.chat.options.thinking.type |
控制是否启用大模型的思维链。可用选项: |
- |
spring.ai.zhipuai.chat.options.tool-names |
工具列表,通过其名称标识,用于在单个提示请求中启用函数调用。具有这些名称的工具必须存在于 ToolCallback 注册表中。 |
- |
spring.ai.zhipuai.chat.options.tool-callbacks |
要注册到 ChatModel 的工具回调。 |
- |
spring.ai.zhipuai.chat.options.internal-tool-execution-enabled |
如果为 false,Spring AI 将不会在内部处理工具调用,而是将其代理到客户端。然后,客户端负责处理工具调用,将其分派到适当的函数,并返回结果。如果为 true(默认),Spring AI 将在内部处理函数调用。仅适用于支持函数调用的聊天模型 |
true |
您可以为 ChatModel 实现覆盖通用的 spring.ai.zhipuai.base-url 和 spring.ai.zhipuai.api-key。如果设置了 spring.ai.zhipuai.chat.base-url 和 spring.ai.zhipuai.chat.api-key 属性,它们将优先于通用属性。这在您希望为不同的模型和不同的模型端点使用不同的智谱 AI 账户时非常有用。 |
所有带有 spring.ai.zhipuai.chat.options 前缀的属性都可以在运行时通过向 Prompt 调用添加请求特定的 运行时选项 来覆盖。 |
运行时选项
ZhiPuAiChatOptions.java 提供了模型配置,例如要使用的模型、温度、频率惩罚等。
在启动时,可以使用 ZhiPuAiChatModel(api, options) 构造函数或 spring.ai.zhipuai.chat.options.* 属性配置默认选项。
在运行时,您可以通过向 Prompt 调用添加新的、请求特定的选项来覆盖默认选项。例如,为特定请求覆盖默认模型和温度
ChatResponse response = chatModel.call(
new Prompt(
"Generate the names of 5 famous pirates.",
ZhiPuAiChatOptions.builder()
.model(ZhiPuAiApi.ChatModel.GLM_4_Air.getValue())
.temperature(0.5)
.build()
));
| 除了模型特定的 ZhiPuAiChatOptions,您还可以使用通过 ChatOptions#builder() 创建的可移植 ChatOptions 实例。 |
示例控制器
创建一个新的 Spring Boot 项目,并将 spring-ai-starter-model-zhipuai 添加到您的 pom (或 gradle) 依赖项中。
在 src/main/resources 目录下添加一个 application.properties 文件,以启用和配置智谱 AI 聊天模型
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
将 api-key 替换为您的智谱 AI 凭据。 |
这将创建一个 ZhiPuAiChatModel 实现,您可以将其注入到您的类中。这是一个简单的 @Controller 类的示例,它使用聊天模型进行文本生成。
@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(value = "/ai/generateStream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
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);
}
}
手动配置
ZhiPuAiChatModel 实现了 ChatModel 和 StreamingChatModel,并使用 低级 ZhiPuAiApi 客户端 连接到智谱 AI 服务。
将 spring-ai-zhipuai 依赖项添加到您的项目的 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'
}
| 请参阅 依赖项管理 部分,将 Spring AI BOM 添加到您的构建文件中。 |
接下来,创建一个 ZhiPuAiChatModel 并将其用于文本生成
var zhiPuAiApi = new ZhiPuAiApi(System.getenv("ZHIPU_AI_API_KEY"));
var chatModel = new ZhiPuAiChatModel(this.zhiPuAiApi, ZhiPuAiChatOptions.builder()
.model(ZhiPuAiApi.ChatModel.GLM_4_Air.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."));
ZhiPuAiChatOptions 提供了聊天请求的配置信息。ZhiPuAiChatOptions.Builder 是一个流畅的选项构建器。
低级 ZhiPuAiApi 客户端
ZhiPuAiApi 提供了一个轻量级的 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_4_Air.getValue(), 0.7, false));
// Streaming request
Flux<ChatCompletionChunk> streamResponse = this.zhiPuAiApi.chatCompletionStream(
new ChatCompletionRequest(List.of(this.chatCompletionMessage), ZhiPuAiApi.ChatModel.GLM_4_Air.getValue(), 0.7, true));
有关更多信息,请参阅 ZhiPuAiApi.java 的 JavaDoc。
ZhiPuAiApi 示例
-
ZhiPuAiApiIT.java 测试提供了一些如何使用轻量级库的通用示例。