このバージョンはまだ開発中であり、まだ安定しているとは考えられていません。最新のスナップショットバージョンについては、Spring AI 1.0.3 を使用してください。 |
Anthropic チャット
Anthropic Claude (英語) は、さまざまなアプリケーションで使用できる基礎的な AI モデルのファミリーです。開発者や企業は、API アクセスを活用して、Anthropic の AI インフラ (英語) 上に直接構築できます。
Spring AI は、同期およびストリーミングテキスト生成のために Anthropic メッセージング API (英語) をサポートします。
Anthropic の Claude モデルは、Amazon Bedrock Converse を通じても利用できます。Spring AI は専用の Amazon Bedrock コンバース Anthropic クライアント実装も提供します。 |
前提条件
Anthropic ポータルで API キーを作成する必要があります。
Anthropic API ダッシュボード (英語) でアカウントを作成し、API キーを取得する (英語) ページで API キーを生成します。
Spring AI プロジェクトは、spring.ai.anthropic.api-key
という名前の構成プロパティを定義します。このプロパティは、anthropic.com から取得した API Key
の値に設定する必要があります。
この構成プロパティは、application.properties
ファイルで設定できます。
spring.ai.anthropic.api-key=<your-anthropic-api-key>
API キーなどの機密情報を扱う際のセキュリティを強化するために、Spring 式言語 (SpEL) を使用してカスタム環境変数を参照できます。
# In application.yml
spring:
ai:
anthropic:
api-key: ${ANTHROPIC_API_KEY}
# In your environment or .env file
export ANTHROPIC_API_KEY=<your-anthropic-api-key>
この構成は、アプリケーションコード内でプログラム的に取得することもできます。
// Retrieve API key from a secure source or environment variable
String apiKey = System.getenv("ANTHROPIC_API_KEY");
リポジトリと BOM の追加
Spring AI アーティファクトは、Maven Central リポジトリと Spring スナップショットリポジトリに公開されています。これらのリポジトリをビルドシステムに追加するには、アーティファクトリポジトリセクションを参照してください。
依存関係の管理を支援するために、Spring AI は BOM (部品表) を提供し、一貫したバージョンの Spring AI がプロジェクト全体で使用されるようにします。Spring AI BOM をビルドシステムに追加するには、"依存関係管理" セクションを参照してください。
自動構成
Spring AI 自動構成、スターターモジュールのアーティファクト名に大きな変更がありました。詳細については、アップグレードノートを参照してください。 |
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 をスローし、 | 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 | |
spring.ai.anthropic.completions-path | ベース URL に追加するパス。 |
|
spring.ai.anthropic.version | Anthropic API バージョン | 2023-06-01 |
spring.ai.anthropic.api-key | API キー | - |
spring.ai.anthropic.beta-version | 新しい / 実験的な機能を有効にします。 |
|
プロパティの構成
チャットの自動構成の有効化と無効化は、プレフィックス 有効にするには、spring.ai.model.chat=anthropic (デフォルトで有効になっています) 無効にするには、spring.ai.model.chat=none (または人類学的に一致しない値) この変更は、複数のモデルの構成を可能にするために行われます。 |
プレフィックス spring.ai.anthropic.chat
は、Anthropic のチャットモデル実装を構成できるプロパティプレフィックスです。
プロパティ | 説明 | デフォルト |
---|---|---|
spring.ai.anthropic.chat.enabled (削除され、無効になりました) | Anthropic チャットモデルを有効にします。 | true |
spring.ai.model.chat | Anthropic チャットモデルを有効にします。 | 人類的な |
spring.ai.anthropic.chat.options.model | 使用する Anthropic チャットモデルです。サポート: |
|
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.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 |
( 非推奨 - | 単一のプロンプトリクエストで関数呼び出しを有効にするために、名前で識別される関数のリスト。これらの名前を持つ関数は、functionCallbacks レジストリに存在する必要があります。 | - |
( 非推奨 - | ChatModel に登録するツール関数コールバック。 | - |
( 非推奨 - 否定形の | true の場合、Spring AI は関数呼び出しを内部で処理せず、クライアントにプロキシします。関数呼び出しを処理し、適切な関数にディスパッチして、結果を返すのはクライアントの責任です。false (デフォルト) の場合、Spring AI は関数呼び出しを内部で処理します。関数呼び出しをサポートするチャットモデルにのみ適用されます。 | false |
spring.ai.anthropic.chat.options.http-headers | チャット補完リクエストに追加されるオプションの HTTP ヘッダー。 | - |
モデルエイリアスの最新リストとその説明については、公式の Anthropic モデルエイリアスのドキュメント (英語) を参照してください。 |
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()
.model("claude-3-7-sonnet-latest")
.temperature(0.4)
.build()
));
モデル固有の AnthropicChatOptions [GitHub] (英語) に加えて、ChatOptions#builder() [GitHub] (英語) で作成されたポータブル ChatOptions [GitHub] (英語) インスタンスを使用できます。 |
プロンプトキャッシュ
Anthropic’s prompt caching feature (英語) allows you to cache frequently used prompts to reduce costs and improve response times for repeated interactions. When you cache a prompt, subsequent identical requests can reuse the cached content, significantly reducing the number of input tokens processed.
対応モデル プロンプトキャッシュは現在、Claude Opus 4、Claude Sonnet 4、Claude Sonnet 3.7、Claude Sonnet 3.5、Claude Haiku 3.5、Claude Haiku 3、および Claude Opus 3 でサポートされています。 トークン要件 異なるモデルには、キャッシュの有効性に関する最小トークンしきい値が異なります。- Claude Sonnet 4: 1024+ トークン - Claude Haiku モデル: 2048+ トークン - その他のモデル: 1024+ トークン |
キャッシュ戦略
Spring AI は、AnthropicCacheStrategy
列挙型を通じて戦略的なキャッシュ配置を提供します。
NONE
: プロンプトのキャッシュを完全に無効にするSYSTEM_ONLY
: システムメッセージの内容のみをキャッシュしますSYSTEM_AND_TOOLS
: Caches system message and the last tool definitionCONVERSATION_HISTORY
: Caches conversation history in chat memory scenarios
This strategic approach ensures optimal cache breakpoint placement while staying within Anthropic’s 4-breakpoint limit.
Enabling Prompt Caching
Enable prompt caching by setting cacheOptions
on AnthropicChatOptions
and choosing a strategy
.
System-Only Caching
// Cache system message content
ChatResponse response = chatModel.call(
new Prompt(
List.of(
new SystemMessage("You are a helpful AI assistant with extensive knowledge..."),
new UserMessage("What is machine learning?")
),
AnthropicChatOptions.builder()
.model("claude-sonnet-4")
.cacheOptions(AnthropicCacheOptions.builder()
.strategy(AnthropicCacheStrategy.SYSTEM_ONLY)
.build())
.maxTokens(500)
.build()
)
);
System and Tools Caching
// Cache system message and the last tool definition
ChatResponse response = chatModel.call(
new Prompt(
List.of(
new SystemMessage("You are a weather analysis assistant..."),
new UserMessage("What's the weather like in San Francisco?")
),
AnthropicChatOptions.builder()
.model("claude-sonnet-4")
.cacheOptions(AnthropicCacheOptions.builder()
.strategy(AnthropicCacheStrategy.SYSTEM_AND_TOOLS)
.build())
.toolCallbacks(weatherToolCallback)
.maxTokens(500)
.build()
)
);
Conversation History Caching
// Cache conversation history with ChatClient and memory (latest user question is not cached)
ChatClient chatClient = ChatClient.builder(chatModel)
.defaultSystem("You are a personalized career counselor...")
.defaultAdvisors(MessageChatMemoryAdvisor.builder(chatMemory)
.conversationId(conversationId)
.build())
.build();
String response = chatClient.prompt()
.user("What career advice would you give me?")
.options(AnthropicChatOptions.builder()
.model("claude-sonnet-4")
.cacheOptions(AnthropicCacheOptions.builder()
.strategy(AnthropicCacheStrategy.CONVERSATION_HISTORY)
.build())
.maxTokens(500)
.build())
.call()
.content();
Using ChatClient Fluent API
String response = ChatClient.create(chatModel)
.prompt()
.system("You are an expert document analyst...")
.user("Analyze this large document: " + document)
.options(AnthropicChatOptions.builder()
.model("claude-sonnet-4")
.cacheOptions(AnthropicCacheOptions.builder()
.strategy(AnthropicCacheStrategy.SYSTEM_ONLY)
.build())
.build())
.call()
.content();
Advanced Caching Options
Per-Message TTL (5m or 1h)
By default, cached content uses a 5-minute TTL. You can set a 1-hour TTL for specific message types. When 1-hour TTL is used, Spring AI automatically sets the required Anthropic beta header.
ChatResponse response = chatModel.call(
new Prompt(
List.of(new SystemMessage(largeSystemPrompt)),
AnthropicChatOptions.builder()
.model("claude-sonnet-4")
.cacheOptions(AnthropicCacheOptions.builder()
.strategy(AnthropicCacheStrategy.SYSTEM_ONLY)
.messageTypeTtl(MessageType.SYSTEM, AnthropicCacheTtl.ONE_HOUR)
.build())
.maxTokens(500)
.build()
)
);
Extended TTL uses Anthropic beta feature extended-cache-ttl-2025-04-11 . |
Cache Eligibility Filters
Control when cache breakpoints are used by setting minimum content lengths and an optional token-based length function:
AnthropicCacheOptions cache = AnthropicCacheOptions.builder()
.strategy(AnthropicCacheStrategy.CONVERSATION_HISTORY)
.messageTypeMinContentLength(MessageType.SYSTEM, 1024)
.messageTypeMinContentLength(MessageType.USER, 1024)
.messageTypeMinContentLength(MessageType.ASSISTANT, 1024)
.contentLengthFunction(text -> MyTokenCounter.count(text))
.build();
ChatResponse response = chatModel.call(
new Prompt(
List.of(/* messages */),
AnthropicChatOptions.builder()
.model("claude-sonnet-4")
.cacheOptions(cache)
.build()
)
);
Tool Definitions are always considered for caching if SYSTEM_AND_TOOLS strategy is used, regardless of content length. |
使用例
Here’s a complete example demonstrating prompt caching with cost tracking:
// Create system content that will be reused multiple times
String largeSystemPrompt = "You are an expert software architect specializing in distributed systems...";
// First request - creates cache
ChatResponse firstResponse = chatModel.call(
new Prompt(
List.of(
new SystemMessage(largeSystemPrompt),
new UserMessage("What is microservices architecture?")
),
AnthropicChatOptions.builder()
.model("claude-sonnet-4")
.cacheOptions(AnthropicCacheOptions.builder()
.strategy(AnthropicCacheStrategy.SYSTEM_ONLY)
.build())
.maxTokens(500)
.build()
)
);
// Access cache-related token usage
AnthropicApi.Usage firstUsage = (AnthropicApi.Usage) firstResponse.getMetadata()
.getUsage().getNativeUsage();
System.out.println("Cache creation tokens: " + firstUsage.cacheCreationInputTokens());
System.out.println("Cache read tokens: " + firstUsage.cacheReadInputTokens());
// Second request with same system prompt - reads from cache
ChatResponse secondResponse = chatModel.call(
new Prompt(
List.of(
new SystemMessage(largeSystemPrompt),
new UserMessage("What are the benefits of event sourcing?")
),
AnthropicChatOptions.builder()
.model("claude-sonnet-4")
.cacheOptions(AnthropicCacheOptions.builder()
.strategy(AnthropicCacheStrategy.SYSTEM_ONLY)
.build())
.maxTokens(500)
.build()
)
);
AnthropicApi.Usage secondUsage = (AnthropicApi.Usage) secondResponse.getMetadata()
.getUsage().getNativeUsage();
System.out.println("Cache creation tokens: " + secondUsage.cacheCreationInputTokens()); // Should be 0
System.out.println("Cache read tokens: " + secondUsage.cacheReadInputTokens()); // Should be > 0
Token Usage Tracking
The Usage
record provides detailed information about cache-related token consumption. To access Anthropic-specific cache metrics, use the getNativeUsage()
method:
AnthropicApi.Usage usage = (AnthropicApi.Usage) response.getMetadata()
.getUsage().getNativeUsage();
Cache-specific metrics include:
cacheCreationInputTokens()
: Returns the number of tokens used when creating a cache entrycacheReadInputTokens()
: Returns the number of tokens read from an existing cache entry
When you first send a cached prompt: - cacheCreationInputTokens()
will be greater than 0 - cacheReadInputTokens()
will be 0
When you send the same cached prompt again: - cacheCreationInputTokens()
will be 0 - cacheReadInputTokens()
will be greater than 0
Real-World Use Cases
Legal Document Analysis
Analyze large legal contracts or compliance documents efficiently by caching document content across multiple questions:
// Load a legal contract (PDF or text)
String legalContract = loadDocument("merger-agreement.pdf"); // ~3000 tokens
// System prompt with legal expertise
String legalSystemPrompt = "You are an expert legal analyst specializing in corporate law. " +
"Analyze the following contract and provide precise answers about terms, obligations, and risks: " +
legalContract;
// First analysis - creates cache
ChatResponse riskAnalysis = chatModel.call(
new Prompt(
List.of(
new SystemMessage(legalSystemPrompt),
new UserMessage("What are the key termination clauses and associated penalties?")
),
AnthropicChatOptions.builder()
.model("claude-sonnet-4")
.cacheOptions(AnthropicCacheOptions.builder()
.strategy(AnthropicCacheStrategy.SYSTEM_ONLY)
.build())
.maxTokens(1000)
.build()
)
);
// Subsequent questions reuse cached document - 90% cost savings
ChatResponse obligationAnalysis = chatModel.call(
new Prompt(
List.of(
new SystemMessage(legalSystemPrompt), // Same content - cache hit
new UserMessage("List all financial obligations and payment schedules.")
),
AnthropicChatOptions.builder()
.model("claude-sonnet-4")
.cacheOptions(AnthropicCacheOptions.builder()
.strategy(AnthropicCacheStrategy.SYSTEM_ONLY)
.build())
.maxTokens(1000)
.build()
)
);
Batch Code Review
Process multiple code files with consistent review criteria while caching the review guidelines:
// Define comprehensive code review guidelines
String reviewGuidelines = """
You are a senior software engineer conducting code reviews. Apply these criteria:
- Security vulnerabilities and best practices
- Performance optimizations and memory usage
- Code maintainability and readability
- Testing coverage and edge cases
- Design patterns and architecture compliance
""";
List<String> codeFiles = Arrays.asList(
"UserService.java", "PaymentController.java", "SecurityConfig.java"
);
List<String> reviews = new ArrayList<>();
for (String filename : codeFiles) {
String sourceCode = loadSourceFile(filename);
ChatResponse review = chatModel.call(
new Prompt(
List.of(
new SystemMessage(reviewGuidelines), // Cached across all reviews
new UserMessage("Review this " + filename + " code:\n\n" + sourceCode)
),
AnthropicChatOptions.builder()
.model("claude-sonnet-4")
.cacheOptions(AnthropicCacheOptions.builder()
.strategy(AnthropicCacheStrategy.SYSTEM_ONLY)
.build())
.maxTokens(800)
.build()
)
);
reviews.add(review.getResult().getOutput().getText());
}
// Guidelines cached after first request, subsequent reviews are faster and cheaper
Customer Support with Knowledge Base
Create a customer support system that caches your product knowledge base for consistent, accurate responses:
// Load comprehensive product knowledge
String knowledgeBase = """
PRODUCT DOCUMENTATION:
- API endpoints and authentication methods
- Common troubleshooting procedures
- Billing and subscription details
- Integration guides and examples
- Known issues and workarounds
""" + loadProductDocs(); // ~2500 tokens
@Service
public class CustomerSupportService {
public String handleCustomerQuery(String customerQuery, String customerId) {
ChatResponse response = chatModel.call(
new Prompt(
List.of(
new SystemMessage("You are a helpful customer support agent. " +
"Use this knowledge base to provide accurate solutions: " + knowledgeBase),
new UserMessage("Customer " + customerId + " asks: " + customerQuery)
),
AnthropicChatOptions.builder()
.model("claude-sonnet-4")
.cacheOptions(AnthropicCacheOptions.builder()
.strategy(AnthropicCacheStrategy.SYSTEM_ONLY)
.build())
.maxTokens(600)
.build()
)
);
return response.getResult().getOutput().getText();
}
}
// Knowledge base is cached across all customer queries
// Multiple support agents can benefit from the same cached content
ベストプラクティス
Choose the Right Strategy :
Use
SYSTEM_ONLY
for reusable system prompts and instructionsUse
SYSTEM_AND_TOOLS
when you have both system content and tool definitions to cache (the last tool definition is cached)Use
CONVERSATION_HISTORY
with ChatClient memory for multi-turn conversationsUse
NONE
to explicitly disable caching
Meet Token Requirements : Focus on caching content that meets the minimum token requirements (1024+ tokens for Sonnet 4, 2048+ for Haiku models).
Reuse Identical Content : Caching works best with exact matches of prompt content. Even small changes will require a new cache entry.
Monitor Token Usage : Use the cache usage statistics to track cache effectiveness:
java AnthropicApi.Usage usage = (AnthropicApi.Usage) response.getMetadata().getUsage().getNativeUsage(); if (usage != null) { System.out.println("Cache creation: " + usage.cacheCreationInputTokens()); System.out.println("Cache read: " + usage.cacheReadInputTokens()); }
Strategic Cache Placement : The implementation automatically places cache breakpoints at optimal locations based on your chosen strategy, ensuring compliance with Anthropic’s 4-breakpoint limit.
Cache Lifetime : Default TTL is 5 minutes; set 1-hour TTL per message type via
messageTypeTtl(…)
. Each cache access resets the timer.Tool Caching Limitations : Be aware that tool-based interactions may not provide cache usage metadata in the response.
実装の詳細
The prompt caching implementation in Spring AI follows these key design principles:
Strategic Cache Placement : Cache breakpoints are automatically placed at optimal locations based on the chosen strategy, ensuring compliance with Anthropic’s 4-breakpoint limit.
Provider Portability : Cache configuration is done through
AnthropicChatOptions
rather than individual messages, preserving compatibility when switching between different AI providers.スレッドセーフ : The cache breakpoint tracking is implemented with thread-safe mechanisms to handle concurrent requests correctly.
Automatic Content Ordering : The implementation ensures proper on-the-wire ordering of JSON content blocks and cache controls according to Anthropic’s API requirements.
Future Enhancements
The current cache strategies are designed to handle 90% of common use cases effectively. For applications requiring more granular control, future enhancements may include:
Message-level cache control for fine-grained breakpoint placement
Multi-block content caching within individual messages
Advanced cache boundary selection for complex tool scenarios
Mixed TTL strategies for optimized cache hierarchies
These enhancements will maintain full backward compatibility while unlocking Anthropic’s complete prompt caching capabilities for specialized use cases.
考え
Anthropic Claude モデルは、「思考」機能をサポートしており、最終的な答えを出す前にモデルが推論プロセスを示すことができます。この機能により、特に段階的な推論を必要とする複雑な問題において、より透明性が高く詳細な問題解決が可能になります。
対応モデル 思考機能は、次の Claude モデルでサポートされています。
モデルの機能:
API リクエスト構造はサポートされているすべてのモデルで同じですが、出力動作は異なります。 |
思考構成
サポートされている Claude モデルで思考を有効にするには、リクエストに次の構成を含めます。
必要な構成
thinking
オブジェクトを追加する :"type": "enabled"
budget_tokens
: 推論のためのトークン制限 (1024 から始めることをお勧めします)
トークン予算ルール :
budget_tokens
は通常max_tokens
より小さくなければなりませんClaude は割り当てられたトークンよりも少ないトークンを使用する場合があります
予算が大きいほど推論の深さは増しますが、レイテンシに影響する可能性があります
インターリーブ思考でツールの使用を使用する場合 (Claude 4 のみ)、この制約は緩和されますが、Spring AI ではまだサポートされていません。
重要な考慮事項
Claude 3.7 は完全な思考内容をレスポンスで返します
Claude 4 は、モデルの内部推論の要約版を返すことで、レイテンシを削減し、機密コンテンツを保護します。
出力トークンの一部としての思考トークンは課金可能 (たとえすべての反応が目に見えなくても)
インターリーブ思考は Claude 4 モデルでのみ使用可能で、ベータヘッダー
interleaved-thinking-2025-05-14
が必要です。
ツールの統合とインターリーブ思考
Claude 4 モデルはツールの使用とインターリーブされた思考をサポートし、モデルがツールの呼び出し間で推論できるようにします。
現在の Spring AI 実装では、基本的な思考とツールの使用が個別にサポートされていますが、ツールの使用とインターリーブされた思考 (複数のツール呼び出しにわたって思考が継続される) はまだサポートされていません。 |
ツールの使用とインターリーブ思考の詳細については、Anthropic ドキュメント (英語) を参照してください。
非ストリーミングの例
ChatClient API を使用して非ストリーミングリクエストで思考を有効にする方法は次のとおりです。
ChatClient chatClient = ChatClient.create(chatModel);
// For Claude 3.7 Sonnet - explicit thinking configuration required
ChatResponse response = chatClient.prompt()
.options(AnthropicChatOptions.builder()
.model("claude-3-7-sonnet-latest")
.temperature(1.0) // Temperature should be set to 1 when thinking is enabled
.maxTokens(8192)
.thinking(AnthropicApi.ThinkingType.ENABLED, 2048) // Must be ≥1024 && < max_tokens
.build())
.user("Are there an infinite number of prime numbers such that n mod 4 == 3?")
.call()
.chatResponse();
// For Claude 4 models - thinking is enabled by default
ChatResponse response4 = chatClient.prompt()
.options(AnthropicChatOptions.builder()
.model("claude-opus-4-0")
.maxTokens(8192)
// No explicit thinking configuration needed
.build())
.user("Are there an infinite number of prime numbers such that n mod 4 == 3?")
.call()
.chatResponse();
// Process the response which may contain thinking content
for (Generation generation : response.getResults()) {
AssistantMessage message = generation.getOutput();
if (message.getText() != null) {
// Regular text response
System.out.println("Text response: " + message.getText());
}
else if (message.getMetadata().containsKey("signature")) {
// Thinking content
System.out.println("Thinking: " + message.getMetadata().get("thinking"));
System.out.println("Signature: " + message.getMetadata().get("signature"));
}
}
ストリーミングの例
ストリーミングレスポンスで思考を使用することもできます。
ChatClient chatClient = ChatClient.create(chatModel);
// For Claude 3.7 Sonnet - explicit thinking configuration
Flux<ChatResponse> responseFlux = chatClient.prompt()
.options(AnthropicChatOptions.builder()
.model("claude-3-7-sonnet-latest")
.temperature(1.0)
.maxTokens(8192)
.thinking(AnthropicApi.ThinkingType.ENABLED, 2048)
.build())
.user("Are there an infinite number of prime numbers such that n mod 4 == 3?")
.stream();
// For Claude 4 models - thinking is enabled by default
Flux<ChatResponse> responseFlux4 = chatClient.prompt()
.options(AnthropicChatOptions.builder()
.model("claude-opus-4-0")
.maxTokens(8192)
// No explicit thinking configuration needed
.build())
.user("Are there an infinite number of prime numbers such that n mod 4 == 3?")
.stream();
// For streaming, you might want to collect just the text responses
String textContent = responseFlux.collectList()
.block()
.stream()
.map(ChatResponse::getResults)
.flatMap(List::stream)
.map(Generation::getOutput)
.map(AssistantMessage::getText)
.filter(text -> text != null && !text.isBlank())
.collect(Collectors.joining());
ツール / 関数の呼び出し
AnthropicChatModel
にカスタム Java ツールを登録し、Anthropic Claude モデルで、登録された関数の 1 つまたは複数を呼び出すための引数を含む JSON オブジェクトをインテリジェントに出力するように選択できます。これは、LLM 機能を外部ツールや API に接続するための強力な手法です。ツール呼び出しの詳細については、こちらを参照してください。
マルチモーダル
マルチモーダル性とは、テキスト、PDF、イメージ、データ形式など、さまざまなソースからの情報を同時に理解して処理するモデルの機能を指します。
イメージ
現在、Anthropic、Claude 3 は、images
の base64
ソース型と、image/jpeg
、image/png
、image/gif
、image/webp
メディア型をサポートしています。詳細については、ビジョンガイド (英語) を確認してください。Anthropic、Claude 3.5 Sonnet は、application/pdf
ファイルの pdf
ソース型もサポートしています。
Spring AI の Message
インターフェースは、メディア型を導入することでマルチモーダル AI モデルをサポートします。この型には、生のメディアデータに Spring の org.springframework.util.MimeType
および java.lang.Object
を使用して、メッセージ内のメディア添付ファイルに関するデータと情報が含まれます。
以下は、AnthropicChatModelIT.java [GitHub] (英語) から抽出された簡単なコード例で、ユーザーテキストとイメージの組み合わせを示しています。
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
:

「この写真に何が写っているか説明してください」というテキストメッセージとともに、次のようなレスポンスが生成されます。
The image shows a close-up view of a wire fruit basket containing several pieces of fruit. ...
Sonnet 以降では 3.5 と PDF サポート (ベータ) (英語) が提供されています。メッセージに PDF ファイルを添付するには、application/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
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 [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 anthropicChatOptions = AnthropicChatOptions.builder()
.model("claude-3-7-sonnet-20250219")
.temperature(0.4)
.maxTokens(200)
.build()
var chatModel = AnthropicChatModel.builder().anthropicApi(anthropicApi)
.defaultOptions(anthropicChatOptions).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 クライアント
AnthropicApi [GitHub] (英語) が提供するのは、Anthropic メッセージ API (英語) 用の軽量 Java クライアントです。
次のクラス図は、AnthropicApi
チャットインターフェースと構成要素を示しています。


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 [GitHub] (英語) の JavaDoc を参照してください。
低レベル API の例
AnthropicApiIT.java [GitHub] (英語) テストでは、軽量ライブラリの使用方法の一般的な例をいくつか示します。