Anthropic 3 聊天模型

Anthropic Claude 是一系列基礎 AI 模型,可用於各種應用。開發者和企業可以利用其 API 訪問,直接在 Anthropic 的 AI 基礎設施 之上進行構建。

Spring AI 支援 Anthropic Messaging API,用於同步和流式文字生成。

Anthropic 的 Claude 模型也可透過 Amazon Bedrock Converse 獲得。Spring AI 也提供了專門的 Amazon Bedrock Converse Anthropic 客戶端實現。

先決條件

您需要在 Anthropic 門戶上建立一個 API 金鑰。在 Anthropic API 控制面板 上建立一個帳戶,然後在 獲取 API 金鑰 頁面上生成 API 金鑰。Spring AI 專案定義了一個名為 spring.ai.anthropic.api-key 的配置屬性,您應將其設定為從 anthropic.com 獲取的 API Key 的值。匯出環境變數是設定該配置屬性的一種方法。

export SPRING_AI_ANTHROPIC_API_KEY=<INSERT KEY HERE>

新增倉庫和 BOM

Spring AI 元件釋出在 Maven Central 和 Spring Snapshot 倉庫中。請參考 倉庫 部分將這些倉庫新增到您的構建系統中。

為了幫助進行依賴管理,Spring AI 提供了一個 BOM(物料清單),以確保整個專案中使用一致版本的 Spring AI。請參考 依賴管理 部分將 Spring AI BOM 新增到您的構建系統中。

自動配置

Spring AI 自動配置、Starter 模組的構件名稱發生了重大變化。請參考 升級注意事項 獲取更多資訊。

Spring AI 為 Anthropic 聊天客戶端提供了 Spring Boot 自動配置。要啟用它,請將以下依賴項新增到您的專案 Maven pom.xml 或 Gradle build.gradle 檔案中:

  • Maven

  • Gradle

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-model-anthropic</artifactId>
</dependency>
dependencies {
    implementation 'org.springframework.ai:spring-ai-starter-model-anthropic'
}
請參考 依賴管理 部分將 Spring AI BOM 新增到您的構建檔案中。

聊天屬性

重試屬性

字首 spring.ai.retry 用作屬性字首,允許您配置 Anthropic 聊天模型的重試機制。

屬性 描述 預設值

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)。

當前,重試策略不適用於流式 API。

連線屬性

字首 spring.ai.anthropic 用作屬性字首,允許您連線到 Anthropic。

屬性 描述 預設值

spring.ai.anthropic.base-url

連線的 URL

api.anthropic.com

spring.ai.anthropic.version

Anthropic API 版本

2023-06-01

spring.ai.anthropic.api-key

API 金鑰

-

spring.ai.anthropic.beta-version

啟用新/實驗性功能。如果設定為 max-tokens-3-5-sonnet-2024-07-15,輸出 token 限制會從 4096 增加到 8192 token(僅適用於 claude-3-5-sonnet)。

tools-2024-04-04

配置屬性

聊天自動配置的啟用和停用現在透過字首為 spring.ai.model.chat 的頂級屬性進行配置。

要啟用,將 spring.ai.model.chat=anthropic (預設啟用)

要停用,將 spring.ai.model.chat=none (或任何不匹配 anthropic 的值)

進行此更改是為了允許配置多個模型。

字首 spring.ai.anthropic.chat 是屬性字首,允許您為 Anthropic 配置聊天模型實現。

屬性 描述 預設值

spring.ai.anthropic.chat.enabled(已移除且不再有效)

啟用 Anthropic 聊天模型。

true

spring.ai.model.chat

啟用 Anthropic 聊天模型。

anthropic

spring.ai.anthropic.chat.options.model

要使用的 Anthropic 聊天模型。支援:claude-3-7-sonnet-latestclaude-3-5-sonnet-latestclaude-3-opus-20240229claude-3-sonnet-20240229claude-3-haiku-20240307

claude-3-7-sonnet-latest

spring.ai.anthropic.chat.options.temperature

用於控制生成完成內容表觀創造性的取樣溫度。值越高,輸出越隨機;值越低,結果越集中和確定。不建議在同一完成請求中同時修改 temperature 和 top_p,因為這兩個設定的相互作用難以預測。

0.8

spring.ai.anthropic.chat.options.max-tokens

在聊天完成中生成的最大 token 數。輸入 token 和生成 token 的總長度受模型上下文長度限制。

500

spring.ai.anthropic.chat.options.stop-sequence

會導致模型停止生成的自定義文字序列。我們的模型通常會在自然完成其回合時停止,這將導致響應的 stop_reason 為 "end_turn"。如果您希望模型在遇到自定義文字字串時停止生成,可以使用 stop_sequences 引數。如果模型遇到其中一個自定義序列,響應的 stop_reason 值將為 "stop_sequence",並且響應的 stop_sequence 值將包含匹配的停止序列。

