跳到主要内容

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 特有选项(cacheSystemMessagescacheToolsreturnCacheDiagnosticsthinkingTypethinkingBudgetTokenssendThinkingreturnThinkingmidConversationSystemMessagestoolChoiceNamedisableParallelToolUse 以及 userId),以及 previousMessageId(仅请求级,见 缓存诊断), 也可通过 AnthropicChatRequestParameters 按请求设置,从而覆盖模型构建器上配置的值。 这样可以用同一个共享模型实例在不同调用间改变这些选项——例如, 在长时间运行的智能体循环中启用提示缓存,而在廉价的一次性补全中跳过缓存,而无需 构建第二个模型:

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 可异步处理大量聊天请求, 价格为标准按 token 计费的 50%。AnthropicBatchChatModel 实现了核心的 BatchChatModel 接口(submitretrievecancellist)。每个请求提交时使用的参数与 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 让 Claude 通过在代码执行容器中运行预构建技能,生成可下载的真实文档(.xlsx.pptx.docx.pdf)。 通过类型化的 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。 同一个 skills(...) 参数也可用于 AnthropicStreamingChatModel

工具搜索工具(Tool Search Tool)

Anthropic 的 工具搜索工具 通过 serverTools、工具 metadata 以及 toolMetadataKeysToSend 参数支持。

以下是使用高层 AI Service 与 @Tool API 的示例:

AnthropicServerTool toolSearchTool = AnthropicServerTool.builder()
.type("tool_search_tool_regex_20251119")
.name("tool_search_tool_regex")
.build();

class Tools {

@Tool(metadata = "{\"defer_loading\": true}")
String getWeather(String location) {
return "sunny";
}

@Tool
String getTime(String location) {
return "12:34:56";
}
}

ChatModel chatModel = AnthropicChatModel.builder()
.apiKey(System.getenv("ANTHROPIC_API_KEY"))
.modelName(CLAUDE_SONNET_4_5_20250929)
.beta("advanced-tool-use-2025-11-20")
.serverTools(toolSearchTool)
.toolMetadataKeysToSend("defer_loading") // need to specify it explicitly
.logRequests(true)
.logResponses(true)
.build();

interface Assistant {

@SystemMessage("Use tool search if needed")
String chat(String userMessage);
}

Assistant assistant = AiServices.builder(Assistant.class)
.chatModel(chatModel)
.tools(new Tools())
.build();

assistant.chat("What is the weather in Munich?");

以下是使用底层 ChatModelToolSpecification API 的示例:

AnthropicServerTool toolSearchTool = AnthropicServerTool.builder()
.type("tool_search_tool_regex_20251119")
.name("tool_search_tool_regex")
.build();

Map<String, Object> toolMetadata = Map.of("defer_loading", true);

ToolSpecification weatherTool = ToolSpecification.builder()
.name("get_weather")
.parameters(JsonObjectSchema.builder()
.addStringProperty("location")
.required("location")
.build())
.metadata(toolMetadata)
.build();

ToolSpecification timeTool = ToolSpecification.builder()
.name("get_time")
.parameters(JsonObjectSchema.builder()
.addStringProperty("location")
.required("location")
.build())
.build();

ChatModel model = AnthropicChatModel.builder()
.apiKey(System.getenv("ANTHROPIC_API_KEY"))
.modelName(CLAUDE_SONNET_4_5_20250929)
.beta("advanced-tool-use-2025-11-20")
.serverTools(toolSearchTool)
.toolMetadataKeysToSend(toolMetadata.keySet()) // need to specify it explicitly
.logRequests(true)
.logResponses(true)
.build();

ChatRequest chatRequest = ChatRequest.builder()
.messages(UserMessage.from("What is the weather in Munich? Use tool search if needed."))
.toolSpecifications(weatherTool, timeTool)
.build();

ChatResponse chatResponse = model.chat(chatRequest);

程序化工具调用(Programmatic Tool Calling)

Anthropic 的 程序化工具调用 通过 serverTools、工具 metadata 以及 toolMetadataKeysToSend 参数支持。

以下是使用高层 AI Service 与 @Tool API 的示例:

AnthropicServerTool codeExecutionTool = AnthropicServerTool.builder()
.type("code_execution_20250825")
.name("code_execution")
.build();

