ZhiPu AI 聊天

Spring AI 支援來自 ZhiPu AI 的各種 AI 語言模型。您可以與 ZhiPu AI 語言模型互動,並基於 ZhiPuAI 模型建立多語言對話式助理。

先決條件

您需要使用 ZhiPuAI 建立 API,才能存取 ZhiPu AI 語言模型。

ZhiPu AI 註冊頁面 建立帳戶,並在 API 金鑰頁面 上產生權杖。 Spring AI 專案定義了一個名為 spring.ai.zhipuai.api-key 的組態屬性,您應該將其設定為從 API 金鑰頁面 取得的 API 金鑰 值。匯出環境變數是設定該組態屬性的一種方法

export SPRING_AI_ZHIPU_AI_API_KEY=<INSERT KEY HERE>

新增儲存庫和 BOM

Spring AI 構件發佈在 Spring Milestone 和 Snapshot 儲存庫中。請參閱 儲存庫 章節,將這些儲存庫新增到您的建置系統。

為了協助進行相依性管理,Spring AI 提供了 BOM(物料清單),以確保在整個專案中使用一致版本的 Spring AI。請參閱 相依性管理 章節,將 Spring AI BOM 新增到您的建置系統。

自動組態

Spring AI 為 ZhiPuAI 聊天用戶端提供 Spring Boot 自動組態。若要啟用它,請將以下相依性新增到您專案的 Maven pom.xml 檔案

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

或您的 Gradle build.gradle 建置檔案。

dependencies {
    implementation 'org.springframework.ai:spring-ai-zhipuai-spring-boot-starter'
}
請參閱 相依性管理 章節,將 Spring AI BOM 新增到您的建置檔案。

聊天屬性

重試屬性

字首 spring.ai.retry 用作屬性字首,可讓您設定 ZhiPu 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 用作屬性字首,可讓您連線至 ZhiPuAI。

屬性 描述 預設值

spring.ai.zhipuai.base-url

要連線的 URL

open.bigmodel.cn/api/paas

spring.ai.zhipuai.api-key

API 金鑰

-

組態屬性

字首 spring.ai.zhipuai.chat 是屬性字首,可讓您設定 ZhiPuAI 的聊天模型實作。

屬性 描述 預設值

spring.ai.zhipuai.chat.enabled

啟用 ZhiPuAI 聊天模型。

true

spring.ai.zhipuai.chat.base-url

選擇性覆寫 spring.ai.zhipuai.base-url 以提供聊天專用 URL

open.bigmodel.cn/api/paas

spring.ai.zhipuai.chat.api-key

選擇性覆寫 spring.ai.zhipuai.api-key 以提供聊天專用 API 金鑰

-

spring.ai.zhipuai.chat.options.model

這是要使用的 ZhiPuAI 聊天模型

GLM-3-TurboGLM-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

代表您的終端使用者的唯一識別碼,可以協助 ZhiPuAI 監控和偵測濫用行為。

-

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

您可以覆寫 ChatModel 實作的通用 spring.ai.zhipuai.base-urlspring.ai.zhipuai.api-key。如果設定了 spring.ai.zhipuai.chat.base-urlspring.ai.zhipuai.chat.api-key 屬性,則它們優先於通用屬性。如果您想要對不同的模型和不同的模型端點使用不同的 ZhiPuAI 帳戶,這會很有用。
所有以 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()
            .withModel(ZhiPuAiApi.ChatModel.GLM_3_Turbo.getValue())
            .withTemperature(0.5)
        .build()
    ));
除了模型特定的 ZhiPuAiChatOptions 之外,您還可以使用的可攜式 ChatOptions 實例,使用 ChatOptionsBuilder#builder() 建立。

範例控制器

建立 新的 Spring Boot 專案,並將 spring-ai-zhipuai-spring-boot-starter 新增到您的 pom(或 gradle)相依性。

src/main/resources 目錄下新增 application.properties 檔案,以啟用和組態 ZhiPuAi 聊天模型

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 替換為您的 ZhiPuAI 憑證。

這將建立一個 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 實作了 ChatModelStreamingChatModel,並使用 底層 ZhiPuAiApi 用戶端 連線到 ZhiPuAI 服務。

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()
                .withModel(ZhiPuAiApi.ChatModel.GLM_3_Turbo.getValue())
                .withTemperature(0.4)
                .withMaxTokens(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 提供適用於 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 測試提供了一些關於如何使用輕量級程式庫的通用範例。