收藏本站,收获最前沿的人工智能与编程资讯!!

Spring AI 使用智谱 AI

技术文档 11℃ 0

Spring 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 密钥页面获取的 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}
# 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");

添加仓库和物料清单(BOM)

Spring AI 构件发布在 Maven 中央仓库和 Spring 快照仓库中。参考构件仓库章节将这些仓库添加到你的构建系统中。

为了方便依赖管理,Spring AI 提供了物料清单(BOM),确保整个项目使用一致版本的 Spring AI。参考依赖管理章节将 Spring AI BOM 添加到你的构建系统中。

自动配置

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,针对 4xx 客户端错误码抛出 NonTransientAiException 异常,不重试false
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 的地址
若使用 Z.ai 平台,需设置为 https://api.z.ai/api/paas
https://open.bigmodel.cn/api/paas
spring.ai.zhipuai.api-keyAPI 密钥-

配置属性

聊天自动配置的启用与禁用现在通过以 spring.ai.model.chat 为前缀的顶级属性配置。

启用: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,提供聊天专用地址
若使用 Z.ai 平台,需设置为 https://api.z.ai/api/paas
https://open.bigmodel.cn/api/paas
spring.ai.zhipuai.chat.api-key可选,覆盖 spring.ai.zhipuai.api-key,提供聊天专用密钥-
spring.ai.zhipuai.chat.options.model使用的智谱 AI 聊天模型,可选 glm-4.6、glm-4.5、glm-4-air 等glm-4-air
spring.ai.zhipuai.chat.options.maxTokens聊天补全最大生成令牌数,输入令牌与生成令牌总长度受模型上下文长度限制-
spring.ai.zhipuai.chat.options.temperature采样温度,取值 0-1,值越高输出越随机,值越低越聚焦确定,建议仅修改该参数或 top_p 中的一个0.7
spring.ai.zhipuai.chat.options.topP核采样参数,替代温度控制随机性,建议仅修改该参数或 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.response-format.type控制模型输出格式,设置为 json_object 可确保输出合法 JSON 对象,可选值:text 或 json_object-
spring.ai.zhipuai.chat.options.thinking.type控制是否启用大模型思维链,可选值:enabled 或 disabled-
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(默认)则内部处理,仅适用于支持函数调用的聊天模型true

你可以为 ChatModel 实现覆盖通用的 spring.ai.zhipuai.base-urlspring.ai.zhipuai.api-key。若设置了 spring.ai.zhipuai.chat.base-urlspring.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 实现。以下是简单的 @RestController 示例,使用聊天模型生成文本:

@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 的 Java 文档。

ZhiPuAiApi 示例

ZhiPuAiApiIT.java 测试提供轻量级库的通用使用示例。

相关推荐