class Tools {

static final String TOOL_METADATA = "{\"allowed_callers\": [\"code_execution_20250825\"]}";
static final String TOOL_DESCRIPTION = """
Returns daily minimum and maximum temperatures recorded
for a specified city for a specified number of previous days.
Response format: [{"min":0.0,"max":10.0},{"min":0.0,"max":20.0},{"min":0.0,"max":30.0}]
""";

record TemperatureRange(double min, double max) {}

@Tool(value = TOOL_DESCRIPTION, metadata = TOOL_METADATA)
List<TemperatureRange> getDailyTemperatures(String city, int days) {
if ("Munich".equals(city) && days == 5) {
return List.of(
new TemperatureRange(0.0, 1.0),
new TemperatureRange(0.0, 2.0),
new TemperatureRange(0.0, 3.0),
new TemperatureRange(0.0, 4.0),
new TemperatureRange(0.0, 5.0)
);
}

throw new IllegalArgumentException("Unknown city: " + city + " or days: " + days);
}

@Tool(value = "Calculates the average of the specified list of numbers", metadata = TOOL_METADATA)
Double average(List<Double> numbers) {
return numbers.stream()
.mapToDouble(Double::doubleValue)
.average()
.orElseThrow();
}
}

ChatModel chatModel = AnthropicChatModel.builder()
.apiKey(System.getenv("ANTHROPIC_API_KEY"))
.modelName(CLAUDE_SONNET_4_5_20250929)
.beta("advanced-tool-use-2025-11-20")
.serverTools(codeExecutionTool)
.toolMetadataKeysToSend("allowed_callers") // need to specify it explicitly
.logRequests(true)
.logResponses(true)
.build();

interface Assistant {

String chat(String userMessage);
}

Assistant assistant = AiServices.builder(Assistant.class)
.chatModel(chatModel)
.tools(new Tools())
.build();

assistant.chat("What was the average max temperature in Munich in the last 5 days?");

查看 工具搜索工具 一节, 了解如何在底层 ToolSpecification API 中指定工具 metadata

工具使用示例(Tool Use Examples)

Anthropic 的 工具使用示例 通过工具 metadatatoolMetadataKeysToSend 参数支持。

以下是使用高层 AI Service 与 @Tool API 的示例:

enum Unit {
CELSIUS, FAHRENHEIT
}

class Tools {

// NOTE: if javac "-parameters" option is not enabled, you need to change "location" to "arg0"
// and "unit" to "arg1" inside the TOOL_METADATA to make it work.
public static final String TOOL_METADATA = """
{
"input_examples": [
{
"location": "San Francisco, CA",
"unit": "FAHRENHEIT"
},
{
"location": "Tokyo, Japan",
"unit": "CELSIUS"
},
{
"location": "New York, NY"
}
]
}
""";

@Tool(metadata = TOOL_METADATA)
String getWeather(String location, @P(description = "temperature unit", required = false) Unit unit) {
return "sunny";
}
}

ChatModel chatModel = AnthropicChatModel.builder()
.apiKey(System.getenv("ANTHROPIC_API_KEY"))
.modelName(CLAUDE_SONNET_4_5_20250929)
.beta("advanced-tool-use-2025-11-20")
.toolMetadataKeysToSend("input_examples") // need to specify it explicitly
.logRequests(true)
.logResponses(true)
.build();

interface Assistant {

String chat(String userMessage);
}

Assistant assistant = AiServices.builder(Assistant.class)
.chatModel(chatModel)
.tools(new Tools())
.build();

assistant.chat("What is the weather in Munich in Fahrenheit?");

查看 工具搜索工具 一节, 了解如何在底层 ToolSpecification API 中指定工具 metadata

缓存(Caching)

AnthropicChatModelAnthropicStreamingChatModel 在响应中返回 AnthropicTokenUsage, 其中包含 cacheCreationInputTokenscacheReadInputTokens

关于缓存的更多信息见 此处

缓存系统消息与工具

系统消息与工具的缓存默认禁用。 可分别通过设置 cacheSystemMessagescacheTools 参数启用。

启用后,将分别向最后一条系统消息与最后一个工具添加 cache_control 块。

缓存单条消息

UserMessageAiMessageToolExecutionResultMessage 都可通过将 cache_control 属性设为 ephemeral 来标记缓存。缓存控制标记会自动应用到该消息的 最后一个内容块(对 ToolExecutionResultMessage 而言,即 tool_result 块 本身)。

UserMessage 暴露可变的 attributes 映射:

UserMessage userMessage = UserMessage.from("Hello cached world");
userMessage.attributes().put("cache_control", "ephemeral");

AiMessageToolExecutionResultMessage 携带不可变的 attributes 映射,因此通过 toBuilder() 设置。这在智能体工具执行循环中特别有用:对话 历史每轮都会增长;将一轮的最后一条消息标记为 ephemeral,可让后续更大的 请求复用缓存前缀,而不必对不断增长的整段历史按全价重新计费。

AiMessage aiMessage = someAiMessage.toBuilder()
.attributes(Map.of("cache_control", "ephemeral"))
.build();

ToolExecutionResultMessage toolExecutionResultMessage = someToolExecutionResultMessage.toBuilder()
.attributes(Map.of("cache_control", "ephemeral"))
.build();

缓存诊断

