Anthropic
Maven依存関係
<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-anthropic</artifactId>
<version>1.18.1</version>
</dependency>
AnthropicChatModel
AnthropicChatModel model = AnthropicChatModel.builder()
.apiKey(System.getenv("ANTHROPIC_API_KEY"))
.modelName(CLAUDE_3_5_SONNET_20240620)
.build();
String answer = model.chat("Say 'Hello World'");
System.out.println(answer);
AnthropicChatModel のカスタマイズ
AnthropicChatModel model = AnthropicChatModel.builder()
.httpClientBuilder(...)
.baseUrl(...)
.apiKey(...)
.version(...)
.beta(...)
.modelName(...)
.temperature(...)
.topP(...)
.topK(...)
.maxTokens(...)
.stopSequences(...)
.toolSpecifications(...)
.toolChoice(...)
.toolChoiceName(...)
.disableParallelToolUse(...)
.serverTools(...)
.returnServerToolResults(...)
.toolMetadataKeysToSend(...)
.cacheSystemMessages(...)
.cacheTools(...)
.returnCacheDiagnostics(...)
.thinkingType(...)
.thinkingBudgetTokens(...)
.thinkingDisplay(...)
.returnThinking(...)
.sendThinking(...)
.midConversationSystemMessages(...)
.timeout(...)
.maxRetries(...)
.logRequests(...)
.logResponses(...)
.listeners(...)
// You can also specify default chat request parameters using ChatRequestParameters or AnthropicChatRequestParameters
.defaultRequestParameters(...)
.userId(...)
.customParameters(...)
.build();
上記の一部パラメータの説明は こちら。
リクエスト単位のパラメータ
上記の Anthropic 固有オプション(cacheSystemMessages、cacheTools、returnCacheDiagnostics、
thinkingType、thinkingBudgetTokens、sendThinking、returnThinking、midConversationSystemMessages、
toolChoiceName、disableParallelToolUse、および userId)、ならびに previousMessageId(リクエスト専用、
キャッシュ診断 を参照)は、
AnthropicChatRequestParameters 経由でリクエスト単位にも設定でき、モデルビルダー上の値を上書きします。
これにより、共有の単一モデルインスタンスで呼び出しごとにこれらのオプションを変えられます——例えば、
長時間のエージェントループではプロンプトキャッシュを有効にし、安価なワンショット補完ではスキップし、
2 つ目のモデルを構築せずに済みます:
AnthropicChatModel model = AnthropicChatModel.builder()
.apiKey(System.getenv("ANTHROPIC_API_KEY"))
.modelName(CLAUDE_3_5_SONNET_20240620)
.build();
AnthropicChatRequestParameters parameters = AnthropicChatRequestParameters.builder()
.cacheSystemMessages(true)
.cacheTools(true)
.build();
ChatRequest chatRequest = ChatRequest.builder()
.messages(systemMessage, userMessage)
.parameters(parameters)
.build();
ChatResponse chatResponse = model.chat(chatRequest);
リクエストに設定されていないパラメータは、モデルビルダー上の値にフォールバックします。
AnthropicStreamingChatModel
AnthropicStreamingChatModel model = AnthropicStreamingChatModel.builder()
.apiKey(System.getenv("ANTHROPIC_API_KEY"))
.modelName(CLAUDE_3_5_SONNET_20240620)
.build();
model.chat("Say 'Hello World'", new StreamingChatResponseHandler() {
@Override
public void onPartialResponse(String partialResponse) {
// this method is called when a new partial response is available. It can consist of one or more tokens.
}
@Override
public void onCompleteResponse(ChatResponse completeResponse) {
// this method is called when the model has completed responding
}
@Override
public void onError(Throwable error) {
// this method is called when an error occurs
}
});
AnthropicStreamingChatModel のカスタマイズ
AnthropicChatModel と同一です。上記を参照してください。
Batch API
Message Batches API は多数のチャットリクエストを
標準のトークン単価の 50% で非同期処理します。AnthropicBatchChatModel はコアの BatchChatModel
インターフェース(submit、retrieve、cancel、list)を実装します。各リクエストは
AnthropicChatModel 呼び出しと同じパラメータで送信します。
AnthropicBatchChatModel model = AnthropicBatchChatModel.builder()
.apiKey(System.getenv("ANTHROPIC_API_KEY"))
.modelName("claude-sonnet-4-5")
.maxTokens(1024)
.build();
// Submit a batch of requests
BatchResponse<ChatResponse> submitted = model.submit(new BatchRequest<>(List.of(
ChatRequest.builder().messages(UserMessage.from("What is the capital of France?")).build(),
ChatRequest.builder().messages(UserMessage.from("What is the capital of Germany?")).build())));
String batchId = submitted.batchId();
// Poll until the batch reaches a terminal state (typically well under an hour)
BatchResponse<ChatResponse> batch = model.retrieve(batchId);
while (!batch.state().isTerminal()) {
TimeUnit.SECONDS.sleep(30); // throws InterruptedException
batch = model.retrieve(batchId);
}
// Read the per-request results, in submission order
for (BatchItemResult<ChatResponse> result : batch.results()) {
if (result.isSuccess()) {
System.out.println(result.response().aiMessage().text());
} else {
System.out.println("Failed: " + result.error().message());
}
}
model.list(...) で最近のバッチをページングし、model.cancel(batchId) で処理中のバッチをキャンセルできます。
キャンセルしたバッチも Anthropic 側では ended 状態で終わり、BatchState.CANCELLED として報告されます。
キャンセルが効く前に完了したリクエストの結果が含まれる場合があります。
thinking やプロンプトキャッシュなどの Anthropic 固有オ プションは defaultRequestParameters(...) で設定し、
AnthropicChatModel と全く同様で、リクエスト単位で上書きできます:
AnthropicBatchChatModel model = AnthropicBatchChatModel.builder()
.apiKey(System.getenv("ANTHROPIC_API_KEY"))
.modelName("claude-sonnet-4-5")
.maxTokens(4096)
.defaultRequestParameters(AnthropicChatRequestParameters.builder()
.thinkingType("enabled")
.thinkingBudgetTokens(2000)
.cacheSystemMessages(true)
.build())
.returnThinking(true) // store the returned thinking in AiMessage.thinking()
.build();
ツール(Tools)
Anthropic はストリーミング/非ストリーミングの両方で ツール をサポートします。
Anthropic のツールに関するドキュメントは こちら。
ツール選択(Tool Choice)
Anthropic の ツール選択
機能は、toolChoice(ToolChoice) または toolChoiceName(String) を設定することで、
ストリーミング/非ストリーミングの両方で利用できます。
並列ツール使用
デフォルトでは Anthropic Claude はユーザーのクエリに答えるために複数のツールを使うことがありますが、
disableParallelToolUse(true) を設定することで 並列ツール を無効化できます。
サーバーツール(Server Tools)
Anthropic の サーバーツール
は serverTools パラメータでサポートされます。以下は ウェブ検索ツール の使用例です:
AnthropicServerTool webSearchTool = AnthropicServerTool.builder()
.type("web_search_20250305")
.name("web_search")
.addAttribute("max_uses", 5)
.addAttribute("allowed_domains", List.of("accuweather.com"))
.build();
ChatModel model = AnthropicChatModel.builder()
.apiKey(System.getenv("ANTHROPIC_API_KEY"))
.modelName("claude-sonnet-4-5")
.serverTools(webSearchTool)
.logRequests(true)
.logResponses(true)
.build();
String answer = model.chat("What is the weather in Munich?");
serverTools で指定したツールは、Anthropic API へのすべてのリクエストに含まれます。
サーバーツール結果の取得
サーバーツールの生の結果(ウェブ検索結果、コード実行出力、
生成ファイルの fileIds など)にアクセスするには、returnServerToolResults(true) を有効にします。
結果は AiMessage.attributes() の "server_tool_results" キー配下に入ります:
ChatModel model = AnthropicChatModel.builder()
.apiKey(System.getenv("ANTHROPIC_API_KEY"))
.modelName("claude-sonnet-4-5")
.serverTools(webSearchTool)
.returnServerToolResults(true)
.build();
ChatResponse response = model.chat("What is the weather in Munich?");
AiMessage aiMessage = response.aiMessage();
List<AnthropicServerToolResult> results = aiMessage.attribute("server_tool_results", List.class);
for (AnthropicServerToolResult result : results) {
System.out.println("Type: " + result.type());
System.out.println("Tool Use ID: " + result.toolUseId());
System.out.println("Content: " + result.content());
}
ChatMemory に大きなデータが保存されるのを避けるため、デフォルトでは無効です。
Skills
Anthropic の Agent Skills
は、コード実行コンテナ 内で事前構築スキルを実行し、ダウンロード可能な実ドキュメント(.xlsx、.pptx、.docx、.pdf)を Claude に生成させます。
型付きの skills パラメータで有効化します:
AnthropicChatModel model = AnthropicChatModel.builder()
.apiKey(System.getenv("ANTHROPIC_API_KEY"))
.modelName("claude-opus-4-8")
.maxTokens(4096)
.beta("code-execution-2025-08-25,skills-2025-10-02,files-api-2025-04-14")
.skills(AnthropicSkill.XLSX, AnthropicSkill.PPTX)
.returnServerToolResults(true)
.build();
ChatResponse response = model.chat("Create an Excel spreadsheet with the numbers 1 to 5 in column A");
skills を有効にすると自動的に:
- リクエストに
container.skillsブロックを追加し、 - 必要な
code_executionサーバーツールを追加します(既にserverTools(...)で設定済みでない場合)。
必要な beta 機能は、上記のように自分で beta(...) によりオプトインする必要があります。これらは beta
ヘッダーで、値は時間とともに変わるため自動注入されません——現行セットは
Agent Skills ドキュメント
を確認してください。
returnServerToolResults(true) と組み合わせると、生成されたファイル id が
AiMessage.attributes() の "server_tool_results" キー配下に現れます(上記の
サーバーツール結果の取得 を参照)。ファイルは Anthropic の Files API 経由で
24 時間ダウンロード可能です。
Skills は Claude Sonnet 4 / 4.5、Opus 4 以降でサポートされます。リクエストあたり最大 8 スキルまで有効化できます。
同じ skills(...) パラメータは AnthropicStreamingChatModel でも利用できます。