如需最新的快照版本,请使用 Spring AI 1.1.3spring-doc.cadn.net.cn

智谱 AI 聊天

Spring AI 支持智谱 AI(ZhiPu AI)的多种大语言模型。您可以与智谱 AI 的大语言模型进行交互,并基于智谱 AI 模型创建多语言对话助手。spring-doc.cadn.net.cn

前置条件

您需要创建一个智谱 AI 的 API 以访问智谱大语言模型。spring-doc.cadn.net.cn

智谱 AI 注册页面 创建账户,并在 API 密钥页面 生成Tokens。spring-doc.cadn.net.cn

The Spring AI 项目定义了一个配置属性名为spring.ai.zhipuai.api-key,你应该将其设置为从API密钥页面获得的API Key的值。spring-doc.cadn.net.cn

您可以在您的application.properties文件中设置此配置属性:spring-doc.cadn.net.cn

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

处理敏感信息(如API密钥)时,为了增强安全性,您可以使用Spring表达式语言(SpEL)引用自定义环境变量:spring-doc.cadn.net.cn

# 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>

您也可以在应用程序代码中通过编程方式设置此配置:spring-doc.cadn.net.cn

// Retrieve API key from a secure source or environment variable
String apiKey = System.getenv("ZHIPUAI_API_KEY");

添加仓库和BOM

Spring AI 构件发布在 Maven 中央仓库和 Spring Snapshot 仓库中。 请参阅 构件仓库 部分,将这些仓库添加到您的构建系统中。spring-doc.cadn.net.cn

为了帮助进行依赖管理,Spring AI 提供了一个 BOM(物料清单),以确保整个项目中使用的是相同的 Spring AI 版本。请参阅 依赖管理 部分,将 Spring AI BOM 添加到您的构建系统中。spring-doc.cadn.net.cn

Auto-configuration

Spring AI自动配置和starter模块的artifact名称有了重大变化。 请参阅升级说明获取更多信息。spring-doc.cadn.net.cn

Spring AI 为智谱 AI(ZhiPuAI)聊天客户端提供 Spring Boot 自动配置。 要启用它,请将以下依赖项添加到项目的 Maven pom.xml 文件中:spring-doc.cadn.net.cn

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

请将以下内容添加到您的Gradle build.gradle 构建文件中。spring-doc.cadn.net.cn

dependencies {
    implementation 'org.springframework.ai:spring-ai-starter-model-zhipuai'
}
请参阅依赖管理部分,将Spring AI BOM添加到您的构建文件中。

聊天属性

重试属性

前缀 spring.ai.retry 用作属性前缀,允许您配置智谱 AI 聊天模型的重试机制。spring-doc.cadn.net.cn

<property> </property> <description> </description> 默认

spring.ai.retry.max-attemptsspring-doc.cadn.net.cn

最大重试尝试次数。spring-doc.cadn.net.cn

10spring-doc.cadn.net.cn

spring.ai.retry.backoff.initial-intervalspring-doc.cadn.net.cn

指数退避策略的初始睡眠时长。spring-doc.cadn.net.cn

2 秒。spring-doc.cadn.net.cn

spring.ai.retry.backoff.multiplierspring-doc.cadn.net.cn

重试间隔倍数。spring-doc.cadn.net.cn

5spring-doc.cadn.net.cn

spring.ai.retry.backoff.max-intervalspring-doc.cadn.net.cn

最大退避持续时间。spring-doc.cadn.net.cn

3 min.spring-doc.cadn.net.cn

spring.ai.retry.on-client-errorsspring-doc.cadn.net.cn

如果为假,则抛出一个NonTransientAiException,并且不尝试重试4xx客户端错误代码spring-doc.cadn.net.cn

falsespring-doc.cadn.net.cn

spring.ai.retry.exclude-on-http-codesspring-doc.cadn.net.cn

不应当触发重试的HTTP状态码列表(例如,抛出NonTransientAiException)。spring-doc.cadn.net.cn