-

spring.ai.anthropic.chat.options.top-p

使用核取樣。在核取樣中,我們按機率遞減的順序計算每個後續 token 的所有選項的累積分佈,並在達到 top_p 指定的特定機率時截斷。您應該只更改 temperature 或 top_p 中的一個,而不是同時更改兩者。僅推薦用於高階用例。通常只需要使用 temperature。

-

spring.ai.anthropic.chat.options.top-k

僅從每個後續 token 的前 K 個選項中進行取樣。用於去除“長尾”低機率響應。在此瞭解更多技術細節。僅推薦用於高階用例。通常只需要使用 temperature。

-

spring.ai.anthropic.chat.options.toolNames

要在一個提示請求中啟用工具呼叫的工具列表,透過其名稱標識。具有這些名稱的工具必須存在於 toolCallbacks 登錄檔中。

-

spring.ai.anthropic.chat.options.toolCallbacks

要向 ChatModel 註冊的工具回撥。

-

spring.ai.anthropic.chat.options.internal-tool-execution-enabled

如果為 false,Spring AI 將不會在內部處理工具呼叫,而是將它們代理給客戶端。然後由客戶端負責處理工具呼叫,將其分派給適當的函式並返回結果。如果為 true(預設值),Spring AI 將在內部處理函式呼叫。僅適用於支援函式呼叫的聊天模型。

true

(已棄用 - 由 toolNames 替代) spring.ai.anthropic.chat.options.functions

要在一個提示請求中啟用函式呼叫的函式列表,透過其名稱標識。具有這些名稱的函式必須存在於 functionCallbacks 登錄檔中。

-

(已棄用 - 由 toolCallbacks 替代) spring.ai.anthropic.chat.options.functionCallbacks

要向 ChatModel 註冊的工具函式回撥。

-

(已棄用 - 由 negated internal-tool-execution-enabled 替代) spring.ai.anthropic.chat.options.proxy-tool-calls

如果為 true,Spring AI 將不會在內部處理函式呼叫,而是將它們代理給客戶端。然後由客戶端負責處理函式呼叫,將其分派給適當的函式並返回結果。如果為 false(預設值),Spring AI 將在內部處理函式呼叫。僅適用於支援函式呼叫的聊天模型。

false

spring.ai.anthropic.chat.options.http-headers

要新增到聊天完成請求中的可選 HTTP 頭。

-

所有帶有 spring.ai.anthropic.chat.options 字首的屬性都可以在執行時透過向 Prompt 呼叫新增特定於請求的 執行時選項 來覆蓋。

執行時選項

AnthropicChatOptions.java 提供了模型配置,例如要使用的模型、溫度、最大 token 數等。

啟動時,可以使用 AnthropicChatModel(api, options) 建構函式或 spring.ai.anthropic.chat.options.* 屬性配置預設選項。

執行時,您可以透過向 Prompt 呼叫新增新的、特定於請求的選項來覆蓋預設選項。例如,為一個特定請求覆蓋預設模型和溫度:

ChatResponse response = chatModel.call(
    new Prompt(
        "Generate the names of 5 famous pirates.",
        AnthropicChatOptions.builder()
            .model("claude-3-7-sonnet-latest")
            .temperature(0.4)
        .build()
    ));
除了模型特定的 AnthropicChatOptions,您還可以使用可移植的 ChatOptions 例項,透過 ChatOptionsBuilder#builder() 建立。

工具/函式呼叫

您可以向 AnthropicChatModel 註冊自定義 Java 工具,並讓 Anthropic Claude 模型智慧地選擇輸出一個包含呼叫一個或多個已註冊函式所需的引數的 JSON 物件。這是一種將 LLM 能力與外部工具和 API 連線起來的強大技術。閱讀更多關於 Anthropic 函式呼叫 的資訊。

多模態

多模態是指模型同時理解和處理來自各種來源資訊的能力,包括文字、PDF、影像、資料格式。

影像

目前,Anthropic Claude 3 支援影像的 base64 源型別,以及 image/jpegimage/pngimage/gifimage/webp 媒體型別。更多資訊請檢視 Vision guide。Anthropic Claude 3.5 Sonnet 還支援 application/pdf 檔案的 pdf 源型別。

Spring AI 的 Message 介面透過引入 Media 型別來支援多模態 AI 模型。此型別包含訊息中媒體附件的資料和資訊,使用 Spring 的 org.springframework.util.MimeType 和一個用於原始媒體資料的 java.lang.Object