Anthropic 的(beta)缓存诊断 功能会报告提示缓存未命中的原因(模型、系统提示、工具或消息历史发生了变化), 而不仅仅是显示 cacheReadInputTokens 降为零。

需要 cache-diagnosis-2026-04-07 beta 头,并通过 returnCacheDiagnostics 启用。在对话的第一轮将 previousMessageId 传为 null 以选择加入,之后每一轮传入上一轮响应的 id

AnthropicChatModel model = AnthropicChatModel.builder()
.apiKey(System.getenv("ANTHROPIC_API_KEY"))
.beta("cache-diagnosis-2026-04-07")
.returnCacheDiagnostics(true)
.build();

ChatResponse response1 = model.chat(ChatRequest.builder()
.messages(UserMessage.from("Summarize section 1."))
.build());
String previousMessageId = ((AnthropicChatResponseMetadata) response1.metadata()).id();

ChatResponse response2 = model.chat(ChatRequest.builder()
.messages(UserMessage.from("Summarize section 1."), UserMessage.from("Now summarize section 2."))
.parameters(AnthropicChatRequestParameters.builder()
// returnCacheDiagnostics is already enabled on the model above, so on subsequent turns
// you only need to supply the previousMessageId (it changes every turn).
.previousMessageId(previousMessageId)
.build())
.build());

AnthropicCacheDiagnostics diagnostics = ((AnthropicChatResponseMetadata) response2.metadata()).cacheDiagnostics();
if (diagnostics != null && diagnostics.cacheMissReasonType() != null) {
// e.g. "model_changed", "system_changed", "tools_changed", "messages_changed",
// "previous_message_not_found" or "unavailable"
System.out.println(diagnostics.cacheMissReasonType());
}

未请求诊断或未发现分歧时,cacheDiagnostics()null

Thinking

AnthropicChatModelAnthropicStreamingChatModel 均支持 扩展 thinking自适应 thinking 功能。

由以下参数控制:

  • thinkingTypethinkingBudgetTokens:启用 thinking, 详见 此处
  • thinkingDisplay:控制 thinking 内容如何返回。有效值为 "summarized""omitted"
  • returnThinking:控制是否在 AiMessage.thinking() 中返回 thinking(若可用), 以及使用 BedrockStreamingChatModel 时是否调用 StreamingChatResponseHandler.onPartialThinking()TokenStream.onPartialThinking() 回调。 默认禁用。若启用,thinking 签名也会存储并返回在 AiMessage.attributes() 中。
  • sendThinking:控制是否在后续请求中将存储在 AiMessage 中的 thinking 与签名发送给 LLM。 默认启用。

要配置 effort 参数,在构建模型时设置 customParameters

ChatModel model = AnthropicChatModel.builder()
.apiKey(System.getenv("ANTHROPIC_API_KEY"))
.modelName("claude-sonnet-4-7")
.customParameters(Map.of("output_config", Map.of("effort", "max")))
...
.build();

以下是配置 thinking 的示例:

ChatModel model = AnthropicChatModel.builder()
.apiKey(System.getenv("ANTHROPIC_API_KEY"))
.modelName("claude-sonnet-4-5-20250929")
.thinkingType("enabled")
.thinkingBudgetTokens(1024)
.maxTokens(1024 + 100)
.returnThinking(true)
.sendThinking(true)
.build();

对话中途系统消息(Mid-Conversation System Messages)

默认情况下,无论 SystemMessage 出现在消息列表的何处,都会折叠到顶层 system 提示中。 这与 Anthropic 一贯的行为一致,保持不变。

Claude Opus 4.8 额外支持 对话中途系统消息: 出现在对话开始之后SystemMessage 可作为 messages 数组中的内联 system 条目发送, 从而从该点起对后续对话生效(例如,在会话中途更改助手指令)。 通过 midConversationSystemMessages(true) 启用:

AnthropicChatModel model = AnthropicChatModel.builder()
.apiKey(System.getenv("ANTHROPIC_API_KEY"))
.modelName("claude-opus-4-8")
.midConversationSystemMessages(true)
.build();

ChatResponse response = model.chat(ChatRequest.builder()
.messages(
SystemMessage.from("You are a helpful assistant."), // leading -> top-level "system" prompt
UserMessage.from("Hello"),
AiMessage.from("Hi! How can I help?"),
SystemMessage.from("From now on, answer only in French."), // mid-conversation -> inline
UserMessage.from("What is the capital of Spain?"))
.build());

启用后,前导 SystemMessage(第一条用户/助手消息之前的那些)仍会填充顶层 system 提示;只有对话开始之后出现的才会内联发送。这不仅仅是约定——Anthropic 要求如此: system 消息不能作为 messages 数组的第一条, 且基础系统提示本来就应放在稳定、可缓存的前缀中。在选项禁用(默认)时, 行为不变,所有 SystemMessage 都进入顶层 system 提示。

