智谱
本站(springdoc.cn)中的内容来源于 spring.io ,原始版权归属于 spring.io。由 springdoc.cn 进行翻译,整理。可供个人学习、研究,未经许可,不得进行任何转载、商用或与之相关的行为。 商标声明:Spring 是 Pivotal Software, Inc. 在美国以及其他国家的商标。 |
Spring AI 支持智谱 AI(ZhiPu AI)的多种语言模型。你可以通过智谱 AI 模型交互,构建基于智谱 AI 的多语言对话助手。
先决条件
你需要创建智谱 AI(ZhiPuAI)的 API Key 以访问其语言模型。
在 智谱 AI 注册页面 创建账户,并于 API Key 页面 生成访问令牌。
Spring AI 项目定义了名为 spring.ai.zhipuai.api-key
的配置属性,应将其设置为从 API Key 页面获取的密钥值。
你可以在 application.properties
文件中设置此配置属性:
spring.ai.zhipuai.api-key=<your-zhipuai-api-key>
为提升处理 API Key 等敏感信息的安全性,可使用 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 自动配置及 Starter 模块的 Artifact 命名已发生重大变更。具体升级说明请参阅 更新文档。 |
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 sec. |
spring.ai.retry.backoff.multiplier |
退避间隔乘数。 |
5 |
spring.ai.retry.backoff.max-interval |
最大退避时长。 |
3 min. |
spring.ai.retry.on-client-errors |
如果为 |
false |
spring.ai.retry.exclude-on-http-codes |
不应触发重试的 HTTP 状态代码列表(例如抛出 |
empty |
spring.ai.retry.on-http-codes |
应触发重试的 HTTP 状态代码列表(例如抛出 |
empty |
连接属性
前缀 spring.ai.zhipuai
用作连接至智谱 AI 的属性配置前缀。
属性 | 说明 | 默认值 |
---|---|---|
spring.ai.zhipuai.base-url |
The URL to connect to |
|
spring.ai.zhipuai.api-key |
The API Key |
- |
配置属性
聊天自动配置的启用和禁用现在通过顶级属性配置,前缀为
此变更是为了支持多模型配置。 |
前缀 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.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 |
温度采样的替代方案,称为核采样(nucleus sampling),模型仅考虑概率质量之和达到 top_p 的 token 结果。例如 0.1 表示仅考虑概率质量前 10% 的 token。通常建议调整此参数或 temperature 中的一个,而非同时调整两者。 |
1.0 |
spring.ai.zhipuai.chat.options.stop |
模型将在遇到 |
- |
spring.ai.zhipuai.chat.options.user |
一个代表你的终端用户的唯一标识符,可帮助智谱 AI 监控和检测滥用行为。 |
- |
spring.ai.zhipuai.chat.options.requestId |
该参数由客户端传入,必须保证唯一性,用于区分每次请求的唯一标识。若客户端未提供,平台将默认生成。 |
- |
spring.ai.zhipuai.chat.options.doSample |
当 |
true |
spring.ai.zhipuai.chat.options.proxy-tool-calls |
若为 |
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 账户的场景。
|
所有以 spring.ai.zhipuai.chat.options 为前缀的属性,都可通过在 Prompt 调用中添加请求特定的 运行时选项 来覆盖。
|
运行时选项
ZhiPuAiChatOptions.java 提供模型配置参数,包括使用的模型、温度值(Temperature)、频率惩罚(Frequency Penalty)等。
启动时,默认选项可通过 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_3_Turbo.getValue())
.temperature(0.5)
.build()
));
除了模型专用的 ZhiPuAiChatOptions 外,你还可以使用通过 ChatOptionsBuilder#builder() 创建的可移植 ChatOptions 实例。 |
示例 Controller
创建 一个新的 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("/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);
}
}
手动配置
ZhiPuAiChatModel 实现了 ChatModel
和 StreamingChatModel
接口,并使用 底层智谱 Api 客户端 连接至智谱 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_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."));
ZhiPuAiChatOptions
为聊天请求提供配置信息,其内置的 ZhiPuAiChatOptions.Builder
为 Fluent 式选项构建器。
底层智谱 Api 客户端
ZhiPuAiApi 是面向 ZhiPu AI API 的轻量级 Java 客户端。
以下是通过代码使用该 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));
更多详细信息请参阅 ZhiPuAiApi.java 的 JavaDoc 文档。
ZhiPuAiApi 示例
ZhiPuAiApiIT.java 测试类提供了使用该轻量级库的通用示例。