Skip to main content
Spring AI 支持智谱 AI 提供的各种 AI 语言模型。你可以与智谱 AI 语言模型进行交互,并基于智谱 AI 模型创建多语言会话助手。

前提条件

你需要使用智谱 AI 创建一个 API 才能访问智谱 AI 语言模型。 智谱 AI 注册页面创建一个帐户,并在API 密钥页面生成令牌。 Spring AI 项目定义了一个名为 spring.ai.zhipuai.api-key 的配置属性,你应该将其设置为从 API 密钥页面获取的 API 密钥 的值。 你可以在 application.properties 文件中设置此配置属性:
spring.ai.zhipuai.api-key=<你的智谱AI API密钥>
为了在处理 API 密钥等敏感信息时增强安全性,你可以使用 Spring 表达式语言 (SpEL) 来引用自定义环境变量:
# 在 application.yml 中
spring:
  ai:
    zhipuai:
      api-key: ${ZHIPUAI_API_KEY}
# 在你的环境或 .env 文件中
export ZHIPUAI_API_KEY=<你的智谱AI API密钥>
你也可以在应用程序代码中以编程方式设置此配置:
// 从安全来源或环境变量中检索 API 密钥
String apiKey = System.getenv("ZHIPUAI_API_KEY");

添加仓库和 BOM

Spring AI 的构件发布在 Maven Central 和 Spring Snapshot 仓库中。 请参阅构件仓库部分,将这些仓库添加到你的构建系统中。 为了帮助进行依赖管理,Spring AI 提供了一个 BOM (bill of materials),以确保在整个项目中使用一致版本的 Spring AI。请参阅依赖管理部分,将 Spring AI BOM 添加到你的构建系统中。

自动配置

:::note 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'
}
:::tip 请参阅依赖管理部分,将 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,并且不尝试对 4xx 客户端错误代码进行重试false
spring.ai.retry.exclude-on-http-codes不应触发重试的 HTTP 状态代码列表(例如,抛出 NonTransientAiException)。
spring.ai.retry.on-http-codes应触发重试的 HTTP 状态代码列表(例如,抛出 TransientAiException)。

连接属性

前缀 spring.ai.zhiPu 用作属性前缀,允许你连接到智谱 AI。
属性描述默认值
spring.ai.zhipuai.base-url要连接的 URLhttps://open.bigmodel.cn/api/paas
spring.ai.zhipuai.api-keyAPI 密钥-

配置属性

:::note 聊天自动配置的启用和禁用现在通过前缀为 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 以提供特定于聊天的 urlhttps://open.bigmodel.cn/api/paas
spring.ai.zhipuai.chat.api-key可选地覆盖 spring.ai.zhipuai.api-key 以提供特定于聊天的 api-key-
spring.ai.zhipuai.chat.options.model这是要使用的智谱 AI 聊天模型GLM-3-Turbo (GLM-3-TurboGLM-4GLM-4-AirGLM-4-AirXGLM-4-FlashGLM-4V 指向最新的模型版本)
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 概率质量的标记的结果。因此 0.1 表示仅考虑构成前 10% 概率质量的标记。我们通常建议更改此项或温度,但不能同时更改两者。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.proxy-tool-calls如果为 true,Spring AI 将不会在内部处理函数调用,而是将它们代理到客户端。然后由客户端负责处理函数调用,将它们分派到适当的函数,并返回结果。如果为 false(默认值),Spring AI 将在内部处理函数调用。仅适用于具有函数调用支持的聊天模型false
:::note 你可以为 ChatModel 实现覆盖通用的 spring.ai.zhipuai.base-urlspring.ai.zhipuai.api-key。 如果设置了 spring.ai.zhipuai.chat.base-urlspring.ai.zhipuai.chat.api-key 属性,则它们优先于通用属性。 如果你想为不同的模型和不同的模型端点使用不同的智谱 AI 帐户,这将非常有用。 ::: :::tip 所有以 spring.ai.zhipuai.chat.options 为前缀的属性都可以在运行时通过向 Prompt 调用添加特定于请求的聊天选项来覆盖。 :::

