This package provides an integration layer between the LangChain4j framework and Anthropic's Claude language models, enabling Java developers to seamlessly incorporate Anthropic's AI capabilities into their applications.
The AnthropicChatModel class provides synchronous (blocking) access to Claude chat models through the LangChain4j framework.
Build an AnthropicChatModel instance using the fluent builder pattern.
package dev.langchain4j.model.anthropic;
import dev.langchain4j.model.chat.ChatModel;
import dev.langchain4j.model.chat.request.ChatRequest;
import dev.langchain4j.model.chat.response.ChatResponse;
import dev.langchain4j.model.chat.listener.ChatModelListener;
import dev.langchain4j.model.chat.request.ChatRequestParameters;
import dev.langchain4j.model.Capability;
import dev.langchain4j.model.ModelProvider;
import java.util.List;
import java.util.Set;
/**
* Synchronous chat model for Anthropic's Claude API.
* Thread-safe after construction via builder.
*
* @since 1.0.0
*/
public class AnthropicChatModel implements ChatModel {
/**
* Creates a new builder for constructing AnthropicChatModel instances.
*
* @return a new builder instance, never null
*/
public static AnthropicChatModelBuilder builder();
/**
* Executes a synchronous chat request and blocks until response is received.
*
* @param chatRequest the chat request containing messages and parameters, must not be null
* @return chat response with AI message and metadata, never null
* @throws IllegalArgumentException if chatRequest is null or invalid
* @throws RuntimeException if API call fails or times out
*/
public ChatResponse doChat(ChatRequest chatRequest);
/**
* Returns registered chat model listeners for monitoring requests/responses.
*
* @return unmodifiable list of listeners, never null (may be empty)
*/
public List<ChatModelListener> listeners();
/**
* Returns the model provider (always ANTHROPIC).
*
* @return ANTHROPIC provider constant, never null
*/
public ModelProvider provider();
/**
* Returns default request parameters set during construction.
*
* @return default parameters, may be null if not configured
*/
public ChatRequestParameters defaultRequestParameters();
/**
* Returns capabilities supported by this model instance.
*
* @return set of supported capabilities, never null
*/
public Set<Capability> supportedCapabilities();
}Configure API connection settings.
package dev.langchain4j.model.anthropic;
import dev.langchain4j.http.client.HttpClientBuilder;
import java.time.Duration;
public class AnthropicChatModelBuilder {
/**
* Sets the Anthropic API key for authentication.
*
* @param apiKey the API key, must not be null or empty
* @return this builder for method chaining, never null
* @throws IllegalArgumentException if apiKey is null or empty
* @default no default - REQUIRED parameter
*/
public AnthropicChatModelBuilder apiKey(String apiKey);
/**
* Sets the base URL for Anthropic API.
*
* @param baseUrl the base URL including trailing slash, must not be null
* @return this builder for method chaining, never null
* @default "https://api.anthropic.com/v1/"
*/
public AnthropicChatModelBuilder baseUrl(String baseUrl);
/**
* Sets the API version header.
*
* @param version the API version string, must not be null
* @return this builder for method chaining, never null
* @default "2023-06-01"
*/
public AnthropicChatModelBuilder version(String version);
/**
* Sets beta feature flags to enable experimental features.
* For example, "prompt-caching-2024-07-31" enables prompt caching.
*
* @param beta comma-separated beta feature identifiers, may be null
* @return this builder for method chaining, never null
* @default null (no beta features)
*/
public AnthropicChatModelBuilder beta(String beta);
/**
* Sets custom HTTP client builder for advanced HTTP configuration.
*
* @param httpClientBuilder custom HTTP client builder, must not be null
* @return this builder for method chaining, never null
* @default platform default HTTP client
*/
public AnthropicChatModelBuilder httpClientBuilder(HttpClientBuilder httpClientBuilder);
/**
* Sets request timeout for API calls.
*
* @param timeout timeout duration, must not be null, must be positive
* @return this builder for method chaining, never null
* @throws IllegalArgumentException if timeout is null or not positive
* @default 60 seconds
*/
public AnthropicChatModelBuilder timeout(Duration timeout);
/**
* Sets user ID for abuse detection and tracking.
* Should be a UUID or hashed user identifier.
*
* @param userId user identifier, may be null
* @return this builder for method chaining, never null
* @default null (no user tracking)
*/
public AnthropicChatModelBuilder userId(String userId);
}Usage Example:
AnthropicChatModel model = AnthropicChatModel.builder()
.apiKey(System.getenv("ANTHROPIC_API_KEY")) // Required
.baseUrl("https://api.anthropic.com/v1/") // Optional, default shown
.version("2023-06-01") // Optional, default shown
.timeout(Duration.ofSeconds(60)) // Optional
.userId("user-uuid-or-hash") // Optional, for abuse detection
.build();Resource Lifecycle:
Configure model selection and sampling parameters.
package dev.langchain4j.model.anthropic;
import dev.langchain4j.model.chat.request.ResponseFormat;
import java.util.List;
import java.util.Map;
public class AnthropicChatModelBuilder {
/**
* Sets model name using string identifier.
*
* @param modelName model identifier string (e.g., "claude-sonnet-4-5-20250929"), must not be null
* @return this builder for method chaining, never null
* @throws IllegalArgumentException if modelName is null or empty
* @default "claude-sonnet-4-5-20250929"
*/
public AnthropicChatModelBuilder modelName(String modelName);
/**
* Sets model name using enum constant for type safety.
*
* @param modelName model name enum constant, must not be null
* @return this builder for method chaining, never null
* @throws IllegalArgumentException if modelName is null
* @default CLAUDE_SONNET_4_5_20250929
*/
public AnthropicChatModelBuilder modelName(AnthropicChatModelName modelName);
/**
* Sets temperature for response randomness.
* Higher values (e.g., 0.8-1.0) make output more random.
* Lower values (e.g., 0.0-0.3) make output more deterministic.
*
* @param temperature sampling temperature, must be null or in range [0.0, 1.0]
* @return this builder for method chaining, never null
* @throws IllegalArgumentException if temperature is out of range
* @default null (API default, typically ~0.7)
*/
public AnthropicChatModelBuilder temperature(Double temperature);
/**
* Sets nucleus sampling threshold.
* Model considers tokens with top-p cumulative probability mass.
*
* @param topP nucleus sampling parameter, must be null or in range (0.0, 1.0]
* @return this builder for method chaining, never null
* @throws IllegalArgumentException if topP is out of range
* @default null (API default, typically 1.0)
*/
public AnthropicChatModelBuilder topP(Double topP);
/**
* Sets top-K sampling parameter.
* Model samples from K most likely next tokens.
*
* @param topK top-K parameter, must be null or >= 0
* @return this builder for method chaining, never null
* @throws IllegalArgumentException if topK is negative
* @default null (API default, model-dependent)
*/
public AnthropicChatModelBuilder topK(Integer topK);
/**
* Sets maximum number of tokens to generate in response.
* Model stops generating after this many tokens.
*
* @param maxTokens maximum output tokens, must be null or > 0
* @return this builder for method chaining, never null
* @throws IllegalArgumentException if maxTokens is not positive
* @default 1024
*/
public AnthropicChatModelBuilder maxTokens(Integer maxTokens);
/**
* Sets custom stop sequences that halt generation.
* Generation stops when any sequence is encountered.
*
* @param stopSequences list of stop strings, may be null (max 4 sequences)
* @return this builder for method chaining, never null
* @throws IllegalArgumentException if more than 4 sequences provided
* @default null (no custom stop sequences)
*/
public AnthropicChatModelBuilder stopSequences(List<String> stopSequences);
/**
* Sets response format for structured output (e.g., JSON mode).
*
* @param responseFormat desired response format, may be null
* @return this builder for method chaining, never null
* @default null (plain text)
*/
public AnthropicChatModelBuilder responseFormat(ResponseFormat responseFormat);
/**
* Sets custom parameters for advanced/experimental API features.
* Parameters are passed directly to API request body.
*
* @param customParameters map of parameter names to values, may be null
* @return this builder for method chaining, never null
* @default null (no custom parameters)
*/
public AnthropicChatModelBuilder customParameters(Map<String, Object> customParameters);
}Usage Example:
AnthropicChatModel model = AnthropicChatModel.builder()
.apiKey(apiKey)
.modelName(AnthropicChatModelName.CLAUDE_SONNET_4_5_20250929)
.temperature(0.7) // Controls randomness (0.0-1.0)
.topP(0.9) // Nucleus sampling
.topK(40) // Top-K sampling
.maxTokens(2048) // Max output tokens, default 1024
.stopSequences(List.of("END", "STOP"))
.build();
// Using customParameters for advanced API features
AnthropicChatModel modelWithCustom = AnthropicChatModel.builder()
.apiKey(apiKey)
.modelName(modelName)
.customParameters(Map.of(
"custom_feature", "value",
"experimental_flag", true
))
.build();Common Pitfalls:
❌ DON'T set temperature > 1.0
.temperature(1.5) // Throws IllegalArgumentException✅ DO use valid range
.temperature(0.7) // Valid: 0.0 to 1.0❌ DON'T provide more than 4 stop sequences
.stopSequences(List.of("1", "2", "3", "4", "5")) // Throws IllegalArgumentException✅ DO limit to 4 sequences
.stopSequences(List.of("END", "STOP", "DONE")) // Valid: max 4Performance Notes:
Configure tools (functions) that the model can call.
package dev.langchain4j.model.anthropic;
import dev.langchain4j.agent.tool.ToolSpecification;
import dev.langchain4j.model.chat.request.ToolChoice;
import java.util.List;
import java.util.Set;
public class AnthropicChatModelBuilder {
/**
* Sets tool specifications from a list.
*
* @param toolSpecifications list of tool specifications, may be null
* @return this builder for method chaining, never null
* @default null (no tools)
*/
public AnthropicChatModelBuilder toolSpecifications(List<ToolSpecification> toolSpecifications);
/**
* Sets tool specifications from varargs.
*
* @param toolSpecifications tool specifications array, may be null
* @return this builder for method chaining, never null
* @default null (no tools)
*/
public AnthropicChatModelBuilder toolSpecifications(ToolSpecification... toolSpecifications);
/**
* Sets tool choice strategy (AUTO, REQUIRED, NONE).
* AUTO: model decides whether to use tools.
* REQUIRED: model must use at least one tool.
* NONE: model cannot use tools.
*
* @param toolChoice tool choice strategy, may be null
* @return this builder for method chaining, never null
* @default ToolChoice.AUTO
*/
public AnthropicChatModelBuilder toolChoice(ToolChoice toolChoice);
/**
* Sets specific tool name that must be used when toolChoice is REQUIRED.
* Only valid when toolChoice is REQUIRED.
*
* @param toolChoiceName name of required tool, may be null
* @return this builder for method chaining, never null
* @throws IllegalArgumentException if toolChoiceName specified without REQUIRED toolChoice
* @default null (any tool can be used)
*/
public AnthropicChatModelBuilder toolChoiceName(String toolChoiceName);
/**
* Disables parallel tool execution when true.
* When false, model can call multiple tools simultaneously.
* When true, model calls tools sequentially one at a time.
*
* @param disableParallelToolUse whether to disable parallel execution, may be null
* @return this builder for method chaining, never null
* @default false (parallel execution enabled)
*/
public AnthropicChatModelBuilder disableParallelToolUse(Boolean disableParallelToolUse);
/**
* Enables strict schema validation for tool parameters.
* When enabled, API validates tool arguments against schema strictly.
*
* @param strictTools whether to enable strict validation, may be null
* @return this builder for method chaining, never null
* @default false
*/
public AnthropicChatModelBuilder strictTools(Boolean strictTools);
/**
* Sets which metadata keys from ToolSpecification.metadata() to send to API.
* Only specified keys are included in API request.
*
* @param toolMetadataKeysToSend set of metadata key names, may be null
* @return this builder for method chaining, never null
* @default empty set (no metadata sent)
*/
public AnthropicChatModelBuilder toolMetadataKeysToSend(Set<String> toolMetadataKeysToSend);
/**
* Sets which metadata keys from ToolSpecification.metadata() to send to API (varargs).
*
* @param toolMetadataKeysToSend metadata key names, may be null
* @return this builder for method chaining, never null
* @default empty set (no metadata sent)
*/
public AnthropicChatModelBuilder toolMetadataKeysToSend(String... toolMetadataKeysToSend);
}Usage Example:
import dev.langchain4j.agent.tool.ToolSpecification;
import dev.langchain4j.model.chat.request.ToolChoice;
ToolSpecification weatherTool = ToolSpecification.builder()
.name("get_weather")
.description("Get current weather")
.parameters(/* JSON schema */)
.build();
AnthropicChatModel model = AnthropicChatModel.builder()
.apiKey(apiKey)
.modelName(AnthropicChatModelName.CLAUDE_SONNET_4_5_20250929)
.toolSpecifications(weatherTool)
.toolChoice(ToolChoice.AUTO) // or ANY, REQUIRED, NONE
.disableParallelToolUse(false) // Allow parallel tool calls
.strictTools(true) // Strict schema validation
.build();Error Handling:
IllegalArgumentException: toolChoiceName set without REQUIRED toolChoiceRuntimeException: Tool schema validation fails when strictTools enabledRuntimeException: Tool not found when toolChoiceName references non-existent toolCommon Pitfalls:
❌ DON'T specify toolChoiceName without REQUIRED
.toolChoice(ToolChoice.AUTO)
.toolChoiceName("my_tool") // Invalid combination✅ DO use together with REQUIRED
.toolChoice(ToolChoice.REQUIRED)
.toolChoiceName("my_tool") // ValidPerformance Notes:
Configure Anthropic server-side tools like web search.
package dev.langchain4j.model.anthropic;
import java.util.List;
/**
* EXPERIMENTAL: Server tools API is in beta and may change.
*/
public class AnthropicChatModelBuilder {
/**
* Sets server-side tools executed by Anthropic (e.g., web_search, code_execution).
* EXPERIMENTAL: This API is in beta and subject to change.
*
* @param serverTools list of server tool configurations, may be null
* @return this builder for method chaining, never null
* @default null (no server tools)
*/
public AnthropicChatModelBuilder serverTools(List<AnthropicServerTool> serverTools);
/**
* Sets server-side tools from varargs.
* EXPERIMENTAL: This API is in beta and subject to change.
*
* @param serverTools server tool configurations array, may be null
* @return this builder for method chaining, never null
* @default null (no server tools)
*/
public AnthropicChatModelBuilder serverTools(AnthropicServerTool... serverTools);
/**
* Controls whether server tool results are included in AiMessage attributes.
* When true, results available via response.aiMessage().attributes().get("server_tool_results").
*
* @param returnServerToolResults whether to include results in response, may be null
* @return this builder for method chaining, never null
* @default false (results not returned)
*/
public AnthropicChatModelBuilder returnServerToolResults(Boolean returnServerToolResults);
}Usage Example:
import dev.langchain4j.model.anthropic.AnthropicServerTool;
AnthropicServerTool webSearch = AnthropicServerTool.builder()
.type("web_search_20250305")
.name("web_search")
.addAttribute("max_uses", 5)
.addAttribute("allowed_domains", List.of("wikipedia.org"))
.build();
AnthropicChatModel model = AnthropicChatModel.builder()
.apiKey(apiKey)
.modelName(AnthropicChatModelName.CLAUDE_SONNET_4_5_20250929)
.serverTools(webSearch)
.returnServerToolResults(true) // Include results in AiMessage attributes
.build();Error Handling:
RuntimeException: Server tool not available for API keyRuntimeException: Invalid server tool configurationRuntimeException: max_uses exceeded during requestCommon Pitfalls:
❌ DON'T forget to enable returnServerToolResults
.serverTools(webSearch)
// Results not accessible without returnServerToolResults(true)✅ DO enable to access results
.serverTools(webSearch)
.returnServerToolResults(true) // Results available in attributesPerformance Notes:
Enable caching of system messages and tools to reduce costs.
package dev.langchain4j.model.anthropic;
public class AnthropicChatModelBuilder {
/**
* Enables caching of system messages to reduce input token costs.
* Requires beta feature flag "prompt-caching-2024-07-31" or later.
* First request creates cache, subsequent requests read from cache.
* Cache TTL is typically 5 minutes.
*
* @param cacheSystemMessages whether to cache system messages, may be null
* @return this builder for method chaining, never null
* @default false
*/
public AnthropicChatModelBuilder cacheSystemMessages(Boolean cacheSystemMessages);
/**
* Enables caching of tool definitions to reduce input token costs.
* Requires beta feature flag "prompt-caching-2024-07-31" or later.
* First request creates cache, subsequent requests read from cache.
* Cache TTL is typically 5 minutes.
*
* @param cacheTools whether to cache tool definitions, may be null
* @return this builder for method chaining, never null
* @default false
*/
public AnthropicChatModelBuilder cacheTools(Boolean cacheTools);
}Usage Example:
AnthropicChatModel model = AnthropicChatModel.builder()
.apiKey(apiKey)
.modelName(AnthropicChatModelName.CLAUDE_SONNET_4_5_20250929)
.cacheSystemMessages(true) // Cache system prompts
.cacheTools(true) // Cache tool definitions
.build();
// Cache metrics available in response metadata
ChatResponse response = model.chat(request);
AnthropicChatResponseMetadata metadata =
(AnthropicChatResponseMetadata) response.metadata();
AnthropicTokenUsage usage = metadata.tokenUsage();
Integer cacheCreated = usage.cacheCreationInputTokens();
Integer cacheRead = usage.cacheReadInputTokens();Error Handling:
RuntimeException: Caching not enabled for API key (requires beta access)Common Pitfalls:
❌ DON'T enable caching without beta flag
.cacheSystemMessages(true) // Fails if beta not set✅ DO set beta flag first
.beta("prompt-caching-2024-07-31")
.cacheSystemMessages(true) // ValidPerformance Notes:
Enable Claude's reasoning mode with thinking/reasoning capabilities.
package dev.langchain4j.model.anthropic;
public class AnthropicChatModelBuilder {
/**
* Enables extended thinking/reasoning mode.
* Only supported on compatible models (Opus 4.5+).
* Value "enabled" activates thinking mode.
*
* @param thinkingType thinking mode type ("enabled" or null), may be null
* @return this builder for method chaining, never null
* @throws RuntimeException if model doesn't support thinking
* @default null (thinking disabled)
*/
public AnthropicChatModelBuilder thinkingType(String thinkingType);
/**
* Sets token budget for thinking/reasoning phase.
* Higher budgets allow more complex reasoning.
* Thinking tokens count separately from output tokens.
*
* @param thinkingBudgetTokens maximum tokens for thinking, must be null or > 0
* @return this builder for method chaining, never null
* @throws IllegalArgumentException if budget is not positive
* @default null (model default, typically 1000-2000)
*/
public AnthropicChatModelBuilder thinkingBudgetTokens(Integer thinkingBudgetTokens);
/**
* Controls whether thinking text is included in response.
* When true, thinking available via response.aiMessage().thinking().
* When false, thinking happens but text not returned.
*
* @param returnThinking whether to return thinking text, may be null
* @return this builder for method chaining, never null
* @default false (thinking not returned)
*/
public AnthropicChatModelBuilder returnThinking(Boolean returnThinking);
/**
* Controls whether thinking is sent in follow-up messages.
* When true, previous thinking context sent in conversation.
* When false, thinking reset for each message.
*
* @param sendThinking whether to send thinking in follow-ups, may be null
* @return this builder for method chaining, never null
* @default true (thinking context maintained)
*/
public AnthropicChatModelBuilder sendThinking(Boolean sendThinking);
}Usage Example:
AnthropicChatModel model = AnthropicChatModel.builder()
.apiKey(apiKey)
.modelName(AnthropicChatModelName.CLAUDE_OPUS_4_5_20251101)
.thinkingType("enabled") // Enable thinking mode
.thinkingBudgetTokens(10000) // Token budget for thinking
.returnThinking(true) // Return thinking text in response
.sendThinking(true) // Send thinking in follow-ups (default)
.build();
ChatResponse response = model.chat(request);
String thinking = response.aiMessage().thinking();
String answer = response.aiMessage().text();Error Handling:
RuntimeException: Thinking not supported on selected modelRuntimeException: Thinking budget exceeded during generationIllegalArgumentException: thinkingBudgetTokens not positiveModel Compatibility:
Performance Notes:
Configure logging, listeners, and retry behavior.
package dev.langchain4j.model.anthropic;
import org.slf4j.Logger;
import dev.langchain4j.model.chat.listener.ChatModelListener;
import java.util.List;
public class AnthropicChatModelBuilder {
/**
* Enables logging of HTTP request details.
* Logs request URL, headers, and body.
*
* @param logRequests whether to log requests, may be null
* @return this builder for method chaining, never null
* @default false
*/
public AnthropicChatModelBuilder logRequests(Boolean logRequests);
/**
* Enables logging of HTTP response details.
* Logs response status, headers, and body.
*
* @param logResponses whether to log responses, may be null
* @return this builder for method chaining, never null
* @default false
*/
public AnthropicChatModelBuilder logResponses(Boolean logResponses);
/**
* Sets custom SLF4J logger for model operations.
*
* @param logger custom logger instance, may be null
* @return this builder for method chaining, never null
* @default logger named after AnthropicChatModel class
*/
public AnthropicChatModelBuilder logger(Logger logger);
/**
* Sets chat model listeners for monitoring requests and responses.
* Listeners invoked before request and after response/error.
*
* @param listeners list of listener instances, may be null
* @return this builder for method chaining, never null
* @default empty list (no listeners)
*/
public AnthropicChatModelBuilder listeners(List<ChatModelListener> listeners);
/**
* Sets maximum number of retry attempts for failed requests.
* Retries on transient errors (rate limits, timeouts, 5xx).
* Uses exponential backoff between retries.
*
* @param maxRetries maximum retry attempts, must be null or >= 0
* @return this builder for method chaining, never null
* @throws IllegalArgumentException if maxRetries is negative
* @default 2
*/
public AnthropicChatModelBuilder maxRetries(Integer maxRetries);
}Usage Example:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import dev.langchain4j.model.chat.listener.ChatModelListener;
Logger customLogger = LoggerFactory.getLogger("MyLogger");
AnthropicChatModel model = AnthropicChatModel.builder()
.apiKey(apiKey)
.modelName(AnthropicChatModelName.CLAUDE_SONNET_4_5_20250929)
.logRequests(true) // Log HTTP requests
.logResponses(true) // Log HTTP responses
.logger(customLogger) // Custom SLF4J logger
.maxRetries(3) // Retry failed requests (default: 2)
.listeners(List.of(/* listeners */))
.build();Error Handling:
IllegalArgumentException: maxRetries negativeCommon Pitfalls:
❌ DON'T log responses in production (sensitive data)
.logResponses(true) // May log API keys, user data✅ DO limit logging to development
.logRequests(isDevelopment)
.logResponses(false) // Never log responsesPerformance Notes:
Additional configuration options.
package dev.langchain4j.model.anthropic;
import dev.langchain4j.model.chat.request.ChatRequestParameters;
import dev.langchain4j.model.Capability;
import java.util.Set;
public class AnthropicChatModelBuilder {
/**
* Sets default request parameters applied to all requests.
* Per-request parameters override these defaults.
*
* @param parameters default parameters, may be null
* @return this builder for method chaining, never null
* @default null (no defaults)
*/
public AnthropicChatModelBuilder defaultRequestParameters(ChatRequestParameters parameters);
/**
* Sets capabilities advertised by this model instance (varargs).
* Controls feature detection by LangChain4j framework.
*
* @param supportedCapabilities capability constants, may be null
* @return this builder for method chaining, never null
* @default auto-detected based on model configuration
*/
public AnthropicChatModelBuilder supportedCapabilities(Capability... supportedCapabilities);
/**
* Sets capabilities advertised by this model instance (set).
* Controls feature detection by LangChain4j framework.
*
* @param supportedCapabilities set of capabilities, may be null
* @return this builder for method chaining, never null
* @default auto-detected based on model configuration
*/
public AnthropicChatModelBuilder supportedCapabilities(Set<Capability> supportedCapabilities);
/**
* Builds the configured AnthropicChatModel instance.
* Thread-safe after construction.
*
* @return configured model instance, never null
* @throws IllegalStateException if required parameters missing (apiKey)
* @throws IllegalArgumentException if configuration invalid
*/
public AnthropicChatModel build();
}Usage Example:
import dev.langchain4j.model.chat.request.ChatRequestParameters;
// Set default request parameters that apply to all requests
ChatRequestParameters defaults = ChatRequestParameters.builder()
.modelName("claude-sonnet-4-5-20250929")
.temperature(0.7)
.maxOutputTokens(2048)
.build();
AnthropicChatModel model = AnthropicChatModel.builder()
.apiKey(apiKey)
.defaultRequestParameters(defaults)
.build();Error Handling:
IllegalStateException: apiKey not setIllegalArgumentException: Invalid parameter combinationThread Safety:
Send messages and receive responses.
package dev.langchain4j.model.anthropic;
import dev.langchain4j.model.chat.request.ChatRequest;
import dev.langchain4j.model.chat.response.ChatResponse;
public class AnthropicChatModel {
/**
* Executes synchronous chat request and blocks until response received.
* Thread-safe; can be called concurrently from multiple threads.
*
* @param chatRequest request containing messages and parameters, must not be null
* @return response with AI message and metadata, never null
* @throws IllegalArgumentException if chatRequest null or messages invalid
* @throws RuntimeException if API request fails, times out, or rate limited
*/
public ChatResponse doChat(ChatRequest chatRequest);
}Usage Example:
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.data.message.SystemMessage;
import dev.langchain4j.model.chat.request.ChatRequest;
import dev.langchain4j.model.chat.response.ChatResponse;
// Build chat request
ChatRequest request = ChatRequest.builder()
.messages(
SystemMessage.from("You are a helpful assistant."),
UserMessage.from("What is the capital of France?")
)
.build();
// Execute chat
ChatResponse response = model.doChat(request);
// Extract response
String answer = response.aiMessage().text();
System.out.println(answer);
// Access metadata
AnthropicChatResponseMetadata metadata =
(AnthropicChatResponseMetadata) response.metadata();
System.out.println("Model: " + metadata.modelName());
System.out.println("Tokens: " + metadata.tokenUsage().totalTokenCount());Error Handling:
IllegalArgumentException: null request or invalid messagesRuntimeException: HTTP error (4xx/5xx), timeout, network failureRuntimeException: Rate limit exceeded (even after retries)RuntimeException: Invalid API key or insufficient permissionsCommon Pitfalls:
❌ DON'T reuse ChatRequest with modifications
ChatRequest req = ChatRequest.builder().messages(...).build();
// ChatRequest is immutable; modifications require new builder✅ DO create new request for each call
ChatRequest req1 = ChatRequest.builder().messages(...).build();
ChatRequest req2 = ChatRequest.builder().messages(...).build();Performance Notes:
Send images in user messages (Base64-encoded with MIME type).
Supported Image MIME Types:
image/jpegimage/pngimage/gifimage/webpimport dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.data.message.ImageContent;
import dev.langchain4j.data.message.TextContent;
import dev.langchain4j.data.image.Image;
// Load image as Base64
String base64Image = /* Base64-encoded image data */;
Image image = Image.builder()
.base64Data(base64Image)
.mimeType("image/jpeg") // or image/png, image/gif, image/webp
.build();
UserMessage message = UserMessage.from(
ImageContent.from(image),
TextContent.from("What's in this image?")
);
ChatRequest request = ChatRequest.builder()
.messages(message)
.build();
ChatResponse response = model.doChat(request);Error Handling:
IllegalArgumentException: Unsupported MIME typeRuntimeException: Image too large (>5MB recommended)RuntimeException: Invalid Base64 encodingCommon Pitfalls:
❌ DON'T send image URLs directly
Image.builder().url("https://...").build() // Not supported✅ DO use Base64 encoding
Image.builder().base64Data(base64).mimeType("image/jpeg").build()Size Constraints:
Send PDF documents in user messages (URL or Base64-encoded).
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.data.message.PdfFileContent;
import dev.langchain4j.data.message.TextContent;
// Option 1: PDF from Base64
String base64Pdf = /* Base64-encoded PDF data */;
PdfFileContent pdfContent = PdfFileContent.from(base64Pdf, "application/pdf");
UserMessage message = UserMessage.from(
pdfContent,
TextContent.from("Summarize this document")
);
// Option 2: PDF from URL (if supported by underlying API)
PdfFileContent pdfFromUrl = PdfFileContent.from("https://example.com/document.pdf");
ChatRequest request = ChatRequest.builder()
.messages(UserMessage.from(pdfFromUrl, TextContent.from("What are the main points?")))
.build();
ChatResponse response = model.doChat(request);Error Handling:
RuntimeException: PDF too large (>32MB recommended)RuntimeException: Invalid PDF format or corrupted fileRuntimeException: URL not accessible (if using URL method)Size Constraints:
Get model metadata and capabilities.
package dev.langchain4j.model.anthropic;
import dev.langchain4j.model.chat.listener.ChatModelListener;
import dev.langchain4j.model.ModelProvider;
import dev.langchain4j.model.chat.request.ChatRequestParameters;
import dev.langchain4j.model.Capability;
import java.util.List;
import java.util.Set;
public class AnthropicChatModel {
/**
* Returns registered chat model listeners.
*
* @return unmodifiable list of listeners, never null (may be empty)
*/
public List<ChatModelListener> listeners();
/**
* Returns model provider (always ANTHROPIC).
*
* @return ANTHROPIC constant, never null
*/
public ModelProvider provider();
/**
* Returns default request parameters set during construction.
*
* @return default parameters or null if not configured
*/
public ChatRequestParameters defaultRequestParameters();
/**
* Returns capabilities supported by this model instance.
*
* @return set of capabilities, never null
*/
public Set<Capability> supportedCapabilities();
}Usage Example:
ModelProvider provider = model.provider(); // Returns ANTHROPIC
ChatRequestParameters defaults = model.defaultRequestParameters();
String modelName = defaults.modelName();
Integer maxTokens = defaults.maxOutputTokens();
Set<Capability> capabilities = model.supportedCapabilities();package dev.langchain4j.model.chat.request;
import dev.langchain4j.data.message.ChatMessage;
import java.util.List;
/**
* Request object for chat API calls.
*/
public class ChatRequest {
/**
* Creates new builder for ChatRequest.
*
* @return new builder instance, never null
*/
public static Builder builder();
/**
* Returns list of messages in conversation.
*
* @return list of messages, never null (must contain at least 1 message)
*/
public List<ChatMessage> messages();
/**
* Returns request-specific parameters.
*
* @return parameters or null if using model defaults
*/
public ChatRequestParameters parameters();
}package dev.langchain4j.model.chat.response;
import dev.langchain4j.data.message.AiMessage;
import dev.langchain4j.model.chat.response.ChatResponseMetadata;
/**
* Response object from chat API calls.
*/
public class ChatResponse {
/**
* Creates new builder for ChatResponse.
*
* @return new builder instance, never null
*/
public static Builder builder();
/**
* Returns AI-generated message.
*
* @return AI message, never null
*/
public AiMessage aiMessage();
/**
* Returns response metadata with token usage and model info.
* Cast to AnthropicChatResponseMetadata for Anthropic-specific fields.
*
* @return metadata, never null
*/
public ChatResponseMetadata metadata();
}package dev.langchain4j.model;
/**
* Enum of supported model providers.
*/
public enum ModelProvider {
/** Anthropic (Claude) models */
ANTHROPIC;
}package dev.langchain4j.model.chat.request;
/**
* Strategy for tool selection during chat.
*/
public enum ToolChoice {
/** Model decides whether to use tools */
AUTO,
/** Model must use at least one tool */
REQUIRED,
/** Model cannot use tools */
NONE;
}package dev.langchain4j.model;
/**
* Model capabilities for feature detection.
*/
public enum Capability {
/** Basic chat capabilities */
CHAT,
/** Streaming response support */
STREAMING,
/** Tool/function calling support */
TOOLS,
/** Vision (image input) support */
VISION,
/** Multimodal (images, PDFs, etc.) support */
MULTIMODALITY;
}ResponseFormat type is from langchain4j-core for structured output controlHttpClientBuilder is from dev.langchain4j.http.client for custom HTTP configurationLogger is org.slf4j.Logger for SLF4J-compatible loggingInstall with Tessl CLI
npx tessl i tessl/maven-dev-langchain4j--langchain4j-anthropic