0
# Messages API
1
2
The Messages API is the primary interface for interacting with Claude models to generate text, use tools, and engage in conversations.
3
4
## Message Service
5
6
### MessageService { .api }
7
8
**Location**: `com.anthropic.services.blocking.MessageService`
9
10
**Description**: Synchronous service interface for Messages API operations.
11
12
**Methods**:
13
```java
14
fun withRawResponse(): WithRawResponse
15
fun withOptions(modifier: Consumer<ClientOptions.Builder>): MessageService
16
fun batches(): BatchService
17
fun create(params: MessageCreateParams): Message
18
fun create(params: MessageCreateParams, requestOptions: RequestOptions): Message
19
fun createStreaming(params: MessageCreateParams): StreamResponse<RawMessageStreamEvent>
20
fun createStreaming(params: MessageCreateParams, requestOptions: RequestOptions): StreamResponse<RawMessageStreamEvent>
21
fun countTokens(params: MessageCountTokensParams): MessageTokensCount
22
fun countTokens(params: MessageCountTokensParams, requestOptions: RequestOptions): MessageTokensCount
23
```
24
25
**Example**:
26
```java
27
import com.anthropic.client.AnthropicClient;
28
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
29
import com.anthropic.models.messages.Message;
30
import com.anthropic.models.messages.MessageCreateParams;
31
import com.anthropic.models.messages.Model;
32
33
AnthropicClient client = AnthropicOkHttpClient.fromEnv();
34
35
MessageCreateParams params = MessageCreateParams.builder()
36
.maxTokens(1024L)
37
.addUserMessage("Hello, Claude")
38
.model(Model.CLAUDE_SONNET_4_5)
39
.build();
40
41
Message message = client.messages().create(params);
42
```
43
44
### MessageServiceAsync { .api }
45
46
**Location**: `com.anthropic.services.async.MessageServiceAsync`
47
48
**Description**: Asynchronous service interface for Messages API operations.
49
50
**Methods**:
51
```java
52
fun withRawResponse(): WithRawResponse
53
fun withOptions(modifier: Consumer<ClientOptions.Builder>): MessageServiceAsync
54
fun batches(): BatchServiceAsync
55
fun create(params: MessageCreateParams): CompletableFuture<Message>
56
fun create(params: MessageCreateParams, requestOptions: RequestOptions): CompletableFuture<Message>
57
fun createStreaming(params: MessageCreateParams): AsyncStreamResponse<RawMessageStreamEvent>
58
fun createStreaming(params: MessageCreateParams, requestOptions: RequestOptions): AsyncStreamResponse<RawMessageStreamEvent>
59
fun countTokens(params: MessageCountTokensParams): CompletableFuture<MessageTokensCount>
60
fun countTokens(params: MessageCountTokensParams, requestOptions: RequestOptions): CompletableFuture<MessageTokensCount>
61
```
62
63
**Example**:
64
```java
65
import com.anthropic.client.AnthropicClientAsync;
66
import com.anthropic.client.okhttp.AnthropicOkHttpClientAsync;
67
import com.anthropic.models.messages.Message;
68
import java.util.concurrent.CompletableFuture;
69
70
AnthropicClientAsync client = AnthropicOkHttpClientAsync.fromEnv();
71
72
CompletableFuture<Message> messageFuture = client.messages().create(params);
73
messageFuture.thenAccept(message -> {
74
System.out.println(message.content());
75
});
76
```
77
78
## Creating Messages
79
80
### MessageCreateParams { .api }
81
82
**Location**: `com.anthropic.models.messages.MessageCreateParams`
83
84
**Description**: Parameters for creating a message request. Built using the builder pattern.
85
86
**Properties**:
87
```java
88
fun maxTokens(): Long
89
fun messages(): List<MessageParam>
90
fun model(): Model
91
fun metadata(): Optional<Metadata>
92
fun serviceTier(): Optional<ServiceTier>
93
fun stopSequences(): Optional<List<String>>
94
fun system(): Optional<System>
95
fun temperature(): Optional<Double>
96
fun thinking(): Optional<ThinkingConfigParam>
97
fun toolChoice(): Optional<ToolChoice>
98
fun tools(): Optional<List<ToolUnion>>
99
fun topK(): Optional<Long>
100
fun topP(): Optional<Double>
101
```
102
103
**Builder Methods**:
104
```java
105
MessageCreateParams.builder()
106
.maxTokens(Long maxTokens)
107
.messages(List<MessageParam> messages)
108
.addMessage(MessageParam message)
109
.addUserMessage(String content)
110
.addAssistantMessage(String content)
111
.model(Model model)
112
.model(String value)
113
.metadata(Metadata metadata)
114
.serviceTier(ServiceTier serviceTier)
115
.stopSequences(List<String> stopSequences)
116
.system(String system)
117
.temperature(Double temperature)
118
.thinking(ThinkingConfigParam thinking)
119
.enabledThinking(Long budgetTokens)
120
.toolChoice(ToolChoice toolChoice)
121
.tools(List<ToolUnion> tools)
122
.addTool(Tool tool)
123
.topK(Long topK)
124
.topP(Double topP)
125
.build()
126
```
127
128
**Example**:
129
```java
130
import com.anthropic.models.messages.MessageCreateParams;
131
import com.anthropic.models.messages.Model;
132
133
MessageCreateParams params = MessageCreateParams.builder()
134
.maxTokens(1024L)
135
.addUserMessage("What is the capital of France?")
136
.model(Model.CLAUDE_SONNET_4_5)
137
.temperature(0.7)
138
.topP(0.9)
139
.build();
140
```
141
142
## Message Response
143
144
### Message { .api }
145
146
**Location**: `com.anthropic.models.messages.Message`
147
148
**Description**: Represents a message response from the API containing the model's generated content.
149
150
**Properties**:
151
```java
152
fun id(): String
153
fun content(): List<ContentBlock>
154
fun model(): Model
155
fun stopReason(): Optional<StopReason>
156
fun stopSequence(): Optional<String>
157
fun usage(): Usage
158
```
159
160
**Builder Methods**:
161
```java
162
Message.builder()
163
.id(String id)
164
.content(List<ContentBlock> content)
165
.addContent(ContentBlock content)
166
.addContent(TextBlock text)
167
.addContent(ThinkingBlock thinking)
168
.addContent(ToolUseBlock toolUse)
169
.model(Model model)
170
.stopReason(StopReason stopReason)
171
.stopSequence(String stopSequence)
172
.usage(Usage usage)
173
.build()
174
```
175
176
**Example**:
177
```java
178
Message message = client.messages().create(params);
179
180
System.out.println("Message ID: " + message.id());
181
System.out.println("Model: " + message.model().asString());
182
System.out.println("Stop Reason: " + message.stopReason().orElse(null));
183
184
message.content().forEach(block -> {
185
if (block.isText()) {
186
TextBlock textBlock = block.asText();
187
System.out.println("Text: " + textBlock.text());
188
}
189
});
190
191
Usage usage = message.usage();
192
System.out.println("Input tokens: " + usage.inputTokens());
193
System.out.println("Output tokens: " + usage.outputTokens());
194
```
195
196
## Content Blocks
197
198
### ContentBlock { .api }
199
200
**Location**: `com.anthropic.models.messages.ContentBlock`
201
202
**Description**: Union type representing different content block types in a message response.
203
204
**Variants**:
205
- `TextBlock` - Text content generated by the model
206
- `ThinkingBlock` - Extended thinking content (when enabled)
207
- `RedactedThinkingBlock` - Redacted thinking content
208
- `ToolUseBlock` - Tool use request from the model
209
- `ServerToolUseBlock` - Server-side tool use
210
- `WebSearchToolResultBlock` - Web search results
211
212
**Methods**:
213
```java
214
fun text(): Optional<TextBlock>
215
fun thinking(): Optional<ThinkingBlock>
216
fun toolUse(): Optional<ToolUseBlock>
217
fun isText(): Boolean
218
fun isThinking(): Boolean
219
fun isToolUse(): Boolean
220
fun asText(): TextBlock
221
fun asThinking(): ThinkingBlock
222
fun asToolUse(): ToolUseBlock
223
fun <T> accept(visitor: Visitor<T>): T
224
```
225
226
**Static Factory Methods**:
227
```java
228
@JvmStatic fun ofText(text: TextBlock): ContentBlock
229
@JvmStatic fun ofThinking(thinking: ThinkingBlock): ContentBlock
230
@JvmStatic fun ofToolUse(toolUse: ToolUseBlock): ContentBlock
231
```
232
233
**Example (Type Checking)**:
234
```java
235
message.content().forEach(block -> {
236
if (block.isText()) {
237
TextBlock text = block.asText();
238
System.out.println("Text: " + text.text());
239
} else if (block.isThinking()) {
240
ThinkingBlock thinking = block.asThinking();
241
System.out.println("Thinking: " + thinking.thinking());
242
} else if (block.isToolUse()) {
243
ToolUseBlock toolUse = block.asToolUse();
244
System.out.println("Tool: " + toolUse.name());
245
}
246
});
247
```
248
249
**Example (Visitor Pattern)**:
250
```java
251
block.accept(new ContentBlock.Visitor<Void>() {
252
@Override
253
public Void visitText(TextBlock text) {
254
System.out.println("Text: " + text.text());
255
return null;
256
}
257
258
@Override
259
public Void visitThinking(ThinkingBlock thinking) {
260
System.out.println("Thinking: " + thinking.thinking());
261
return null;
262
}
263
264
@Override
265
public Void visitToolUse(ToolUseBlock toolUse) {
266
System.out.println("Tool: " + toolUse.name());
267
return null;
268
}
269
});
270
```
271
272
### TextBlock { .api }
273
274
**Location**: `com.anthropic.models.messages.TextBlock`
275
276
**Description**: Text content block containing model-generated text.
277
278
**Properties**:
279
```java
280
fun text(): String
281
fun type(): String
282
```
283
284
**Example**:
285
```java
286
TextBlock textBlock = block.asText();
287
String content = textBlock.text();
288
```
289
290
### ThinkingBlock { .api }
291
292
**Location**: `com.anthropic.models.messages.ThinkingBlock`
293
294
**Description**: Extended thinking content block containing the model's reasoning process.
295
296
**Properties**:
297
```java
298
fun thinking(): String
299
fun type(): String
300
```
301
302
**Example**:
303
```java
304
MessageCreateParams params = MessageCreateParams.builder()
305
.maxTokens(4096L)
306
.addUserMessage("Solve this complex problem step by step...")
307
.model(Model.CLAUDE_SONNET_4_5)
308
.enabledThinking(2000L) // Enable thinking with token budget
309
.build();
310
311
Message message = client.messages().create(params);
312
313
message.content().forEach(block -> {
314
if (block.isThinking()) {
315
ThinkingBlock thinking = block.asThinking();
316
System.out.println("Model's reasoning: " + thinking.thinking());
317
}
318
});
319
```
320
321
### ToolUseBlock { .api }
322
323
**Location**: `com.anthropic.models.messages.ToolUseBlock`
324
325
**Description**: Tool use request block containing information about a tool the model wants to use.
326
327
**Properties**:
328
```java
329
fun id(): String
330
fun name(): String
331
fun input(): JsonValue
332
fun type(): String
333
```
334
335
**Example**:
336
```java
337
message.content().forEach(block -> {
338
if (block.isToolUse()) {
339
ToolUseBlock toolUse = block.asToolUse();
340
System.out.println("Tool ID: " + toolUse.id());
341
System.out.println("Tool Name: " + toolUse.name());
342
System.out.println("Tool Input: " + toolUse.input());
343
}
344
});
345
```
346
347
## Content Block Parameters
348
349
### ContentBlockParam { .api }
350
351
**Location**: `com.anthropic.models.messages.ContentBlockParam`
352
353
**Description**: Union type for input content blocks in message requests. Used when constructing messages with mixed content types.
354
355
**Variants**:
356
- Text content blocks
357
- Image content blocks
358
- Document content blocks
359
- Tool use content blocks
360
- Tool result content blocks
361
362
**Example**:
363
```java
364
import com.anthropic.models.messages.ContentBlockParam;
365
import com.anthropic.models.messages.MessageParam;
366
367
MessageParam userMessage = MessageParam.builder()
368
.role(MessageParam.Role.USER)
369
.addContent(ContentBlockParam.ofText("Analyze this text"))
370
.addContent(ContentBlockParam.ofImage(imageSource))
371
.build();
372
```
373
374
## Message Parameters
375
376
### MessageParam { .api }
377
378
**Location**: `com.anthropic.models.messages.MessageParam`
379
380
**Description**: Input message parameter for requests, representing a single message in a conversation.
381
382
**Properties**:
383
```java
384
fun role(): Role
385
fun content(): Content
386
```
387
388
**Role Enum**:
389
```java
390
enum Role {
391
USER, // "user" - User messages
392
ASSISTANT // "assistant" - Assistant messages
393
}
394
```
395
396
**Builder Methods**:
397
```java
398
MessageParam.builder()
399
.role(Role role)
400
.content(String text)
401
.content(List<ContentBlockParam> blocks)
402
.addContent(ContentBlockParam block)
403
.build()
404
```
405
406
**Example**:
407
```java
408
import com.anthropic.models.messages.MessageParam;
409
410
MessageCreateParams params = MessageCreateParams.builder()
411
.maxTokens(1024L)
412
.model(Model.CLAUDE_SONNET_4_5)
413
.addMessage(MessageParam.builder()
414
.role(MessageParam.Role.USER)
415
.content("What is the weather today?")
416
.build())
417
.addMessage(MessageParam.builder()
418
.role(MessageParam.Role.ASSISTANT)
419
.content("I don't have access to current weather data.")
420
.build())
421
.addMessage(MessageParam.builder()
422
.role(MessageParam.Role.USER)
423
.content("Can you explain how weather forecasting works?")
424
.build())
425
.build();
426
```
427
428
## Models
429
430
### Model { .api }
431
432
**Location**: `com.anthropic.models.messages.Model`
433
434
**Description**: Enum representing available Claude models.
435
436
**Constants**:
437
```java
438
// Claude 4.5 Sonnet - Best for agents and coding
439
CLAUDE_SONNET_4_5 // "claude-sonnet-4-5"
440
CLAUDE_SONNET_4_5_20250929 // "claude-sonnet-4-5-20250929"
441
442
// Claude 4 Sonnet - High-performance with extended thinking
443
CLAUDE_SONNET_4_20250514 // "claude-sonnet-4-20250514"
444
CLAUDE_SONNET_4_0 // "claude-sonnet-4-0"
445
CLAUDE_4_SONNET_20250514 // "claude-4-sonnet-20250514"
446
447
// Claude 4 Opus - Most capable models
448
CLAUDE_OPUS_4_0 // "claude-opus-4-0"
449
CLAUDE_OPUS_4_20250514 // "claude-opus-4-20250514"
450
CLAUDE_4_OPUS_20250514 // "claude-4-opus-20250514"
451
CLAUDE_OPUS_4_1_20250805 // "claude-opus-4-1-20250805"
452
453
// Claude 4.5 Haiku - Hybrid model
454
CLAUDE_HAIKU_4_5 // "claude-haiku-4-5"
455
CLAUDE_HAIKU_4_5_20251001 // "claude-haiku-4-5-20251001"
456
457
// Claude 3.5 Haiku - Fastest
458
CLAUDE_3_5_HAIKU_LATEST // "claude-3-5-haiku-latest"
459
CLAUDE_3_5_HAIKU_20241022 // "claude-3-5-haiku-20241022"
460
461
// Claude 3.7 Sonnet (DEPRECATED - End-of-life: February 19, 2026)
462
CLAUDE_3_7_SONNET_LATEST // "claude-3-7-sonnet-latest"
463
CLAUDE_3_7_SONNET_20250219 // "claude-3-7-sonnet-20250219"
464
465
// Claude 3 Opus (DEPRECATED - End-of-life: January 5, 2026)
466
CLAUDE_3_OPUS_LATEST // "claude-3-opus-latest"
467
CLAUDE_3_OPUS_20240229 // "claude-3-opus-20240229"
468
469
// Claude 3 Haiku - Previous fast model
470
CLAUDE_3_HAIKU_20240307 // "claude-3-haiku-20240307"
471
```
472
473
**Methods**:
474
```java
475
@JvmStatic fun of(value: String): Model
476
fun asString(): String
477
fun known(): Known
478
fun value(): Value
479
```
480
481
**Example**:
482
```java
483
import com.anthropic.models.messages.Model;
484
485
// Using predefined constants
486
MessageCreateParams params1 = MessageCreateParams.builder()
487
.model(Model.CLAUDE_SONNET_4_5)
488
.build();
489
490
// Using custom model string
491
MessageCreateParams params2 = MessageCreateParams.builder()
492
.model("claude-new-model")
493
.build();
494
495
// Creating from string
496
Model model = Model.of("claude-sonnet-4-5");
497
System.out.println(model.asString()); // "claude-sonnet-4-5"
498
499
// Handling unknown models
500
Model customModel = Model.of("claude-future-model");
501
if (customModel.value() == Model.Value._UNKNOWN) {
502
System.out.println("Using unknown model");
503
}
504
```
505
506
## Service Tier
507
508
### ServiceTier { .api }
509
510
**Location**: `com.anthropic.models.messages.MessageCreateParams.ServiceTier`
511
512
**Description**: Enum controlling which service tier is used for processing the message request. Affects response speed and throughput.
513
514
**Constants**:
515
```java
516
AUTO // "auto" - Automatically select the best tier based on availability
517
STANDARD_ONLY // "standard_only" - Use only standard tier processing
518
```
519
520
**Methods**:
521
```java
522
@JvmStatic fun of(value: String): ServiceTier
523
fun asString(): String
524
```
525
526
**Example**:
527
```java
528
import com.anthropic.models.messages.MessageCreateParams;
529
import com.anthropic.models.messages.MessageCreateParams.ServiceTier;
530
531
MessageCreateParams params = MessageCreateParams.builder()
532
.maxTokens(1024L)
533
.addUserMessage("Hello, Claude")
534
.model(Model.CLAUDE_SONNET_4_5)
535
.serviceTier(ServiceTier.STANDARD_ONLY)
536
.build();
537
```
538
539
## Sampling Parameters
540
541
### Temperature { .api }
542
543
**Description**: Controls randomness in the model's output. Lower values make output more focused and deterministic; higher values make it more creative and varied.
544
545
**Type**: `Double`
546
547
**Range**: 0.0 to 1.0
548
549
**Default**: 1.0
550
551
**Example**:
552
```java
553
// More deterministic (good for factual tasks)
554
MessageCreateParams params1 = MessageCreateParams.builder()
555
.maxTokens(1024L)
556
.addUserMessage("What is 2 + 2?")
557
.model(Model.CLAUDE_SONNET_4_5)
558
.temperature(0.0)
559
.build();
560
561
// More creative (good for brainstorming)
562
MessageCreateParams params2 = MessageCreateParams.builder()
563
.maxTokens(1024L)
564
.addUserMessage("Write a creative story")
565
.model(Model.CLAUDE_SONNET_4_5)
566
.temperature(0.9)
567
.build();
568
```
569
570
### Top K { .api }
571
572
**Description**: Limits sampling to the K most likely tokens at each step.
573
574
**Type**: `Long`
575
576
**Example**:
577
```java
578
MessageCreateParams params = MessageCreateParams.builder()
579
.maxTokens(1024L)
580
.addUserMessage("Complete this sentence...")
581
.model(Model.CLAUDE_SONNET_4_5)
582
.topK(40L)
583
.build();
584
```
585
586
### Top P { .api }
587
588
**Description**: Nucleus sampling - limits sampling to tokens whose cumulative probability is below the threshold P.
589
590
**Type**: `Double`
591
592
**Range**: 0.0 to 1.0
593
594
**Example**:
595
```java
596
MessageCreateParams params = MessageCreateParams.builder()
597
.maxTokens(1024L)
598
.addUserMessage("Generate text...")
599
.model(Model.CLAUDE_SONNET_4_5)
600
.topP(0.9)
601
.build();
602
```
603
604
## Stop Sequences
605
606
### Stop Sequences { .api }
607
608
**Description**: Custom sequences that will cause the model to stop generating tokens when encountered.
609
610
**Type**: `List<String>`
611
612
**Example**:
613
```java
614
MessageCreateParams params = MessageCreateParams.builder()
615
.maxTokens(1024L)
616
.addUserMessage("List three items:")
617
.model(Model.CLAUDE_SONNET_4_5)
618
.stopSequences(List.of("\n\n", "END", "###"))
619
.build();
620
621
Message message = client.messages().create(params);
622
623
// Check which stop sequence was triggered
624
message.stopSequence().ifPresent(seq -> {
625
System.out.println("Stopped at sequence: " + seq);
626
});
627
628
if (message.stopReason().isPresent()) {
629
StopReason reason = message.stopReason().get();
630
if (reason == StopReason.STOP_SEQUENCE) {
631
System.out.println("Generation stopped due to stop sequence");
632
}
633
}
634
```
635
636
## System Prompts
637
638
### System Parameter { .api }
639
640
**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.
641
642
**Type**: `String` or `System` (complex type)
643
644
**Example (Simple)**:
645
```java
646
MessageCreateParams params = MessageCreateParams.builder()
647
.maxTokens(1024L)
648
.system("You are a helpful assistant specializing in mathematics.")
649
.addUserMessage("Explain calculus")
650
.model(Model.CLAUDE_SONNET_4_5)
651
.build();
652
```
653
654
**Example (Multi-turn with System)**:
655
```java
656
String systemPrompt = """
657
You are a technical support assistant.
658
Always be polite and professional.
659
Provide step-by-step solutions.
660
If you don't know something, say so clearly.
661
""";
662
663
MessageCreateParams params = MessageCreateParams.builder()
664
.maxTokens(1024L)
665
.system(systemPrompt)
666
.addUserMessage("My computer won't start")
667
.model(Model.CLAUDE_SONNET_4_5)
668
.build();
669
```
670
671
## Metadata
672
673
### Metadata { .api }
674
675
**Location**: `com.anthropic.models.messages.Metadata`
676
677
**Description**: Request metadata for tracking and identification purposes.
678
679
**Properties**:
680
```java
681
fun userId(): Optional<String>
682
```
683
684
**Builder Methods**:
685
```java
686
Metadata.builder()
687
.userId(String userId)
688
.build()
689
```
690
691
**Example**:
692
```java
693
import com.anthropic.models.messages.Metadata;
694
695
MessageCreateParams params = MessageCreateParams.builder()
696
.maxTokens(1024L)
697
.addUserMessage("Hello!")
698
.model(Model.CLAUDE_SONNET_4_5)
699
.metadata(Metadata.builder()
700
.userId("user-12345")
701
.build())
702
.build();
703
```
704
705
## Token Counting
706
707
### countTokens Method { .api }
708
709
**Description**: Count the number of tokens in a message before sending it to the API. Useful for estimating costs and staying within model limits.
710
711
**Methods**:
712
```java
713
fun countTokens(params: MessageCountTokensParams): MessageTokensCount
714
fun countTokens(params: MessageCountTokensParams, requestOptions: RequestOptions): MessageTokensCount
715
```
716
717
**Example**:
718
```java
719
import com.anthropic.models.messages.MessageCountTokensParams;
720
import com.anthropic.models.messages.MessageTokensCount;
721
722
MessageCountTokensParams countParams = MessageCountTokensParams.builder()
723
.model(Model.CLAUDE_SONNET_4_5)
724
.addUserMessage("How many tokens is this message?")
725
.system("You are a helpful assistant")
726
.build();
727
728
MessageTokensCount tokenCount = client.messages().countTokens(countParams);
729
System.out.println("Input tokens: " + tokenCount.inputTokens());
730
```
731
732
### MessageTokensCount { .api }
733
734
**Location**: `com.anthropic.models.messages.MessageTokensCount`
735
736
**Description**: Token count response containing the number of tokens in the input.
737
738
**Properties**:
739
```java
740
fun inputTokens(): Long
741
```
742
743
**Example**:
744
```java
745
MessageTokensCount count = client.messages().countTokens(params);
746
747
long tokens = count.inputTokens();
748
System.out.println("This message will use " + tokens + " input tokens");
749
750
// Check if within limits
751
long maxInputTokens = 100000L; // Example limit
752
if (tokens > maxInputTokens) {
753
System.out.println("Message exceeds token limit!");
754
}
755
```
756
757
## Batch Operations
758
759
### Batch Service { .api }
760
761
**Description**: Access to batch operations for processing multiple messages efficiently.
762
763
**Synchronous**: `com.anthropic.services.blocking.messages.BatchService`
764
**Asynchronous**: `com.anthropic.services.async.messages.BatchServiceAsync`
765
766
**Access**:
767
```java
768
BatchService batchService = client.messages().batches();
769
BatchServiceAsync asyncBatchService = client.async().messages().batches();
770
```
771
772
**Example**:
773
```java
774
import com.anthropic.services.blocking.messages.BatchService;
775
776
// Access batch service
777
BatchService batches = client.messages().batches();
778
779
// Batch operations for processing multiple messages
780
// See Batch API documentation for detailed usage
781
```
782
783
### MessageBatch { .api }
784
785
**Location**: `com.anthropic.models.messages.batches.MessageBatch`
786
787
**Description**: Message batch object representing a batch of message requests.
788
789
**Example**:
790
```java
791
import com.anthropic.models.messages.batches.MessageBatch;
792
import com.anthropic.models.messages.batches.BatchListPage;
793
794
// List batches
795
BatchListPage page = client.messages().batches().list();
796
for (MessageBatch batch : page.autoPager()) {
797
System.out.println("Batch ID: " + batch.id());
798
}
799
```
800
801
## Usage Information
802
803
### Usage { .api }
804
805
**Location**: `com.anthropic.models.messages.Usage`
806
807
**Description**: Token usage information for a message, showing how many tokens were used for input and output.
808
809
**Properties**:
810
```java
811
fun inputTokens(): Long
812
fun outputTokens(): Long
813
fun cacheCreationInputTokens(): Optional<Long>
814
fun cacheReadInputTokens(): Optional<Long>
815
```
816
817
**Example**:
818
```java
819
Message message = client.messages().create(params);
820
821
Usage usage = message.usage();
822
823
System.out.println("Input tokens: " + usage.inputTokens());
824
System.out.println("Output tokens: " + usage.outputTokens());
825
826
// Cache-related tokens (if prompt caching is used)
827
usage.cacheCreationInputTokens().ifPresent(tokens -> {
828
System.out.println("Cache creation tokens: " + tokens);
829
});
830
831
usage.cacheReadInputTokens().ifPresent(tokens -> {
832
System.out.println("Cache read tokens: " + tokens);
833
});
834
835
// Calculate total tokens
836
long totalTokens = usage.inputTokens() + usage.outputTokens();
837
System.out.println("Total tokens used: " + totalTokens);
838
```
839
840
## Complete Example
841
842
### Multi-turn Conversation with All Features { .api }
843
844
```java
845
import com.anthropic.client.AnthropicClient;
846
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
847
import com.anthropic.models.messages.*;
848
849
public class MessagesExample {
850
public static void main(String[] args) {
851
// Initialize client
852
AnthropicClient client = AnthropicOkHttpClient.fromEnv();
853
854
// Build message with multiple parameters
855
MessageCreateParams params = MessageCreateParams.builder()
856
.maxTokens(2048L)
857
.model(Model.CLAUDE_SONNET_4_5)
858
.temperature(0.7)
859
.topP(0.9)
860
.system("You are an expert programmer who explains concepts clearly.")
861
.metadata(Metadata.builder()
862
.userId("user-123")
863
.build())
864
.stopSequences(List.of("\n\nHuman:", "END"))
865
// First user message
866
.addUserMessage("What is recursion?")
867
.build();
868
869
// Count tokens before sending
870
MessageCountTokensParams countParams = MessageCountTokensParams.builder()
871
.model(Model.CLAUDE_SONNET_4_5)
872
.addUserMessage("What is recursion?")
873
.system("You are an expert programmer who explains concepts clearly.")
874
.build();
875
876
MessageTokensCount tokenCount = client.messages().countTokens(countParams);
877
System.out.println("Request will use " + tokenCount.inputTokens() + " input tokens");
878
879
// Create message
880
Message message = client.messages().create(params);
881
882
// Process response
883
System.out.println("Message ID: " + message.id());
884
System.out.println("Model: " + message.model().asString());
885
886
// Extract text content
887
message.content().forEach(block -> {
888
if (block.isText()) {
889
System.out.println("Assistant: " + block.asText().text());
890
}
891
});
892
893
// Check stop reason
894
message.stopReason().ifPresent(reason -> {
895
System.out.println("Stop reason: " + reason.asString());
896
});
897
898
message.stopSequence().ifPresent(seq -> {
899
System.out.println("Stop sequence: " + seq);
900
});
901
902
// Usage information
903
Usage usage = message.usage();
904
System.out.println("\nToken usage:");
905
System.out.println(" Input: " + usage.inputTokens());
906
System.out.println(" Output: " + usage.outputTokens());
907
System.out.println(" Total: " + (usage.inputTokens() + usage.outputTokens()));
908
909
// Continue conversation
910
MessageCreateParams followUp = params.toBuilder()
911
.messages(List.of(
912
MessageParam.builder()
913
.role(MessageParam.Role.USER)
914
.content("What is recursion?")
915
.build(),
916
MessageParam.builder()
917
.role(MessageParam.Role.ASSISTANT)
918
.content(message.content().get(0).asText().text())
919
.build(),
920
MessageParam.builder()
921
.role(MessageParam.Role.USER)
922
.content("Can you give me a code example?")
923
.build()
924
))
925
.build();
926
927
Message response = client.messages().create(followUp);
928
response.content().forEach(block -> {
929
if (block.isText()) {
930
System.out.println("\nAssistant: " + block.asText().text());
931
}
932
});
933
}
934
}
935
```
936
937
## Related APIs
938
939
- **Streaming**: See [Streaming API](streaming.md) for real-time message streaming
940
- **Tools**: See [Tools API](tools.md) for function calling and tool use
941
- **Batches**: See [Batch API](batches.md) for batch message processing
942
- **Content Types**: See [Content Types](content-types.md) for images, documents, and multimodal content
943