以下是一個從 AnthropicChatModelIT.java 提取的簡單程式碼示例,演示了使用者文字與影像的組合。

var imageData = new ClassPathResource("/multimodal.test.png");

var userMessage = new UserMessage("Explain what do you see on this picture?",
        List.of(new Media(MimeTypeUtils.IMAGE_PNG, this.imageData)));

ChatResponse response = chatModel.call(new Prompt(List.of(this.userMessage)));

logger.info(response.getResult().getOutput().getContent());

它接受 multimodal.test.png 影像作為輸入

Multimodal Test Image

以及文字訊息 "Explain what do you see on this picture?",並生成類似以下內容的響應:

The image shows a close-up view of a wire fruit basket containing several pieces of fruit.
...

PDF

從 Sonnet 3.5 開始,提供 PDF 支援(測試版)。使用 application/pdf 媒體型別將 PDF 檔案附加到訊息中:

var pdfData = new ClassPathResource("/spring-ai-reference-overview.pdf");

var userMessage = new UserMessage(
        "You are a very professional document summarization specialist. Please summarize the given document.",
        List.of(new Media(new MimeType("application", "pdf"), pdfData)));

var response = this.chatModel.call(new Prompt(List.of(userMessage)));

示例控制器

建立 一個新的 Spring Boot 專案,並將 spring-ai-starter-model-anthropic 新增到您的 pom (或 gradle) 依賴項中。

src/main/resources 目錄下新增一個 application.properties 檔案,以啟用和配置 Anthropic 聊天模型:

spring.ai.anthropic.api-key=YOUR_API_KEY
spring.ai.anthropic.chat.options.model=claude-3-5-sonnet-latest
spring.ai.anthropic.chat.options.temperature=0.7
spring.ai.anthropic.chat.options.max-tokens=450
用您的 Anthropic 憑據替換 api-key

這將建立一個 AnthropicChatModel 實現,您可以將其注入到您的類中。這是一個簡單的 @Controller 類的示例,它使用聊天模型進行文字生成。

@RestController
public class ChatController {

    private final AnthropicChatModel chatModel;

    @Autowired
    public ChatController(AnthropicChatModel 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) {
        Prompt prompt = new Prompt(new UserMessage(message));
        return this.chatModel.stream(prompt);
    }
}

手動配置

AnthropicChatModel 實現了 ChatModelStreamingChatModel 介面,並使用 低階 AnthropicApi 客戶端 連線到 Anthropic 服務。

spring-ai-anthropic 依賴項新增到您的專案 Maven pom.xml 檔案中:

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

或者新增到您的 Gradle build.gradle 構建檔案中。

dependencies {
    implementation 'org.springframework.ai:spring-ai-anthropic'
}
請參考 依賴管理 部分將 Spring AI BOM 新增到您的構建檔案中。

接下來,建立一個 AnthropicChatModel 並將其用於文字生成:

var anthropicApi = new AnthropicApi(System.getenv("ANTHROPIC_API_KEY"));

var chatModel = new AnthropicChatModel(this.anthropicApi,
        AnthropicChatOptions.builder()
            .model("claude-3-opus-20240229")
            .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> response = this.chatModel.stream(
    new Prompt("Generate the names of 5 famous pirates."));

AnthropicChatOptions 提供聊天請求的配置資訊。AnthropicChatOptions.Builder 是流式選項構建器。

低階 AnthropicApi 客戶端

AnthropicApiAnthropic Message API 的輕量級 Java 客戶端。

以下類圖展示了 AnthropicApi 聊天介面和構建塊:

AnthropicApi Chat API Diagram
AnthropicApi Event Model

以下是一個如何透過程式設計方式使用 API 的簡單片段:

AnthropicApi anthropicApi =
    new AnthropicApi(System.getenv("ANTHROPIC_API_KEY"));

AnthropicMessage chatCompletionMessage = new AnthropicMessage(
        List.of(new ContentBlock("Tell me a Joke?")), Role.USER);

// Sync request
ResponseEntity<ChatCompletionResponse> response = this.anthropicApi
    .chatCompletionEntity(new ChatCompletionRequest(AnthropicApi.ChatModel.CLAUDE_3_OPUS.getValue(),
            List.of(this.chatCompletionMessage), null, 100, 0.8, false));

// Streaming request
Flux<StreamResponse> response = this.anthropicApi
    .chatCompletionStream(new ChatCompletionRequest(AnthropicApi.ChatModel.CLAUDE_3_OPUS.getValue(),
            List.of(this.chatCompletionMessage), null, 100, 0.8, true));

請查閱 AnthropicApi.java 的 JavaDoc 以獲取更多資訊。

低階 API 示例