Anthropic 3 チャット

Anthropic Claude (英語) は、さまざまなアプリケーションで使用できる基礎的な AI モデルのファミリーです。開発者や企業は、API アクセスを活用して、Anthropic の AI インフラ (英語) 上に直接構築できます。

Spring AI は、同期およびストリーミングテキスト生成のために Anthropic メッセージング 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 Key の値に設定する必要があります。環境変数をエクスポートすることは、その構成プロパティを設定する 1 つの方法です。

export SPRING_AI_ANTHROPIC_API_KEY=<INSERT KEY HERE>

リポジトリと BOM の追加

Spring AI アーティファクトは、Spring マイルストーンおよびスナップショットリポジトリで公開されます。これらのリポジトリをビルドシステムに追加するには、リポジトリセクションを参照してください。

依存関係の管理を支援するために、Spring AI は BOM (部品表) を提供し、一貫したバージョンの Spring AI がプロジェクト全体で使用されるようにします。Spring AI BOM をビルドシステムに追加するには、"依存関係管理" セクションを参照してください。

自動構成

Spring AI は、Anthropic チャットクライアント用の Spring Boot 自動構成を提供します。これを有効にするには、プロジェクトの Maven pom.xml ファイルに次の依存関係を追加します。

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

または、Gradle build.gradle ビルドファイルに保存します。

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.chat は、Anthropic のチャットモデル実装を構成できるプロパティプレフィックスです。

プロパティ 説明 デフォルト

spring.ai.anthropic.chat.enabled

Anthropic チャットモデルを有効にします。

true

spring.ai.anthropic.chat.options.model

使用する Anthropic チャットモデルです。claude-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

生成される補完の見かけの創造性を制御するために使用するサンプリング温度。値を高くすると出力がよりランダムになり、値を低くすると結果がより集中的で決定的になります。これら 2 つの設定の相互作用を予測するのは難しいため、同じ完了リクエストに対して温度と 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 パラメーターを使用できます。モデルがカスタムシーケンスの 1 つに遭遇すると、レスポンス stop_reason 値は "stop_sequence" になり、レスポンス stop_sequence 値には一致する停止シーケンスが含まれます。

-

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

核サンプリングを使用します。核サンプリングでは、後続の各トークンのすべてのオプションの累積分布を確率の降順で計算し、top_p で指定された特定の確率に達するとそれをカットオフします。温度または top_p のいずれかを変更する必要がありますが、両方を変更することはできません。高度な使用例にのみ推奨されます。通常は温度のみを使用する必要があります。

-

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

後続の各トークンについて、上位 K 個のオプションからのみサンプリングします。「ロングテール」の低確率レスポンスを削除するために使用されます。技術的な詳細については、こちらを参照してください。高度な使用例にのみ推奨されます。通常は温度のみを使用する必要があります。

-

spring.ai.mistralai.chat.options.functions

単一のプロンプトリクエストでの関数呼び出しを有効にする、名前で識別される関数のリスト。これらの名前の関数は、functionCallbacks レジストリに存在する必要があります。

-

spring.ai.mistralai.chat.options.functionCallbacks

ChatModel に登録するための MistralAI ツール関数コールバック。

-

spring.ai.anthropic.chat.options というプレフィックスが付いたすべてのプロパティは、リクエスト固有のランタイムオプションを Prompt 呼び出しに追加することで実行時にオーバーライドできます。

ランタイムオプション

AnthropicChatOptions.java [GitHub] (英語) は、使用するモデル、温度、最大トークン数などのモデル構成を提供します。

起動時に、AnthropicChatModel(api, options) コンストラクターまたは spring.ai.anthropic.chat.options.* プロパティを使用してデフォルトのオプションを構成できます。

実行時に、新しいリクエスト固有のオプションを Prompt 呼び出しに追加することで、デフォルトのオプションをオーバーライドできます。たとえば、特定のリクエストのデフォルトのモデルと温度をオーバーライドするには、次のようにします。

ChatResponse response = chatModel.call(
    new Prompt(
        "Generate the names of 5 famous pirates.",
        AnthropicChatOptions.builder()
            .withModel("claude-2.1")
            .withTemperature(0.4)
        .build()
    ));
モデル固有の AnthropicChatOptions [GitHub] (英語) に加えて、ChatOptionsBuilder#builder() [GitHub] (英語) で作成されたポータブル ChatOptions [GitHub] (英語) インスタンスを使用できます。

関数呼び出し

AnthropicChatModel にカスタム Java 関数を登録し、Anthropic Claude モデルで、登録された関数の 1 つまたは複数を呼び出すための引数を含む JSON オブジェクトをインテリジェントに出力するように選択できます。これは、LLM 機能を外部ツールや API に接続するための強力な手法です。Anthropic 関数呼び出しの詳細については、こちらを参照してください。

マルチモーダル

マルチモダリティとは、テキスト、イメージ、音声、その他のデータ形式を含むさまざまなソースからの情報を同時に理解して処理するモデルの機能を指します。このパラダイムは、AI モデルの大幅な進歩を表しています。

現在、Anthropic、Claude 3 は、images の base64 ソース型と、image/jpegimage/pngimage/gifimage/webp メディア型をサポートしています。詳細については、ビジョンガイド (英語) を参照してください。

Spring AI の Message インターフェースは、メディア型を導入することでマルチモーダル AI モデルをサポートします。この型には、生のメディアデータに Spring の org.springframework.util.MimeType および java.lang.Object を使用して、メッセージ内のメディア添付ファイルに関するデータと情報が含まれます。

以下は、AnthropicChatModelIT.java [GitHub] (英語) から抽出された簡単なコード例で、ユーザーテキストとイメージの組み合わせを示しています。

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, imageData)));

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

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

入力イメージ multimodal.test.png :

Multimodal Test Image

「この写真に何が写っているか説明してください」というテキストメッセージとともに、次のようなレスポンスが生成されます。

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-opus-20240229
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", 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 chatModel.stream(prompt);
    }
}

手動構成

AnthropicChatModel [GitHub] (英語) は ChatModel と StreamingChatModel を実装し、低レベル 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(anthropicApi,
        AnthropicChatOptions.builder()
            .withModel("claude-3-opus-20240229")
            .withTemperature(0.4)
            .withMaxTokens(200)
        .build());

ChatResponse response = chatModel.call(
    new Prompt("Generate the names of 5 famous pirates."));

// Or with streaming responses
Flux<ChatResponse> response = chatModel.stream(
    new Prompt("Generate the names of 5 famous pirates."));

AnthropicChatOptions は、チャットリクエストの構成情報を提供します。AnthropicChatOptions.Builder は流れるようなオプションビルダーです。

低レベル AnthropicApi クライアント

AnthropicApi [GitHub] (英語) が提供するのは、Anthropic メッセージ API (英語) 用の軽量 Java クライアントです。

次のクラス図は、AnthropicApi チャットインターフェースと構成要素を示しています。

AnthropicApi Chat API Diagram

API をプログラムで使用する方法の簡単なスニペットを次に示します。

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

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

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

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

詳細については、AnthropicApi.java [GitHub] (英語) の JavaDoc を参照してください。

低レベル API の例