运行时选项

ZhiPuAiChatOptions.java 提供模型配置,例如要使用的模型、温度、频率惩罚等。 在启动时,可以使用 ZhiPuAiChatModel(api, options) 构造函数或 spring.ai.zhipuai.chat.options.* 属性配置默认选项。 在运行时,你可以通过向 Prompt 调用添加新的、特定于请求的选项来覆盖默认选项。 例如,要为特定请求覆盖默认模型和温度:
ChatResponse response = chatModel.call(
    new Prompt(
        "生成 5 个著名海盗的名字。",
        ZhiPuAiChatOptions.builder()
            .model(ZhiPuAiApi.ChatModel.GLM_3_Turbo.getValue())
            .temperature(0.5)
        .build()
    ));
:::tip 除了特定于模型的 ZhiPuAiChatOptions之外,你还可以使用通过 ChatOptionsBuilder#builder() 创建的可移植 ChatOptions 实例。 :::

示例控制器

创建一个新的 Spring Boot 项目,并将 spring-ai-starter-model-zhipuai 添加到你的 pom (或 gradle) 依赖项中。 src/main/resources 目录下添加一个 application.properties 文件,以启用和配置智谱 AI 聊天模型:
spring.ai.zhipuai.api-key=你的API密钥
spring.ai.zhipuai.chat.options.model=glm-4-air
spring.ai.zhipuai.chat.options.temperature=0.7
:::tip 将 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 = "给我讲个笑话") String message) {
        return Map.of("generation", this.chatModel.call(message));
    }

    @GetMapping("/ai/generateStream")
    public Flux<ChatResponse> generateStream(@RequestParam(value = "message", defaultValue = "给我讲个笑话") String message) {
        var prompt = new Prompt(new UserMessage(message));
        return this.chatModel.stream(prompt);
    }
}

手动配置

ZhiPuAiChatModel.java 实现了 ChatModelStreamingChatModel,并使用低级 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'
}
:::tip 请参阅依赖管理部分,将 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("生成 5 个著名海盗的名字。"));

// 或使用流式响应
Flux<ChatResponse> streamResponse = this.chatModel.stream(
    new Prompt("生成 5 个著名海盗的名字。"));
ZhiPuAiChatOptions 为聊天请求提供配置信息。 ZhiPuAiChatOptions.Builder 是流畅的选项构建器。

低级智谱 AI API 客户端

ZhiPuAiApi.java 提供了轻量级的 Java 客户端,用于智谱 AI API 以下是一个简单的代码片段,展示了如何以编程方式使用 API:
ZhiPuAiApi zhiPuAiApi =
    new ZhiPuAiApi(System.getenv("ZHIPU_AI_API_KEY"));

ChatCompletionMessage chatCompletionMessage =
    new ChatCompletionMessage("你好世界", Role.USER);

// 同步请求
ResponseEntity<ChatCompletion> response = this.zhiPuAiApi.chatCompletionEntity(
    new ChatCompletionRequest(List.of(this.chatCompletionMessage), ZhiPuAiApi.ChatModel.GLM_3_Turbo.getValue(), 0.7, false));

// 流式请求
Flux<ChatCompletionChunk> streamResponse = this.zhiPuAiApi.chatCompletionStream(
        new ChatCompletionRequest(List.of(this.chatCompletionMessage), ZhiPuAiApi.ChatModel.GLM_3_Turbo.getValue(), 0.7, true));
有关更多信息,请参阅 ZhiPuAiApi.java 的 JavaDoc。

智谱 AI API 示例

  • ZhiPuAiApiIT.java 测试提供了一些有关如何使用轻量级库的常规示例。

文档有误?请协助编辑

发现文档问题?点击此处直接在 GitHub 上编辑并提交 PR,帮助我们改进文档!
I