<p>空内容</p>spring-doc.cadn.net.cn

spring.ai.retry.on-http-codesspring-doc.cadn.net.cn

应触发重试的HTTP状态码列表(例如,抛出TransientAiException)。spring-doc.cadn.net.cn

<p>空内容</p>spring-doc.cadn.net.cn

连接属性

前缀 spring.ai.zhiPu 用作属性前缀,让您能够连接到智谱 AI(ZhiPuAI)。spring-doc.cadn.net.cn

<property> </property> <description> </description> 默认

spring.ai.zhipuai.base-urlspring-doc.cadn.net.cn

连接的URLspring-doc.cadn.net.cn

open.bigmodel.cn/api/paasspring-doc.cadn.net.cn

spring.ai.zhipuai.api-keyspring-doc.cadn.net.cn

API密钥spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

配置属性

现在通过带有前缀spring.ai.model.chat的顶级属性来配置聊天自动配置的启用和禁用。spring-doc.cadn.net.cn

要启用,请设置 spring.ai.model.chat=zhipuai(默认已启用)spring-doc.cadn.net.cn

要禁用,请设置 spring.ai.model.chat=none(或任何不匹配 zhipuai 的值)spring-doc.cadn.net.cn

此更改是为了允许配置多个模型。spring-doc.cadn.net.cn

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

<property> </property> <description> </description> 默认

spring.ai.zhipuai.chat.enabled(已移除且不再生效)spring-doc.cadn.net.cn

启用智谱 AI 聊天模型。spring-doc.cadn.net.cn

truespring-doc.cadn.net.cn

spring.ai.model.chatspring-doc.cadn.net.cn

启用智谱 AI 聊天模型。spring-doc.cadn.net.cn

语雀 AIspring-doc.cadn.net.cn

spring.ai.zhipuai.chat.base-urlspring-doc.cadn.net.cn

可选地覆盖 spring.ai.zhipuai.base-url 以提供特定于聊天的 URLspring-doc.cadn.net.cn

open.bigmodel.cn/api/paasspring-doc.cadn.net.cn

spring.ai.zhipuai.chat.api-keyspring-doc.cadn.net.cn

可选地覆盖 spring.ai.zhipuai.api-key,以提供特定于聊天的 API 密钥。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.zhipuai.chat.options.modelspring-doc.cadn.net.cn

这是要使用的 ZhiPuAI 聊天模型spring-doc.cadn.net.cn

GLM-3-TurboGLM-3-TurboGLM-4GLM-4-AirGLM-4-AirXGLM-4-FlashGLM-4V 指向最新的模型版本)spring-doc.cadn.net.cn

spring.ai.zhipuai.chat.options.maxTokensspring-doc.cadn.net.cn

生成聊天补全时的最大token数。输入token和生成token的总长度受限于模型的上下文长度。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.zhipuai.chat.options.temperaturespring-doc.cadn.net.cn

要使用的采样温度,范围在 0 到 1 之间。较高的值(如 0.8)会使输出更随机,而较低的值(如 0.2)会使输出更集中且确定性更强。我们通常建议调整此参数或 top_p,但不要同时调整两者。spring-doc.cadn.net.cn

0.7spring-doc.cadn.net.cn

spring.ai.zhipuai.chat.options.topPspring-doc.cadn.net.cn

一种替代温度采样的方法,称为核采样(nucleus sampling),其中模型仅考虑累积概率达到 top_p 的Tokens结果。例如,0.1 表示只考虑累积概率前 10% 的Tokens。我们通常建议调整此参数或温度参数,但不要同时调整两者。spring-doc.cadn.net.cn

1.0spring-doc.cadn.net.cn

spring.ai.zhipuai.chat.options.stopspring-doc.cadn.net.cn

