Class AnthropicChatModel.AnthropicChatModelBuilder
- Enclosing class:
AnthropicChatModel
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionSets the Anthropic API key used to authenticate requests.Sets the base URL of the Anthropic API.Sets the value of theanthropic-betarequest header to opt into beta features.build()cacheSystemMessages(Boolean cacheSystemMessages) Enables prompt caching forSystemMessages.cacheTools(Boolean cacheTools) Enables prompt caching forToolSpecifications.customHeaders(Supplier<Map<String, String>> customHeadersSupplier) Sets a supplier of extra HTTP headers to include in every request to the Anthropic API.customHeaders(Map<String, String> customHeaders) Sets extra HTTP headers to include in every request to the Anthropic API.customParameters(Map<String, Object> customParameters) Sets arbitrary extra parameters to include in the Anthropic API request body.defaultRequestParameters(ChatRequestParameters parameters) Sets defaultChatRequestParametersthat are merged into every request.disableParallelToolUse(Boolean disableParallelToolUse) When set totrue, prevents the model from calling multiple tools in a single response turn.httpClientBuilder(HttpClientBuilder httpClientBuilder) Sets a customHttpClientBuilderfor the underlying HTTP client.listeners(ChatModelListener... listeners) Sets theChatModelListeners to be notified on each request and response.listeners(List<ChatModelListener> listeners) Sets the list ofChatModelListeners to be notified on each request and response.logger(org.slf4j.Logger logger) logRequests(Boolean logRequests) Enables debug logging of HTTP request bodies sent to the Anthropic API.logResponses(Boolean logResponses) Enables debug logging of HTTP response bodies received from the Anthropic API.maxRetries(Integer maxRetries) Sets the number of times to retry a request on transient errors (e.g. rate limits, server errors).Sets the maximum number of tokens to generate in the response.modelName(AnthropicChatModelName modelName) Sets the model to use for chat completions using a type-safe enum constant.Sets the model to use for chat completions, specified as a string model ID.responseFormat(ResponseFormat responseFormat) Sets the response format, enabling structured output such as JSON mode.returnServerToolResults(Boolean returnServerToolResults) Controls whether to return server tool results (e.g., web_search, code_execution) insideAiMessage.attributes()under the key "server_tool_results".returnThinking(Boolean returnThinking) Controls whether to return thinking/reasoning text (if available) insideAiMessage.thinking().sendThinking(Boolean sendThinking) Controls whether to send thinking/reasoning text to the LLM in follow-up requests.serverTools(AnthropicServerTool... serverTools) Specifies server tools to be included in each request to the Anthropic API.serverTools(List<AnthropicServerTool> serverTools) Specifies server tools to be included in each request to the Anthropic API.stopSequences(List<String> stopSequences) Sets sequences that, when generated, will cause the model to stop generating further tokens.strictTools(Boolean strictTools) Enables strict JSON schema validation for tool input parameters.supportedCapabilities(Capability... supportedCapabilities) Declares the capabilities supported by the model (e.g.supportedCapabilities(Set<Capability> supportedCapabilities) Declares the capabilities supported by the model.temperature(Double temperature) Sets the sampling temperature in the range[0.0, 1.0].thinkingBudgetTokens(Integer thinkingBudgetTokens) Configures thinking.thinkingDisplay(String thinkingDisplay) Controls how thinking content is returned in the response.thinkingType(String thinkingType) Enables thinking.Sets the HTTP request timeout for calls to the Anthropic API.toolChoice(ToolChoice toolChoice) Controls how the model uses tools.toolChoiceName(String toolChoiceName) Sets the name of the specific tool the model must use whenToolChoiceis set toToolChoice.REQUIRED.toolMetadataKeysToSend(String... toolMetadataKeysToSend) Specifies metadata keys from theToolSpecification.metadata()to be included in the request.toolMetadataKeysToSend(Set<String> toolMetadataKeysToSend) Specifies metadata keys from theToolSpecification.metadata()to be included in the request.toolSpecifications(ToolSpecification... toolSpecifications) Sets the tools (functions) available to the model for function calling.toolSpecifications(List<ToolSpecification> toolSpecifications) Sets the list of tools (functions) available to the model for function calling.Sets the top-K sampling value.Sets the nucleus sampling probability (top-p) in the range(0.0, 1.0].Sets the user ID for the requests.Sets the value of theanthropic-versionrequest header.
-
Constructor Details
-
AnthropicChatModelBuilder
public AnthropicChatModelBuilder()
-
-
Method Details
-
httpClientBuilder
public AnthropicChatModel.AnthropicChatModelBuilder httpClientBuilder(HttpClientBuilder httpClientBuilder) Sets a customHttpClientBuilderfor the underlying HTTP client. Use this to configure timeouts, proxies, or other HTTP-level settings.- Parameters:
httpClientBuilder- the HTTP client builder- Returns:
this
-
baseUrl
Sets the base URL of the Anthropic API.Defaults to
https://api.anthropic.com/v1/.- Parameters:
baseUrl- the base URL- Returns:
this
-
apiKey
Sets the Anthropic API key used to authenticate requests.- Parameters:
apiKey- the API key- Returns:
this
-
version
Sets the value of theanthropic-versionrequest header.Defaults to
2023-06-01. See the Anthropic API versioning docs.- Parameters:
version- the API version string- Returns:
this
-
beta
Sets the value of theanthropic-betarequest header to opt into beta features.See the Anthropic beta headers docs.
- Parameters:
beta- the beta feature identifier- Returns:
this
-
modelName
Sets the model to use for chat completions, specified as a string model ID.See
AnthropicChatModelNamefor available model constants.- Parameters:
modelName- the model ID, e.g."claude-opus-4-5"- Returns:
this
-
modelName
Sets the model to use for chat completions using a type-safe enum constant.- Parameters:
modelName- the model name enum value- Returns:
this
-
temperature
Sets the sampling temperature in the range[0.0, 1.0]. Higher values produce more random output; lower values produce more deterministic output.Cannot be used together with
topP(Double).- Parameters:
temperature- the sampling temperature- Returns:
this
-
topP
Sets the nucleus sampling probability (top-p) in the range(0.0, 1.0]. Only the tokens whose cumulative probability exceeds this threshold are considered.Cannot be used together with
temperature(Double).- Parameters:
topP- the nucleus sampling threshold- Returns:
this
-
topK
Sets the top-K sampling value. Only thetopKmost-likely next tokens are considered at each step.Recommended for advanced use only;
temperature(Double)is usually sufficient.- Parameters:
topK- the number of top tokens to sample from- Returns:
this
-
maxTokens
Sets the maximum number of tokens to generate in the response.Defaults to
1024if not set.- Parameters:
maxTokens- the maximum number of output tokens- Returns:
this
-
stopSequences
Sets sequences that, when generated, will cause the model to stop generating further tokens.- Parameters:
stopSequences- the list of stop sequences- Returns:
this
-
responseFormat
Sets the response format, enabling structured output such as JSON mode.- Parameters:
responseFormat- the desired response format- Returns:
this
-
toolSpecifications
public AnthropicChatModel.AnthropicChatModelBuilder toolSpecifications(List<ToolSpecification> toolSpecifications) Sets the list of tools (functions) available to the model for function calling.- Parameters:
toolSpecifications- the tool specifications- Returns:
this
-
toolSpecifications
public AnthropicChatModel.AnthropicChatModelBuilder toolSpecifications(ToolSpecification... toolSpecifications) Sets the tools (functions) available to the model for function calling.- Parameters:
toolSpecifications- the tool specifications- Returns:
this
-
toolChoice
Controls how the model uses tools.Use
ToolChoice.AUTOto let the model decide,ToolChoice.REQUIREDto force tool use, orToolChoice.NONEto disable tool use.- Parameters:
toolChoice- the tool choice strategy- Returns:
this
-
toolChoiceName
Sets the name of the specific tool the model must use whenToolChoiceis set toToolChoice.REQUIRED.- Parameters:
toolChoiceName- the name of the tool to force- Returns:
this
-
disableParallelToolUse
public AnthropicChatModel.AnthropicChatModelBuilder disableParallelToolUse(Boolean disableParallelToolUse) When set totrue, prevents the model from calling multiple tools in a single response turn.- Parameters:
disableParallelToolUse- whether to disable parallel tool use- Returns:
this
-
serverTools
public AnthropicChatModel.AnthropicChatModelBuilder serverTools(List<AnthropicServerTool> serverTools) Specifies server tools to be included in each request to the Anthropic API. For example:AnthropicServerTool webSearchTool = AnthropicServerTool.builder() .type("web_search_20250305") .name("web_search") .addAttribute("max_uses", 5) .addAttribute("allowed_domains", List.of("accuweather.com")) .build(); -
returnServerToolResults
public AnthropicChatModel.AnthropicChatModelBuilder returnServerToolResults(Boolean returnServerToolResults) Controls whether to return server tool results (e.g., web_search, code_execution) insideAiMessage.attributes()under the key "server_tool_results".Disabled by default to avoid polluting ChatMemory with potentially large data. If enabled, server tool results will be stored as a
List<AnthropicServerToolResult>within the AiMessage attributes.- See Also:
-
serverTools
Specifies server tools to be included in each request to the Anthropic API. For example:AnthropicServerTool webSearchTool = AnthropicServerTool.builder() .type("web_search_20250305") .name("web_search") .addAttribute("max_uses", 5) .addAttribute("allowed_domains", List.of("accuweather.com")) .build(); -
toolMetadataKeysToSend
public AnthropicChatModel.AnthropicChatModelBuilder toolMetadataKeysToSend(Set<String> toolMetadataKeysToSend) Specifies metadata keys from theToolSpecification.metadata()to be included in the request. -
toolMetadataKeysToSend
public AnthropicChatModel.AnthropicChatModelBuilder toolMetadataKeysToSend(String... toolMetadataKeysToSend) Specifies metadata keys from theToolSpecification.metadata()to be included in the request. -
cacheSystemMessages
public AnthropicChatModel.AnthropicChatModelBuilder cacheSystemMessages(Boolean cacheSystemMessages) Enables prompt caching forSystemMessages.When
true, system messages are sent with thecache_controlheader to allow Anthropic to cache them across requests, reducing cost and latency for repeated prompts. See the prompt caching docs.- Parameters:
cacheSystemMessages- whether to cache system messages- Returns:
this
-
cacheTools
Enables prompt caching forToolSpecifications.When
true, tool definitions are sent with thecache_controlheader to allow Anthropic to cache them across requests. See the prompt caching docs.- Parameters:
cacheTools- whether to cache tool definitions- Returns:
this
-
thinkingType
Enables thinking. -
thinkingBudgetTokens
public AnthropicChatModel.AnthropicChatModelBuilder thinkingBudgetTokens(Integer thinkingBudgetTokens) Configures thinking. -
thinkingDisplay
Controls how thinking content is returned in the response.Valid values:
"summarized"and"omitted". On Claude Opus 4.7 the server default is"omitted"; on earlier Opus/Sonnet models the default is"summarized". Set to"summarized"explicitly on Opus 4.7+ to restore visible thinking text for UIs that render it.- See Also:
-
returnThinking
Controls whether to return thinking/reasoning text (if available) insideAiMessage.thinking(). Please note that this does not enable thinking/reasoning for the LLM; it only controls whether to parse thethinkingfield from the API response and return it inside theAiMessage.Disabled by default. If enabled, the thinking text will be stored within the
AiMessageand may be persisted. If enabled, thinking signatures will also be stored and returned inside theAiMessage.attributes().- See Also:
-
sendThinking
Controls whether to send thinking/reasoning text to the LLM in follow-up requests.Enabled by default. If enabled, the contents of
AiMessage.thinking()will be sent in the API request. If enabled, thinking signatures (inside theAiMessage.attributes()) will also be sent.- See Also:
-
timeout
Sets the HTTP request timeout for calls to the Anthropic API.- Parameters:
timeout- the request timeout- Returns:
this
-
maxRetries
Sets the number of times to retry a request on transient errors (e.g. rate limits, server errors).Defaults to
2.- Parameters:
maxRetries- the maximum number of retry attempts- Returns:
this
-
logRequests
Enables debug logging of HTTP request bodies sent to the Anthropic API.- Parameters:
logRequests- whether to log requests- Returns:
this
-
logResponses
Enables debug logging of HTTP response bodies received from the Anthropic API.- Parameters:
logResponses- whether to log responses- Returns:
this
-
logger
- Parameters:
logger- an alternateLoggerto be used instead of the default one provided by Langchain4J for logging requests and responses.- Returns:
this.
-
listeners
Sets the list ofChatModelListeners to be notified on each request and response. Useful for logging, metrics, and observability integrations.- Parameters:
listeners- the chat model listeners- Returns:
this
-
listeners
Sets theChatModelListeners to be notified on each request and response.- Parameters:
listeners- the chat model listeners- Returns:
this
-
defaultRequestParameters
public AnthropicChatModel.AnthropicChatModelBuilder defaultRequestParameters(ChatRequestParameters parameters) Sets defaultChatRequestParametersthat are merged into every request. Individual request parameters take precedence over these defaults.- Parameters:
parameters- the default request parameters- Returns:
this
-
userId
Sets the user ID for the requests. This should be a uuid, hash value, or other opaque identifier. Anthropic may use this id to help detect abuse. Do not include any identifying information such as name, email address, or phone number.- Parameters:
userId- the user identifier- Returns:
- this builder
-
customParameters
public AnthropicChatModel.AnthropicChatModelBuilder customParameters(Map<String, Object> customParameters) Sets arbitrary extra parameters to include in the Anthropic API request body. Use this for experimental or provider-specific fields not yet covered by dedicated builder methods.- Parameters:
customParameters- a map of parameter names to values- Returns:
this
-
strictTools
Enables strict JSON schema validation for tool input parameters. Whentrue, the model enforces the exact schema defined inToolSpecification.- Parameters:
strictTools- whether to enable strict tool schema validation- Returns:
this
-
customHeaders
Sets extra HTTP headers to include in every request to the Anthropic API.- Parameters:
customHeaders- a map of header names to values- Returns:
this
-
customHeaders
public AnthropicChatModel.AnthropicChatModelBuilder customHeaders(Supplier<Map<String, String>> customHeadersSupplier) Sets a supplier of extra HTTP headers to include in every request to the Anthropic API. The supplier is called once per request, allowing dynamic header values.- Parameters:
customHeadersSupplier- a supplier that returns a map of header names to values- Returns:
this
-
supportedCapabilities
public AnthropicChatModel.AnthropicChatModelBuilder supportedCapabilities(Capability... supportedCapabilities) Declares the capabilities supported by the model (e.g.Capability.RESPONSE_FORMAT_JSON_SCHEMA). This influences how LangChain4j generates requests for this model.- Parameters:
supportedCapabilities- the capabilities to declare- Returns:
this
-
supportedCapabilities
public AnthropicChatModel.AnthropicChatModelBuilder supportedCapabilities(Set<Capability> supportedCapabilities) Declares the capabilities supported by the model.- Parameters:
supportedCapabilities- the set of capabilities to declare- Returns:
this
-
build
-