Anthropic 3 聊天

Anthropic Claude 是一系列基礎 AI 模型,可用於各種應用程式。對於開發人員和企業,您可以利用 API 存取權,直接在 Anthropic 的 AI 基礎架構之上進行建構。

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

Anthropic 的 Claude 模型也可透過 Amazon Bedrock 取得。Spring AI 也提供專用的 Amazon Bedrock Anthropic 用戶端實作。

先決條件

您需要在 Anthropic 入口網站上建立 API 金鑰。在 Anthropic API 儀表板建立帳戶,並在取得 API 金鑰頁面上產生 API 金鑰。Spring AI 專案定義了一個名為 spring.ai.anthropic.api-key 的組態屬性,您應該將其設定為從 anthropic.com 取得的 API 金鑰值。匯出環境變數是設定該組態屬性的一種方法

export SPRING_AI_ANTHROPIC_API_KEY=<INSERT KEY HERE>

新增儲存庫和 BOM

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

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

自動組態

Spring AI 為 Anthropic Chat Client 提供 Spring Boot 自動組態。若要啟用它,請將以下相依性新增至專案的 Maven pom.xml 或 Gradle build.gradle 檔案

  • Maven

  • Gradle

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-anthropic-spring-boot-starter</artifactId>
</dependency>
dependencies {
    implementation 'org.springframework.ai:spring-ai-anthropic-spring-boot-starter'
}
請參閱相依性管理章節,將 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,則輸出符記限制會從 4096 增加到 8192 個符記(僅適用於 claude-3-5-sonnet)。

tools-2024-04-04

組態屬性

前綴詞 spring.ai.anthropic.chat 是屬性前綴詞,讓您可以為 Anthropic 組態聊天模型實作。

屬性 描述 預設值

spring.ai.anthropic.chat.enabled

啟用 Anthropic 聊天模型。

true

spring.ai.anthropic.chat.options.model

這是要使用的 Anthropic 聊天模型。支援:claude-3-5-sonnet-20241022claude-3-opus-20240229claude-3-sonnet-20240229claude-3-haiku-20240307 和舊版 claude-2.1claude-2.0claude-instant-1.2 模型。

claude-3-opus-20240229

spring.ai.anthropic.chat.options.temperature

要使用的取樣溫度,可控制生成完成的表面創造力。較高的值會使輸出更隨機,而較低的值會使結果更集中且具決定性。不建議針對相同的完成要求修改 temperature 和 top_p,因為這兩個設定的互動難以預測。

0.8

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

聊天完成中要生成的最大符記數。輸入符記和生成符記的總長度受模型內容長度限制。

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

使用核心取樣。在核心取樣中,我們會計算所有選項的累積分佈,以機率遞減順序排列每個後續符記,並在達到 top_p 指定的特定機率時將其截斷。您應該變更 temperature 或 top_p,但不要同時變更兩者。建議僅用於進階使用案例。您通常只需要使用 temperature。

-

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

僅從每個後續符記的前 K 個選項中取樣。用於移除「長尾」低機率回應。在此處深入瞭解技術細節。建議僅用於進階使用案例。您通常只需要使用 temperature。

-

spring.ai.anthropic.chat.options.functions

函數清單,依其名稱識別,以在單一提示要求中啟用函數呼叫。具有這些名稱的函數必須存在於 functionCallbacks 登錄檔中。

-

spring.ai.anthropic.chat.options.functionCallbacks

要向 ChatModel 註冊的工具函數回呼。

-

spring.ai.anthropic.chat.options.proxy-tool-calls

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

false

所有以 spring.ai.anthropic.chat.options 為前綴的屬性都可以在執行階段覆寫,方法是將要求特定的執行階段選項新增至 Prompt 呼叫。

執行階段選項

AnthropicChatOptions.java 提供模型組態,例如要使用的模型、temperature、最大符記計數等。

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

在執行階段,您可以透過將新的、要求特定的選項新增至 Prompt 呼叫來覆寫預設選項。例如,針對特定要求覆寫預設模型和 temperature

ChatResponse response = chatModel.call(
    new Prompt(
        "Generate the names of 5 famous pirates.",
        AnthropicChatOptions.builder()
            .withModel("claude-2.1")
            .withTemperature(0.4)
        .build()
    ));
除了模型特定的 AnthropicChatOptions 之外,您還可以使用可攜式 ChatOptions 實例,使用 ChatOptionsBuilder#builder() 建立。

函數呼叫

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

多模態

多模態是指模型同時理解和處理來自各種來源(包括文字、影像、音訊和其他資料格式)資訊的能力。這種範例代表 AI 模型的一項重大進展。

目前,Anthropic Claude 3 支援 imagesbase64 來源類型,以及 image/jpegimage/pngimage/gifimage/webp 媒體類型。查看視覺指南以取得更多資訊。

Spring AI 的 Message 介面透過引入媒體類型來支援多模態 AI 模型。此類型包含訊息中媒體附件的資料和資訊,使用 Spring 的 org.springframework.util.MimeTypejava.lang.Object 作為原始媒體資料。

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

byte[] imageData = new ClassPathResource("/multimodal.test.png").getContentAsByteArray();

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.
The basket appears to be made of thin metal wires formed into a round shape with an elevated handle.

Inside the basket, there are a few yellow bananas and a couple of red apples or possibly tomatoes.
The vibrant colors of the fruit contrast nicely against the metallic tones of the wire basket.

The shallow depth of field in the photograph puts the focus squarely on the fruit in the foreground, while the basket handle extending upwards is slightly blurred, creating a pleasing bokeh effect in the background.

The composition and lighting give the image a clean, minimalist aesthetic that highlights the natural beauty and freshness of the fruit displayed in this elegant wire basket.

範例控制器

建立新的 Spring Boot 專案,並將 spring-ai-anthropic-spring-boot-starter 新增至您的 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-20241022
spring.ai.anthropic.chat.options.temperature=0.7
spring.ai.anthropic.chat.options.max-tokens=450
api-key 替換為您的 Anthropic 認證。

這將建立一個 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()
            .withModel("claude-3-opus-20240229")
            .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> 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 範例

  • AnthropicApiIT.java 測試提供了一些關於如何使用輕量級程式庫的一般範例。