该模型会在生成指定的停止字符时停止,目前仅支持格式为<code>[spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.zhipuai.chat.options.userspring-doc.cadn.net.cn

代表最终用户的唯一标识符,可帮助智谱 AI 监控和检测滥用行为。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.zhipuai.chat.options.requestIdspring-doc.cadn.net.cn

该参数由客户端传递,必须确保唯一性。它用于区分每个请求的唯一标识符。如果客户端未提供,平台将默认生成它。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.zhipuai.chat.options.doSamplespring-doc.cadn.net.cn

当 do_sample 设置为 true 时,将启用采样策略。如果 do_sample 为 false,则采样策略参数 temperature 和 top_p 将不再生效。spring-doc.cadn.net.cn

truespring-doc.cadn.net.cn

spring.ai.zhipuai.chat.options.proxy-tool-callsspring-doc.cadn.net.cn

如果为 true,Spring AI 将不会在内部处理函数调用,而是将其代理给客户端。然后由客户端负责处理函数调用,将其分派到相应的函数,并返回结果。如果为 false(默认值),Spring AI 将在内部处理函数调用。仅适用于支持函数调用的聊天模型spring-doc.cadn.net.cn

falsespring-doc.cadn.net.cn

您可以为 ChatModel 实现覆盖通用的 spring.ai.zhipuai.base-urlspring.ai.zhipuai.api-key。 如果设置了 spring.ai.zhipuai.chat.base-urlspring.ai.zhipuai.chat.api-key 属性,它们的优先级将高于通用属性。 如果您希望针对不同的模型和不同的模型端点使用不同的智谱 AI(ZhiPuAI)账户,这将非常有用。
所有以spring.ai.zhipuai.chat.options开头的属性可以在运行时通过向Prompt调用添加请求特定的运行时选项来覆盖。

运行时选项

ZhiPuAiChatOptions.java 提供了模型配置,例如要使用的模型、温度、频率惩罚等。spring-doc.cadn.net.cn

启动时,可以使用ZhiPuAiChatModel(api, options)构造函数或spring.ai.zhipuai.chat.options.*属性来配置默认选项。spring-doc.cadn.net.cn

在运行时,您可以覆盖默认选项并通过向Prompt调用添加新的、针对请求的选项来实现。例如,要为特定请求覆盖默认模型和温度:spring-doc.cadn.net.cn

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#builder() 创建的可移植 ChatOptions 实例。

样本控制器

创建一个新的Spring Boot项目,并在pom(或gradle)依赖中添加spring-ai-starter-model-zhipuaispring-doc.cadn.net.cn

src/main/resources 目录下添加一个 application.properties 文件,以启用并配置智谱 AI(ZhiPuAi)聊天模型:spring-doc.cadn.net.cn

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类示例。spring-doc.cadn.net.cn

@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 实现了 ChatModelStreamingChatModel,并使用 低级 ZhiPuAiApi 客户端 连接到智谱 AI 服务。spring-doc.cadn.net.cn

将如下的spring-ai-zhipuai依赖添加到项目中Maven的pom.xml文件中:spring-doc.cadn.net.cn

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

请将以下内容添加到您的Gradle build.gradle 构建文件中。spring-doc.cadn.net.cn

dependencies {
    implementation 'org.springframework.ai:spring-ai-zhipuai'
}
请参阅依赖管理部分,将Spring AI BOM添加到您的构建文件中。

接下来,创建一个ZhiPuAiChatModel 并用于文本生成:spring-doc.cadn.net.cn

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."));

The ZhiPuAiChatOptions 提供了聊天请求的配置信息。 The ZhiPuAiChatOptions.Builder 是流畅选项构建器。spring-doc.cadn.net.cn

ZhiPuAiApi 低级客户端

ZhiPuAiApi 提供了用于 智谱 AI API 的轻量级 Java 客户端。spring-doc.cadn.net.cn

这里是如何通过程序方式使用API的一个简单示例:spring-doc.cadn.net.cn

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 以获取更多信息。spring-doc.cadn.net.cn

ZhiPuAiApi 示例