Class DefaultAnthropicClient
AnthropicClient that provides methods to interact with the
Anthropic API for creating messages, counting tokens, and listing models.
This client handles both synchronous and streaming responses, managing HTTP requests efficiently and processing server-sent events (SSE) for streaming data. It supports detailed logging of requests and responses for debugging purposes.
HTTP Client Configuration
Uses HttpClientBuilderLoader for flexible HTTP client construction with configurable timeouts:
- Connection timeout: defaults to 15 seconds
- Read timeout: defaults to 60 seconds
Request/response logging can be enabled via LoggingHttpClient using builder flags.
Usage Example
DefaultAnthropicClient client = DefaultAnthropicClient.builder()
.baseUrl("https://api.anthropic.com/v1")
.apiKey("your-api-key")
.version("2023-06-01")
.timeout(Duration.ofSeconds(30))
.logRequests(true)
.logResponses(true)
.build();
// Synchronous message creation
AnthropicCreateMessageResponse response = client.createMessage(request);
// Streaming message creation
client.createMessage(request, options, new StreamingChatResponseHandler() {
@Override
public void onPartialResponse(String partialResponse, StreamingHandle handle) {
System.out.print(partialResponse);
}
@Override
public void onCompleteResponse(ChatResponse completeResponse) {
System.out.println("\nComplete: " + completeResponse.aiMessage().text());
}
@Override
public void onError(Throwable error) {
error.printStackTrace();
}
});
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classBuilder for constructingDefaultAnthropicClientinstances. -
Method Summary
Modifier and TypeMethodDescriptionbuilder()Creates a new builder for constructing aDefaultAnthropicClientinstance.countTokens(AnthropicCountTokensRequest request) Counts the number of tokens in a message request.Creates a message synchronously using the Anthropic API.voidcreateMessage(AnthropicCreateMessageRequest request, AnthropicCreateMessageOptions options, StreamingChatResponseHandler handler) Creates a message with streaming response handling.voidcreateMessage(AnthropicCreateMessageRequest request, StreamingChatResponseHandler handler) Creates a message with streaming response handling using default options.Creates a message synchronously and returns both the parsed response and the raw HTTP response.Lists available models from the Anthropic API.
-
Method Details
-
builder
Creates a new builder for constructing aDefaultAnthropicClientinstance.- Returns:
- a new
DefaultAnthropicClient.Builderinstance
-
createMessage
Creates a message synchronously using the Anthropic API.Sends a request to the
/messagesendpoint and blocks until the response is received.- Specified by:
createMessagein classAnthropicClient- Parameters:
request- the message creation request containing the model, messages, and other parameters- Returns:
- the parsed response from the Anthropic API
- Throws:
RuntimeException- if the HTTP request fails or the response cannot be parsed- See Also:
-
createMessageWithRawResponse
Creates a message synchronously and returns both the parsed response and the raw HTTP response.Useful when access to raw HTTP response details (headers, status code) is needed alongside the parsed API response.
- Overrides:
createMessageWithRawResponsein classAnthropicClient- Parameters:
request- the message creation request containing the model, messages, and other parameters- Returns:
- a
ParsedAndRawResponsecontaining both the parsedAnthropicCreateMessageResponseand the rawSuccessfulHttpResponse - Throws:
RuntimeException- if the HTTP request fails or the response cannot be parsed
-
createMessage
public void createMessage(AnthropicCreateMessageRequest request, AnthropicCreateMessageOptions options, StreamingChatResponseHandler handler) Creates a message with streaming response handling.Sends a request to the
/messagesendpoint and processes the response as a stream of server-sent events (SSE). The handler receives callbacks for:- Partial text responses as they arrive
- Partial thinking outputs (if
options.returnThinking()is true) - Partial and complete tool calls
- The complete response when streaming finishes
- Errors if they occur
message_start: Initial message metadata including usage and model infocontent_block_start: Start of a content block (text, thinking, tool_use, server tool results)content_block_delta: Incremental content updatescontent_block_stop: End of a content blockmessage_delta: Message-level updates including stop reason and final usagemessage_stop: End of message, triggers complete response callbackerror: Error event from the API
- Overrides:
createMessagein classAnthropicClient- Parameters:
request- the message creation request (should havestream: true)options- options controlling what data to return (e.g., thinking outputs, server tool results)handler- the callback handler for streaming events- See Also:
-
countTokens
Counts the number of tokens in a message request.Sends a request to the
/messages/count_tokensendpoint to estimate token usage before making an actual message creation request.- Overrides:
countTokensin classAnthropicClient- Parameters:
request- the token counting request containing the messages and model- Returns:
- the response containing the token count
- Throws:
RuntimeException- if the HTTP request fails or the response cannot be parsed
-
listModels
Lists available models from the Anthropic API.Sends a GET request to the
/modelsendpoint to retrieve information about available Claude models.- Overrides:
listModelsin classAnthropicClient- Returns:
- the response containing the list of available models
- Throws:
RuntimeException- if the HTTP request fails or the response cannot be parsed
-
createMessage
public void createMessage(AnthropicCreateMessageRequest request, StreamingChatResponseHandler handler) Creates a message with streaming response handling using default options.Convenience method that calls
createMessage(AnthropicCreateMessageRequest, AnthropicCreateMessageOptions, StreamingChatResponseHandler)with default options (thinking outputs and server tool results disabled).- Specified by:
createMessagein classAnthropicClient- Parameters:
request- the message creation request (should havestream: true)handler- the callback handler for streaming events- See Also:
-