Class DefaultAnthropicClient

java.lang.Object
dev.langchain4j.model.anthropic.internal.client.AnthropicClient
dev.langchain4j.model.anthropic.internal.client.DefaultAnthropicClient

public class DefaultAnthropicClient extends AnthropicClient
Default implementation of 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();
    }
});