The Anthropic Java SDK provides convenient access to the Anthropic REST API from applications written in Java
The Messages API is the primary interface for interacting with Claude models to generate text, use tools, and engage in conversations.
Location: com.anthropic.services.blocking.MessageService
Description: Synchronous service interface for Messages API operations.
Methods:
fun withRawResponse(): WithRawResponse
fun withOptions(modifier: Consumer<ClientOptions.Builder>): MessageService
fun batches(): BatchService
fun create(params: MessageCreateParams): Message
fun create(params: MessageCreateParams, requestOptions: RequestOptions): Message
fun createStreaming(params: MessageCreateParams): StreamResponse<RawMessageStreamEvent>
fun createStreaming(params: MessageCreateParams, requestOptions: RequestOptions): StreamResponse<RawMessageStreamEvent>
fun countTokens(params: MessageCountTokensParams): MessageTokensCount
fun countTokens(params: MessageCountTokensParams, requestOptions: RequestOptions): MessageTokensCountExample:
import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
import com.anthropic.models.messages.Message;
import com.anthropic.models.messages.MessageCreateParams;
import com.anthropic.models.messages.Model;
AnthropicClient client = AnthropicOkHttpClient.fromEnv();
MessageCreateParams params = MessageCreateParams.builder()
.maxTokens(1024L)
.addUserMessage("Hello, Claude")
.model(Model.CLAUDE_SONNET_4_5)
.build();
Message message = client.messages().create(params);Location: com.anthropic.services.async.MessageServiceAsync
Description: Asynchronous service interface for Messages API operations.
Methods:
fun withRawResponse(): WithRawResponse
fun withOptions(modifier: Consumer<ClientOptions.Builder>): MessageServiceAsync
fun batches(): BatchServiceAsync
fun create(params: MessageCreateParams): CompletableFuture<Message>
fun create(params: MessageCreateParams, requestOptions: RequestOptions): CompletableFuture<Message>
fun createStreaming(params: MessageCreateParams): AsyncStreamResponse<RawMessageStreamEvent>
fun createStreaming(params: MessageCreateParams, requestOptions: RequestOptions): AsyncStreamResponse<RawMessageStreamEvent>
fun countTokens(params: MessageCountTokensParams): CompletableFuture<MessageTokensCount>
fun countTokens(params: MessageCountTokensParams, requestOptions: RequestOptions): CompletableFuture<MessageTokensCount>Example:
import com.anthropic.client.AnthropicClientAsync;
import com.anthropic.client.okhttp.AnthropicOkHttpClientAsync;
import com.anthropic.models.messages.Message;
import java.util.concurrent.CompletableFuture;
AnthropicClientAsync client = AnthropicOkHttpClientAsync.fromEnv();
CompletableFuture<Message> messageFuture = client.messages().create(params);
messageFuture.thenAccept(message -> {
System.out.println(message.content());
});Location: com.anthropic.models.messages.MessageCreateParams
Description: Parameters for creating a message request. Built using the builder pattern.
Properties:
fun maxTokens(): Long
fun messages(): List<MessageParam>
fun model(): Model
fun metadata(): Optional<Metadata>
fun serviceTier(): Optional<ServiceTier>
fun stopSequences(): Optional<List<String>>
fun system(): Optional<System>
fun temperature(): Optional<Double>
fun thinking(): Optional<ThinkingConfigParam>
fun toolChoice(): Optional<ToolChoice>
fun tools(): Optional<List<ToolUnion>>
fun topK(): Optional<Long>
fun topP(): Optional<Double>Builder Methods:
MessageCreateParams.builder()
.maxTokens(Long maxTokens)
.messages(List<MessageParam> messages)
.addMessage(MessageParam message)
.addUserMessage(String content)
.addAssistantMessage(String content)
.model(Model model)
.model(String value)
.metadata(Metadata metadata)
.serviceTier(ServiceTier serviceTier)
.stopSequences(List<String> stopSequences)
.system(String system)
.temperature(Double temperature)
.thinking(ThinkingConfigParam thinking)
.enabledThinking(Long budgetTokens)
.toolChoice(ToolChoice toolChoice)
.tools(List<ToolUnion> tools)
.addTool(Tool tool)
.topK(Long topK)
.topP(Double topP)
.build()Example:
import com.anthropic.models.messages.MessageCreateParams;
import com.anthropic.models.messages.Model;
MessageCreateParams params = MessageCreateParams.builder()
.maxTokens(1024L)
.addUserMessage("What is the capital of France?")
.model(Model.CLAUDE_SONNET_4_5)
.temperature(0.7)
.topP(0.9)
.build();Location: com.anthropic.models.messages.Message
Description: Represents a message response from the API containing the model's generated content.
Properties:
fun id(): String
fun content(): List<ContentBlock>
fun model(): Model
fun stopReason(): Optional<StopReason>
fun stopSequence(): Optional<String>
fun usage(): UsageBuilder Methods:
Message.builder()
.id(String id)
.content(List<ContentBlock> content)
.addContent(ContentBlock content)
.addContent(TextBlock text)
.addContent(ThinkingBlock thinking)
.addContent(ToolUseBlock toolUse)
.model(Model model)
.stopReason(StopReason stopReason)
.stopSequence(String stopSequence)
.usage(Usage usage)
.build()Example:
Message message = client.messages().create(params);
System.out.println("Message ID: " + message.id());
System.out.println("Model: " + message.model().asString());
System.out.println("Stop Reason: " + message.stopReason().orElse(null));
message.content().forEach(block -> {
if (block.isText()) {
TextBlock textBlock = block.asText();
System.out.println("Text: " + textBlock.text());
}
});
Usage usage = message.usage();
System.out.println("Input tokens: " + usage.inputTokens());
System.out.println("Output tokens: " + usage.outputTokens());Location: com.anthropic.models.messages.ContentBlock
Description: Union type representing different content block types in a message response.
Variants:
TextBlock - Text content generated by the modelThinkingBlock - Extended thinking content (when enabled)RedactedThinkingBlock - Redacted thinking contentToolUseBlock - Tool use request from the modelServerToolUseBlock - Server-side tool useWebSearchToolResultBlock - Web search resultsMethods:
fun text(): Optional<TextBlock>
fun thinking(): Optional<ThinkingBlock>
fun toolUse(): Optional<ToolUseBlock>
fun isText(): Boolean
fun isThinking(): Boolean
fun isToolUse(): Boolean
fun asText(): TextBlock
fun asThinking(): ThinkingBlock
fun asToolUse(): ToolUseBlock
fun <T> accept(visitor: Visitor<T>): TStatic Factory Methods:
@JvmStatic fun ofText(text: TextBlock): ContentBlock
@JvmStatic fun ofThinking(thinking: ThinkingBlock): ContentBlock
@JvmStatic fun ofToolUse(toolUse: ToolUseBlock): ContentBlockExample (Type Checking):
message.content().forEach(block -> {
if (block.isText()) {
TextBlock text = block.asText();
System.out.println("Text: " + text.text());
} else if (block.isThinking()) {
ThinkingBlock thinking = block.asThinking();
System.out.println("Thinking: " + thinking.thinking());
} else if (block.isToolUse()) {
ToolUseBlock toolUse = block.asToolUse();
System.out.println("Tool: " + toolUse.name());
}
});Example (Visitor Pattern):
block.accept(new ContentBlock.Visitor<Void>() {
@Override
public Void visitText(TextBlock text) {
System.out.println("Text: " + text.text());
return null;
}
@Override
public Void visitThinking(ThinkingBlock thinking) {
System.out.println("Thinking: " + thinking.thinking());
return null;
}
@Override
public Void visitToolUse(ToolUseBlock toolUse) {
System.out.println("Tool: " + toolUse.name());
return null;
}
});Location: com.anthropic.models.messages.TextBlock
Description: Text content block containing model-generated text.
Properties:
fun text(): String
fun type(): StringExample:
TextBlock textBlock = block.asText();
String content = textBlock.text();Location: com.anthropic.models.messages.ThinkingBlock
Description: Extended thinking content block containing the model's reasoning process.
Properties:
fun thinking(): String
fun type(): StringExample:
MessageCreateParams params = MessageCreateParams.builder()
.maxTokens(4096L)
.addUserMessage("Solve this complex problem step by step...")
.model(Model.CLAUDE_SONNET_4_5)
.enabledThinking(2000L) // Enable thinking with token budget
.build();
Message message = client.messages().create(params);
message.content().forEach(block -> {
if (block.isThinking()) {
ThinkingBlock thinking = block.asThinking();
System.out.println("Model's reasoning: " + thinking.thinking());
}
});Location: com.anthropic.models.messages.ToolUseBlock
Description: Tool use request block containing information about a tool the model wants to use.
Properties:
fun id(): String
fun name(): String
fun input(): JsonValue
fun type(): StringExample:
message.content().forEach(block -> {
if (block.isToolUse()) {
ToolUseBlock toolUse = block.asToolUse();
System.out.println("Tool ID: " + toolUse.id());
System.out.println("Tool Name: " + toolUse.name());
System.out.println("Tool Input: " + toolUse.input());
}
});Location: com.anthropic.models.messages.ContentBlockParam
Description: Union type for input content blocks in message requests. Used when constructing messages with mixed content types.
Variants:
Example:
import com.anthropic.models.messages.ContentBlockParam;
import com.anthropic.models.messages.MessageParam;
MessageParam userMessage = MessageParam.builder()
.role(MessageParam.Role.USER)
.addContent(ContentBlockParam.ofText("Analyze this text"))
.addContent(ContentBlockParam.ofImage(imageSource))
.build();Location: com.anthropic.models.messages.MessageParam
Description: Input message parameter for requests, representing a single message in a conversation.
Properties:
fun role(): Role
fun content(): ContentRole Enum:
enum Role {
USER, // "user" - User messages
ASSISTANT // "assistant" - Assistant messages
}Builder Methods:
MessageParam.builder()
.role(Role role)
.content(String text)
.content(List<ContentBlockParam> blocks)
.addContent(ContentBlockParam block)
.build()Example:
import com.anthropic.models.messages.MessageParam;
MessageCreateParams params = MessageCreateParams.builder()
.maxTokens(1024L)
.model(Model.CLAUDE_SONNET_4_5)
.addMessage(MessageParam.builder()
.role(MessageParam.Role.USER)
.content("What is the weather today?")
.build())
.addMessage(MessageParam.builder()
.role(MessageParam.Role.ASSISTANT)
.content("I don't have access to current weather data.")
.build())
.addMessage(MessageParam.builder()
.role(MessageParam.Role.USER)
.content("Can you explain how weather forecasting works?")
.build())
.build();Location: com.anthropic.models.messages.Model
Description: Enum representing available Claude models.
Constants:
// Claude 4.5 Sonnet - Best for agents and coding
CLAUDE_SONNET_4_5 // "claude-sonnet-4-5"
CLAUDE_SONNET_4_5_20250929 // "claude-sonnet-4-5-20250929"
// Claude 4 Sonnet - High-performance with extended thinking
CLAUDE_SONNET_4_20250514 // "claude-sonnet-4-20250514"
CLAUDE_SONNET_4_0 // "claude-sonnet-4-0"
CLAUDE_4_SONNET_20250514 // "claude-4-sonnet-20250514"
// Claude 4 Opus - Most capable models
CLAUDE_OPUS_4_0 // "claude-opus-4-0"
CLAUDE_OPUS_4_20250514 // "claude-opus-4-20250514"
CLAUDE_4_OPUS_20250514 // "claude-4-opus-20250514"
CLAUDE_OPUS_4_1_20250805 // "claude-opus-4-1-20250805"
// Claude 4.5 Haiku - Hybrid model
CLAUDE_HAIKU_4_5 // "claude-haiku-4-5"
CLAUDE_HAIKU_4_5_20251001 // "claude-haiku-4-5-20251001"
// Claude 3.5 Haiku - Fastest
CLAUDE_3_5_HAIKU_LATEST // "claude-3-5-haiku-latest"
CLAUDE_3_5_HAIKU_20241022 // "claude-3-5-haiku-20241022"
// Claude 3.7 Sonnet (DEPRECATED - End-of-life: February 19, 2026)
CLAUDE_3_7_SONNET_LATEST // "claude-3-7-sonnet-latest"
CLAUDE_3_7_SONNET_20250219 // "claude-3-7-sonnet-20250219"
// Claude 3 Opus (DEPRECATED - End-of-life: January 5, 2026)
CLAUDE_3_OPUS_LATEST // "claude-3-opus-latest"
CLAUDE_3_OPUS_20240229 // "claude-3-opus-20240229"
// Claude 3 Haiku - Previous fast model
CLAUDE_3_HAIKU_20240307 // "claude-3-haiku-20240307"Methods:
@JvmStatic fun of(value: String): Model
fun asString(): String
fun known(): Known
fun value(): ValueExample:
import com.anthropic.models.messages.Model;
// Using predefined constants
MessageCreateParams params1 = MessageCreateParams.builder()
.model(Model.CLAUDE_SONNET_4_5)
.build();
// Using custom model string
MessageCreateParams params2 = MessageCreateParams.builder()
.model("claude-new-model")
.build();
// Creating from string
Model model = Model.of("claude-sonnet-4-5");
System.out.println(model.asString()); // "claude-sonnet-4-5"
// Handling unknown models
Model customModel = Model.of("claude-future-model");
if (customModel.value() == Model.Value._UNKNOWN) {
System.out.println("Using unknown model");
}Location: com.anthropic.models.messages.MessageCreateParams.ServiceTier
Description: Enum controlling which service tier is used for processing the message request. Affects response speed and throughput.
Constants:
AUTO // "auto" - Automatically select the best tier based on availability
STANDARD_ONLY // "standard_only" - Use only standard tier processingMethods:
@JvmStatic fun of(value: String): ServiceTier
fun asString(): StringExample:
import com.anthropic.models.messages.MessageCreateParams;
import com.anthropic.models.messages.MessageCreateParams.ServiceTier;
MessageCreateParams params = MessageCreateParams.builder()
.maxTokens(1024L)
.addUserMessage("Hello, Claude")
.model(Model.CLAUDE_SONNET_4_5)
.serviceTier(ServiceTier.STANDARD_ONLY)
.build();Description: Controls randomness in the model's output. Lower values make output more focused and deterministic; higher values make it more creative and varied.
Type: Double
Range: 0.0 to 1.0
Default: 1.0
Example:
// More deterministic (good for factual tasks)
MessageCreateParams params1 = MessageCreateParams.builder()
.maxTokens(1024L)
.addUserMessage("What is 2 + 2?")
.model(Model.CLAUDE_SONNET_4_5)
.temperature(0.0)
.build();
// More creative (good for brainstorming)
MessageCreateParams params2 = MessageCreateParams.builder()
.maxTokens(1024L)
.addUserMessage("Write a creative story")
.model(Model.CLAUDE_SONNET_4_5)
.temperature(0.9)
.build();Description: Limits sampling to the K most likely tokens at each step.
Type: Long
Example:
MessageCreateParams params = MessageCreateParams.builder()
.maxTokens(1024L)
.addUserMessage("Complete this sentence...")
.model(Model.CLAUDE_SONNET_4_5)
.topK(40L)
.build();Description: Nucleus sampling - limits sampling to tokens whose cumulative probability is below the threshold P.
Type: Double
Range: 0.0 to 1.0
Example:
MessageCreateParams params = MessageCreateParams.builder()
.maxTokens(1024L)
.addUserMessage("Generate text...")
.model(Model.CLAUDE_SONNET_4_5)
.topP(0.9)
.build();Description: Custom sequences that will cause the model to stop generating tokens when encountered.
Type: List<String>
Example:
MessageCreateParams params = MessageCreateParams.builder()
.maxTokens(1024L)
.addUserMessage("List three items:")
.model(Model.CLAUDE_SONNET_4_5)
.stopSequences(List.of("\n\n", "END", "###"))
.build();
Message message = client.messages().create(params);
// Check which stop sequence was triggered
message.stopSequence().ifPresent(seq -> {
System.out.println("Stopped at sequence: " + seq);
});
if (message.stopReason().isPresent()) {
StopReason reason = message.stopReason().get();
if (reason == StopReason.STOP_SEQUENCE) {
System.out.println("Generation stopped due to stop sequence");
}
}Description: System prompt that provides context and instructions to the model. System prompts are processed before user messages and help establish the assistant's behavior.
Type: String or System (complex type)
Example (Simple):
MessageCreateParams params = MessageCreateParams.builder()
.maxTokens(1024L)
.system("You are a helpful assistant specializing in mathematics.")
.addUserMessage("Explain calculus")
.model(Model.CLAUDE_SONNET_4_5)
.build();Example (Multi-turn with System):
String systemPrompt = """
You are a technical support assistant.
Always be polite and professional.
Provide step-by-step solutions.
If you don't know something, say so clearly.
""";
MessageCreateParams params = MessageCreateParams.builder()
.maxTokens(1024L)
.system(systemPrompt)
.addUserMessage("My computer won't start")
.model(Model.CLAUDE_SONNET_4_5)
.build();Location: com.anthropic.models.messages.Metadata
Description: Request metadata for tracking and identification purposes.
Properties:
fun userId(): Optional<String>Builder Methods:
Metadata.builder()
.userId(String userId)
.build()Example:
import com.anthropic.models.messages.Metadata;
MessageCreateParams params = MessageCreateParams.builder()
.maxTokens(1024L)
.addUserMessage("Hello!")
.model(Model.CLAUDE_SONNET_4_5)
.metadata(Metadata.builder()
.userId("user-12345")
.build())
.build();Description: Count the number of tokens in a message before sending it to the API. Useful for estimating costs and staying within model limits.
Methods:
fun countTokens(params: MessageCountTokensParams): MessageTokensCount
fun countTokens(params: MessageCountTokensParams, requestOptions: RequestOptions): MessageTokensCountExample:
import com.anthropic.models.messages.MessageCountTokensParams;
import com.anthropic.models.messages.MessageTokensCount;
MessageCountTokensParams countParams = MessageCountTokensParams.builder()
.model(Model.CLAUDE_SONNET_4_5)
.addUserMessage("How many tokens is this message?")
.system("You are a helpful assistant")
.build();
MessageTokensCount tokenCount = client.messages().countTokens(countParams);
System.out.println("Input tokens: " + tokenCount.inputTokens());Location: com.anthropic.models.messages.MessageTokensCount
Description: Token count response containing the number of tokens in the input.
Properties:
fun inputTokens(): LongExample:
MessageTokensCount count = client.messages().countTokens(params);
long tokens = count.inputTokens();
System.out.println("This message will use " + tokens + " input tokens");
// Check if within limits
long maxInputTokens = 100000L; // Example limit
if (tokens > maxInputTokens) {
System.out.println("Message exceeds token limit!");
}Description: Access to batch operations for processing multiple messages efficiently.
Synchronous: com.anthropic.services.blocking.messages.BatchService
Asynchronous: com.anthropic.services.async.messages.BatchServiceAsync
Access:
BatchService batchService = client.messages().batches();
BatchServiceAsync asyncBatchService = client.async().messages().batches();Example:
import com.anthropic.services.blocking.messages.BatchService;
// Access batch service
BatchService batches = client.messages().batches();
// Batch operations for processing multiple messages
// See Batch API documentation for detailed usageLocation: com.anthropic.models.messages.batches.MessageBatch
Description: Message batch object representing a batch of message requests.
Example:
import com.anthropic.models.messages.batches.MessageBatch;
import com.anthropic.models.messages.batches.BatchListPage;
// List batches
BatchListPage page = client.messages().batches().list();
for (MessageBatch batch : page.autoPager()) {
System.out.println("Batch ID: " + batch.id());
}Location: com.anthropic.models.messages.Usage
Description: Token usage information for a message, showing how many tokens were used for input and output.
Properties:
fun inputTokens(): Long
fun outputTokens(): Long
fun cacheCreationInputTokens(): Optional<Long>
fun cacheReadInputTokens(): Optional<Long>Example:
Message message = client.messages().create(params);
Usage usage = message.usage();
System.out.println("Input tokens: " + usage.inputTokens());
System.out.println("Output tokens: " + usage.outputTokens());
// Cache-related tokens (if prompt caching is used)
usage.cacheCreationInputTokens().ifPresent(tokens -> {
System.out.println("Cache creation tokens: " + tokens);
});
usage.cacheReadInputTokens().ifPresent(tokens -> {
System.out.println("Cache read tokens: " + tokens);
});
// Calculate total tokens
long totalTokens = usage.inputTokens() + usage.outputTokens();
System.out.println("Total tokens used: " + totalTokens);import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
import com.anthropic.models.messages.*;
public class MessagesExample {
public static void main(String[] args) {
// Initialize client
AnthropicClient client = AnthropicOkHttpClient.fromEnv();
// Build message with multiple parameters
MessageCreateParams params = MessageCreateParams.builder()
.maxTokens(2048L)
.model(Model.CLAUDE_SONNET_4_5)
.temperature(0.7)
.topP(0.9)
.system("You are an expert programmer who explains concepts clearly.")
.metadata(Metadata.builder()
.userId("user-123")
.build())
.stopSequences(List.of("\n\nHuman:", "END"))
// First user message
.addUserMessage("What is recursion?")
.build();
// Count tokens before sending
MessageCountTokensParams countParams = MessageCountTokensParams.builder()
.model(Model.CLAUDE_SONNET_4_5)
.addUserMessage("What is recursion?")
.system("You are an expert programmer who explains concepts clearly.")
.build();
MessageTokensCount tokenCount = client.messages().countTokens(countParams);
System.out.println("Request will use " + tokenCount.inputTokens() + " input tokens");
// Create message
Message message = client.messages().create(params);
// Process response
System.out.println("Message ID: " + message.id());
System.out.println("Model: " + message.model().asString());
// Extract text content
message.content().forEach(block -> {
if (block.isText()) {
System.out.println("Assistant: " + block.asText().text());
}
});
// Check stop reason
message.stopReason().ifPresent(reason -> {
System.out.println("Stop reason: " + reason.asString());
});
message.stopSequence().ifPresent(seq -> {
System.out.println("Stop sequence: " + seq);
});
// Usage information
Usage usage = message.usage();
System.out.println("\nToken usage:");
System.out.println(" Input: " + usage.inputTokens());
System.out.println(" Output: " + usage.outputTokens());
System.out.println(" Total: " + (usage.inputTokens() + usage.outputTokens()));
// Continue conversation
MessageCreateParams followUp = params.toBuilder()
.messages(List.of(
MessageParam.builder()
.role(MessageParam.Role.USER)
.content("What is recursion?")
.build(),
MessageParam.builder()
.role(MessageParam.Role.ASSISTANT)
.content(message.content().get(0).asText().text())
.build(),
MessageParam.builder()
.role(MessageParam.Role.USER)
.content("Can you give me a code example?")
.build()
))
.build();
Message response = client.messages().create(followUp);
response.content().forEach(block -> {
if (block.isText()) {
System.out.println("\nAssistant: " + block.asText().text());
}
});
}
}Install with Tessl CLI
npx tessl i tessl/maven-com-anthropic--anthropic-java