也可通过 AnthropicChatRequestParameters 按请求设置(见 按请求参数)。

备注

Anthropic 限制对话中途系统消息的放置位置:必须紧跟在 user 轮次之后(包括携带工具结果的 user 轮次),必须位于 assistant 轮次之前或位于数组末尾,且不得 夹在 tool_use 块与其 tool_result 之间。也不允许连续的 system 消息。 注意:在选项禁用时,langchain4j 会将多条 SystemMessage 合并到顶层 system 字段;启用时,两条相邻的对话中途 SystemMessage 会作为连续的内联 system 条目发送并被拒绝。langchain4j 不会重排或合并内联消息——按你提供的位置发送—— 因此不支持的模型或无效放置会导致 Anthropic API 返回 400

PDF 支持

Anthropic Claude 支持处理 PDF 文档。你可以通过 URL 或 base64 编码数据发送 PDF。

通过 URL 发送 PDF

UserMessage message = UserMessage.from(
PdfFileContent.from(URI.create("https://example.com/document.pdf")),
TextContent.from("What are the key findings in this document?")
);

ChatResponse response = model.chat(message);

通过 Base64 发送 PDF

String base64Data = Base64.getEncoder().encodeToString(Files.readAllBytes(Path.of("document.pdf")));

UserMessage message = UserMessage.from(
PdfFileContent.from(base64Data, "application/pdf"),
TextContent.from("Summarize this document.")
);

ChatResponse response = model.chat(message);

关于 PDF 支持的更多信息见 此处

设置自定义聊天请求参数

构建 AnthropicChatModelAnthropicStreamingChatModel 时, 可为 HTTP 请求 JSON 体中的聊天请求配置自定义参数。 以下是启用 上下文编辑 的示例:

record Edit(String type) {}
record ContextManagement(List<Edit> edits) { }
Map<String, Object> customParameters = Map.of("context_management", new ContextManagement(List.of(new Edit("clear_tool_uses_20250919"))));

ChatModel model = AnthropicChatModel.builder()
.apiKey(System.getenv("ANTHROPIC_API_KEY"))
.modelName(CLAUDE_SONNET_4_5_20250929)
.beta("context-management-2025-06-27")
.customParameters(customParameters)
.logRequests(true)
.logResponses(true)
.build();

String answer = model.chat("Hi");

这将产生如下 body 的 HTTP 请求:

{
"model" : "claude-sonnet-4-5-20250929",
"messages" : [ {
"role" : "user",
"content" : [ {
"type" : "text",
"text" : "Hi"
} ]
} ],
"context_management" : {
"edits" : [ {
"type" : "clear_tool_uses_20250919"
} ]
}
}

也可以将自定义参数指定为嵌套 map 结构:

Map<String, Object> customParameters = Map.of(
"context_management",
Map.of("edits", List.of(Map.of("type", "clear_tool_uses_20250919")))
);

访问原始 HTTP 响应与服务器发送事件(SSE)

使用 AnthropicChatModel 时,你可以访问原始 HTTP 响应:

SuccessfulHttpResponse rawHttpResponse = ((AnthropicChatResponseMetadata) chatResponse.metadata()).rawHttpResponse();
System.out.println(rawHttpResponse.body());
System.out.println(rawHttpResponse.headers());
System.out.println(rawHttpResponse.statusCode());

使用 AnthropicStreamingChatModel 时,你可以访问原始 HTTP 响应(见上)以及原始服务器发送事件:

List<ServerSentEvent> rawServerSentEvents = ((AnthropicChatResponseMetadata) chatResponse.metadata()).rawServerSentEvents();
System.out.println(rawServerSentEvents.get(0).data());
System.out.println(rawServerSentEvents.get(0).event());

AnthropicTokenCountEstimator

TokenCountEstimator tokenCountEstimator = AnthropicTokenCountEstimator.builder()
.modelName(CLAUDE_3_OPUS_20240229)
.apiKey(System.getenv("ANTHROPIC_API_KEY"))
.logRequests(true)
.logResponses(true)
.build();

List<ChatMessage> messages = List.of(...);

int tokenCount = tokenCountEstimator.estimateTokenCountInMessages(messages);

Quarkus

更多详情见 此处

Spring Boot

导入 Anthropic 的 Spring Boot starter:

<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-anthropic-spring-boot-starter</artifactId>
<version>1.18.1-beta28</version>
</dependency>

配置 AnthropicChatModel bean:

langchain4j.anthropic.chat-model.api-key = ${ANTHROPIC_API_KEY}

配置 AnthropicStreamingChatModel bean:

langchain4j.anthropic.streaming-chat-model.api-key = ${ANTHROPIC_API_KEY}

示例