Repository Public
1---2title: Stop reasons and fallback3url: https://platform.claude.com/docs/en/build-with-claude/handling-stop-reasons4description: Learn what each stop_reason value means and how to handle truncation, tool use, paused turns, and refusals in your application.5---67Every Messages API response includes a `stop_reason` field that tells you why Claude stopped generating. Check this field to decide whether to use the response as-is, continue the conversation, retry, or fall back to another model.89For the full response schema, see the [Messages API reference](https://platform.claude.com/docs/en/api/messages/create).1011## Quick reference1213| Value | When it occurs | What to do |14| -------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |15| [`end_turn`](https://platform.claude.com/docs/en/build-with-claude/handling-stop-reasons#end-turn) | Claude finished its response naturally. | Use the response. |16| [`max_tokens`](https://platform.claude.com/docs/en/build-with-claude/handling-stop-reasons#max-tokens) | The response reached your `max_tokens` limit. | Raise `max_tokens` or [continue the response](https://platform.claude.com/docs/en/build-with-claude/handling-stop-reasons#ensuring-complete-responses). |17| [`stop_sequence`](https://platform.claude.com/docs/en/build-with-claude/handling-stop-reasons#stop-sequence) | Claude emitted one of your `stop_sequences`. | Read `stop_sequence` to see which one fired. |18| [`tool_use`](https://platform.claude.com/docs/en/build-with-claude/handling-stop-reasons#tool-use) | Claude is calling a tool. | Run the tool and return the result. A server tool call still missing its result block completes in a later response. |19| [`pause_turn`](https://platform.claude.com/docs/en/build-with-claude/handling-stop-reasons#pause-turn) | A server-tool loop reached its iteration limit. | Send the assistant content back to continue. |20| [`refusal`](https://platform.claude.com/docs/en/build-with-claude/handling-stop-reasons#refusal) | Claude declined to respond. | Read `stop_details` and [retry on a fallback model](https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback). |21| [`model_context_window_exceeded`](https://platform.claude.com/docs/en/build-with-claude/handling-stop-reasons#model-context-window-exceeded) | The response filled the model's context window. | Treat the response as truncated. |2223## The stop\_reason field2425The `stop_reason` field is part of every successful Messages API response. Unlike errors, which indicate failures in processing your request, `stop_reason` tells you why Claude completed its response generation.2627```json Example response28{29 "id": "msg_01234",30 "type": "message",31 "role": "assistant",32 "content": [33 {34 "type": "text",35 "text": "Here's the answer to your question..."36 }37 ],38 "stop_reason": "end_turn",39 "stop_sequence": null,40 "stop_details": null,41 "usage": {42 "input_tokens": 100,43 "output_tokens": 5044 }45}46```4748## Stop reason values4950### end\_turn5152The most common stop reason. Indicates Claude finished its response naturally.5354<CodeGroup>55 ```bash cURL56 curl https://api.anthropic.com/v1/messages \57 -H "x-api-key: $ANTHROPIC_API_KEY" \58 -H "anthropic-version: 2023-06-01" \59 -H "content-type: application/json" \60 -d '{61 "model": "claude-opus-5",62 "max_tokens": 1024,63 "messages": [{"role": "user", "content": "Hello!"}]64 }' | jq 'if .stop_reason == "end_turn" then (.content[] | select(.type == "text") | .text) else . end'65 ```6667 ```bash CLI68 ant messages create \69 --model claude-opus-5 \70 --max-tokens 1024 \71 --message '{role: user, content: "Hello!"}' \72 --format json | jq 'if .stop_reason == "end_turn" then (.content[] | select(.type == "text") | .text) else . end'73 ```7475 ```python Python76 client = anthropic.Anthropic()7778 response = client.messages.create(79 model="claude-opus-5",80 max_tokens=1024,81 messages=[{"role": "user", "content": "Hello!"}],82 )83 if response.stop_reason == "end_turn":84 # Process the complete response85 for block in response.content:86 if block.type == "text":87 print(block.text)88 ```8990 ```typescript TypeScript91 const client = new Anthropic();9293 const response = await client.messages.create({94 model: "claude-opus-5",95 max_tokens: 1024,96 messages: [{ role: "user", content: "Hello!" }]97 });9899 if (response.stop_reason === "end_turn") {100 // Process the complete response101 const textBlock = response.content.find(102 (block): block is Anthropic.TextBlock => block.type === "text"103 );104 console.log(textBlock?.text);105 }106 ```107108 ```csharp C#109 AnthropicClient client = new();110111 var response = await client.Messages.Create(new MessageCreateParams112 {113 Model = Model.ClaudeOpus5,114 MaxTokens = 1024,115 Messages = [new() { Role = Role.User, Content = "Hello!" }]116 });117118 if (response.StopReason == "end_turn")119 {120 // Process the complete response121 foreach (var block in response.Content)122 {123 if (block.TryPickText(out var textBlock))124 {125 Console.WriteLine(textBlock.Text);126 }127 }128 }129 ```130131 ```go Go132 client := anthropic.NewClient()133134 response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{135 Model: anthropic.ModelClaudeOpus5,136 MaxTokens: 1024,137 Messages: []anthropic.MessageParam{138 anthropic.NewUserMessage(anthropic.NewTextBlock("Hello!")),139 },140 })141 if err != nil {142 log.Fatal(err)143 }144145 if response.StopReason == "end_turn" {146 // Process the complete response147 for _, block := range response.Content {148 if textBlock, ok := block.AsAny().(anthropic.TextBlock); ok {149 fmt.Println(textBlock.Text)150 }151 }152 }153 ```154155 ```java Java156 AnthropicClient client = AnthropicOkHttpClient.fromEnv();157158 Message response = client.messages().create(159 MessageCreateParams.builder()160 .model(Model.CLAUDE_OPUS_5)161 .maxTokens(1024L)162 .addUserMessage("Hello!")163 .build()164 );165166 if (response.stopReason().map(StopReason.END_TURN::equals).orElse(false)) {167 // Process the complete response168 response.content().stream()169 .flatMap(block -> block.text().stream())170 .forEach(textBlock -> IO.println(textBlock.text()));171 }172 ```173174 ```php PHP175 $client = new Client();176177 $response = $client->messages->create(178 maxTokens: 1024,179 messages: [['role' => 'user', 'content' => 'Hello!']],180 model: 'claude-opus-5',181 );182183 if ($response->stopReason === 'end_turn') {184 // Process the complete response185 foreach ($response->content as $block) {186 if ($block->type === 'text') {187 echo $block->text, PHP_EOL;188 }189 }190 }191 ```192193 ```ruby Ruby194 client = Anthropic::Client.new195196 response = client.messages.create(197 model: "claude-opus-5",198 max_tokens: 1024,199 messages: [{ role: "user", content: "Hello!" }]200 )201202 if response.stop_reason == :end_turn203 # Process the complete response204 response.content.each do |block|205 puts block.text if block.type == :text206 end207 end208 ```209</CodeGroup>210211<Accordion title="Empty responses with end_turn">212 Sometimes Claude returns an empty response (exactly 2–3 tokens with no content) with `stop_reason: "end_turn"`. This typically occurs when Claude interprets that the assistant turn is complete, particularly after tool results.213214 **Common causes:**215216 * Adding text blocks immediately after tool results (Claude learns to expect the user to always insert text after tool results, so it ends its turn to follow the pattern)217 * Sending Claude's completed response back without adding anything (Claude already determined it's done, so it will remain done)218219 **How to prevent empty responses:**220221 <CodeGroup exclude="shell">222 ```python Python223 # INCORRECT: Adding text immediately after tool_result224 messages = [225 {"role": "user", "content": "Calculate the sum of 1234 and 5678"},226 {227 "role": "assistant",228 "content": [229 {230 "type": "tool_use",231 "id": "toolu_123",232 "name": "calculator",233 "input": {"operation": "add", "a": 1234, "b": 5678},234 }235 ],236 },237 {238 "role": "user",239 "content": [240 {"type": "tool_result", "tool_use_id": "toolu_123", "content": "6912"},241 {242 "type": "text",243 "text": "Here's the result", # Don't add text after tool_result244 },245 ],246 },247 ]248249 # CORRECT: Send tool results directly without additional text250 messages = [251 {"role": "user", "content": "Calculate the sum of 1234 and 5678"},252 {253 "role": "assistant",254 "content": [255 {256 "type": "tool_use",257 "id": "toolu_123",258 "name": "calculator",259 "input": {"operation": "add", "a": 1234, "b": 5678},260 }261 ],262 },263 {264 "role": "user",265 "content": [266 {"type": "tool_result", "tool_use_id": "toolu_123", "content": "6912"}267 ],268 }, # Just the tool_result, no additional text269 ]270 ```271272 ```typescript TypeScript273 // INCORRECT: Adding text immediately after tool_result274 let messages: Anthropic.MessageParam[] = [275 { role: "user", content: "Calculate the sum of 1234 and 5678" },276 {277 role: "assistant",278 content: [279 {280 type: "tool_use",281 id: "toolu_123",282 name: "calculator",283 input: { operation: "add", a: 1234, b: 5678 }284 }285 ]286 },287 {288 role: "user",289 content: [290 { type: "tool_result", tool_use_id: "toolu_123", content: "6912" },291 { type: "text", text: "Here's the result" } // Don't add text after tool_result292 ]293 }294 ];295296 // CORRECT: Send tool results directly without additional text297 messages = [298 { role: "user", content: "Calculate the sum of 1234 and 5678" },299 {300 role: "assistant",301 content: [302 {303 type: "tool_use",304 id: "toolu_123",305 name: "calculator",306 input: { operation: "add", a: 1234, b: 5678 }307 }308 ]309 },310 {311 role: "user",312 // Just the tool_result, no additional text313 content: [{ type: "tool_result", tool_use_id: "toolu_123", content: "6912" }]314 }315 ];316 ```317318 ```csharp C#319 using System.Text.Json;320 using Anthropic.Models.Messages;321322 var input = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(323 """{"operation":"add","a":1234,"b":5678}"""324 )!;325326 // INCORRECT: Adding text immediately after tool_result327 List<MessageParam> messages =328 [329 new() { Role = Role.User, Content = "Calculate the sum of 1234 and 5678" },330 new()331 {332 Role = Role.Assistant,333 Content = new List<ContentBlockParam>334 {335 new ToolUseBlockParam { ID = "toolu_123", Name = "calculator", Input = input }336 }337 },338 new()339 {340 Role = Role.User,341 Content = new List<ContentBlockParam>342 {343 new ToolResultBlockParam { ToolUseID = "toolu_123", Content = "6912" },344 new TextBlockParam { Text = "Here's the result" } // Don't add text after tool_result345 }346 }347 ];348349 // CORRECT: Send tool results directly without additional text350 messages =351 [352 new() { Role = Role.User, Content = "Calculate the sum of 1234 and 5678" },353 new()354 {355 Role = Role.Assistant,356 Content = new List<ContentBlockParam>357 {358 new ToolUseBlockParam { ID = "toolu_123", Name = "calculator", Input = input }359 }360 },361 new()362 {363 Role = Role.User,364 // Just the tool_result, no additional text365 Content = new List<ContentBlockParam>366 {367 new ToolResultBlockParam { ToolUseID = "toolu_123", Content = "6912" }368 }369 }370 ];371 ```372373 ```go Go374 input := map[string]any{"operation": "add", "a": 1234, "b": 5678}375376 // INCORRECT: Adding text immediately after tool_result377 messages := []anthropic.MessageParam{378 anthropic.NewUserMessage(anthropic.NewTextBlock("Calculate the sum of 1234 and 5678")),379 anthropic.NewAssistantMessage(380 anthropic.NewToolUseBlock("toolu_123", input, "calculator"),381 ),382 anthropic.NewUserMessage(383 anthropic.NewToolResultBlock("toolu_123", "6912", false),384 anthropic.NewTextBlock("Here's the result"), // Don't add text after tool_result385 ),386 }387388 // CORRECT: Send tool results directly without additional text389 messages = []anthropic.MessageParam{390 anthropic.NewUserMessage(anthropic.NewTextBlock("Calculate the sum of 1234 and 5678")),391 anthropic.NewAssistantMessage(392 anthropic.NewToolUseBlock("toolu_123", input, "calculator"),393 ),394 // Just the tool_result, no additional text395 anthropic.NewUserMessage(396 anthropic.NewToolResultBlock("toolu_123", "6912", false),397 ),398 }399 ```400401 ```java Java402 ToolUseBlockParam toolUse = ToolUseBlockParam.builder()403 .id("toolu_123")404 .name("calculator")405 .input(ToolUseBlockParam.Input.builder()406 .putAdditionalProperty("operation", JsonValue.from("add"))407 .putAdditionalProperty("a", JsonValue.from(1234))408 .putAdditionalProperty("b", JsonValue.from(5678))409 .build())410 .build();411412 // INCORRECT: Adding text immediately after tool_result413 List<MessageParam> messages = List.of(414 MessageParam.builder().role(MessageParam.Role.USER)415 .content("Calculate the sum of 1234 and 5678").build(),416 MessageParam.builder().role(MessageParam.Role.ASSISTANT)417 .contentOfBlockParams(List.of(ContentBlockParam.ofToolUse(toolUse))).build(),418 MessageParam.builder().role(MessageParam.Role.USER)419 .contentOfBlockParams(List.of(420 ContentBlockParam.ofToolResult(421 ToolResultBlockParam.builder().toolUseId("toolu_123").content("6912").build()),422 // Don't add text after tool_result423 ContentBlockParam.ofText(TextBlockParam.builder().text("Here's the result").build())424 )).build()425 );426427 // CORRECT: Send tool results directly without additional text428 messages = List.of(429 MessageParam.builder().role(MessageParam.Role.USER)430 .content("Calculate the sum of 1234 and 5678").build(),431 MessageParam.builder().role(MessageParam.Role.ASSISTANT)432 .contentOfBlockParams(List.of(ContentBlockParam.ofToolUse(toolUse))).build(),433 // Just the tool_result, no additional text434 MessageParam.builder().role(MessageParam.Role.USER)435 .contentOfBlockParams(List.of(436 ContentBlockParam.ofToolResult(437 ToolResultBlockParam.builder().toolUseId("toolu_123").content("6912").build())438 )).build()439 );440 ```441442 ```php PHP443 // INCORRECT: Adding text immediately after tool_result444 $messages = [445 ['role' => 'user', 'content' => 'Calculate the sum of 1234 and 5678'],446 [447 'role' => 'assistant',448 'content' => [449 [450 'type' => 'tool_use',451 'id' => 'toolu_123',452 'name' => 'calculator',453 'input' => ['operation' => 'add', 'a' => 1234, 'b' => 5678],454 ],455 ],456 ],457 [458 'role' => 'user',459 'content' => [460 ['type' => 'tool_result', 'tool_use_id' => 'toolu_123', 'content' => '6912'],461 // Don't add text after tool_result462 ['type' => 'text', 'text' => "Here's the result"],463 ],464 ],465 ];466467 // CORRECT: Send tool results directly without additional text468 $messages = [469 ['role' => 'user', 'content' => 'Calculate the sum of 1234 and 5678'],470 [471 'role' => 'assistant',472 'content' => [473 [474 'type' => 'tool_use',475 'id' => 'toolu_123',476 'name' => 'calculator',477 'input' => ['operation' => 'add', 'a' => 1234, 'b' => 5678],478 ],479 ],480 ],481 [482 'role' => 'user',483 // Just the tool_result, no additional text484 'content' => [485 ['type' => 'tool_result', 'tool_use_id' => 'toolu_123', 'content' => '6912'],486 ],487 ],488 ];489 ```490491 ```ruby Ruby492 # INCORRECT: Adding text immediately after tool_result493 messages = [494 { role: "user", content: "Calculate the sum of 1234 and 5678" },495 {496 role: "assistant",497 content: [498 {499 type: "tool_use",500 id: "toolu_123",501 name: "calculator",502 input: { operation: "add", a: 1234, b: 5678 }503 }504 ]505 },506 {507 role: "user",508 content: [509 { type: "tool_result", tool_use_id: "toolu_123", content: "6912" },510 # Don't add text after tool_result511 { type: "text", text: "Here's the result" }512 ]513 }514 ]515516 # CORRECT: Send tool results directly without additional text517 messages = [518 { role: "user", content: "Calculate the sum of 1234 and 5678" },519 {520 role: "assistant",521 content: [522 {523 type: "tool_use",524 id: "toolu_123",525 name: "calculator",526 input: { operation: "add", a: 1234, b: 5678 }527 }528 ]529 },530 {531 role: "user",532 # Just the tool_result, no additional text533 content: [534 { type: "tool_result", tool_use_id: "toolu_123", content: "6912" }535 ]536 }537 ]538 ```539 </CodeGroup>540541 If you still get empty responses after fixing the message structure, add a continuation prompt in a new user message rather than retrying with the empty response:542543 <CodeGroup exclude="shell">544 ```python Python545 def handle_empty_response(client, messages):546 response = client.messages.create(547 model="claude-opus-5", max_tokens=1024, messages=messages548 )549550 # Check if response is empty551 if response.stop_reason == "end_turn" and not response.content:552 # INCORRECT: Don't just retry with the empty response553 # This won't work because Claude already decided it's done554555 # CORRECT: Add a continuation prompt in a NEW user message556 messages.append({"role": "user", "content": "Please continue"})557558 response = client.messages.create(559 model="claude-opus-5", max_tokens=1024, messages=messages560 )561562 return response563 ```564565 ```typescript TypeScript566 async function handleEmptyResponse(567 client: Anthropic,568 messages: Anthropic.MessageParam[]569 ): Promise<Anthropic.Message> {570 let response = await client.messages.create({571 model: "claude-opus-5",572 max_tokens: 1024,573 messages574 });575576 // Check if response is empty577 if (response.stop_reason === "end_turn" && response.content.length === 0) {578 // INCORRECT: Don't just retry with the empty response579 // This won't work because Claude already decided it's done580581 // CORRECT: Add a continuation prompt in a NEW user message582 messages.push({ role: "user", content: "Please continue" });583584 response = await client.messages.create({585 model: "claude-opus-5",586 max_tokens: 1024,587 messages588 });589 }590591 return response;592 }593 ```594595 ```csharp C#596 static async Task<Message> HandleEmptyResponse(AnthropicClient client, List<MessageParam> messages)597 {598 var response = await client.Messages.Create(new MessageCreateParams599 {600 Model = Model.ClaudeOpus5,601 MaxTokens = 1024,602 Messages = messages603 });604605 // Check if response is empty606 if (response.StopReason == "end_turn" && response.Content.Count == 0)607 {608 // CORRECT: Add a continuation prompt in a NEW user message609 messages.Add(new() { Role = Role.User, Content = "Please continue" });610611 response = await client.Messages.Create(new MessageCreateParams612 {613 Model = Model.ClaudeOpus5,614 MaxTokens = 1024,615 Messages = messages616 });617 }618619 return response;620 }621 ```622623 ```go Go624 func handleEmptyResponse(client anthropic.Client, messages []anthropic.MessageParam) (*anthropic.Message, error) {625 response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{626 Model: anthropic.ModelClaudeOpus5,627 MaxTokens: 1024,628 Messages: messages,629 })630 if err != nil {631 return nil, err632 }633634 // Check if response is empty635 if response.StopReason == "end_turn" && len(response.Content) == 0 {636 // CORRECT: Add a continuation prompt in a NEW user message637 messages = append(messages, anthropic.NewUserMessage(anthropic.NewTextBlock("Please continue")))638639 response, err = client.Messages.New(context.TODO(), anthropic.MessageNewParams{640 Model: anthropic.ModelClaudeOpus5,641 MaxTokens: 1024,642 Messages: messages,643 })644 if err != nil {645 return nil, err646 }647 }648649 return response, nil650 }651 ```652653 ```java Java654 static Message handleEmptyResponse(AnthropicClient client, List<MessageParam> messages) {655 Message response = client.messages().create(656 MessageCreateParams.builder()657 .model(Model.CLAUDE_OPUS_5)658 .maxTokens(1024L)659 .messages(messages)660 .build()661 );662663 // Check if response is empty664 boolean isEndTurn = response.stopReason().map(StopReason.END_TURN::equals).orElse(false);665 if (isEndTurn && response.content().isEmpty()) {666 // CORRECT: Add a continuation prompt in a NEW user message667 List<MessageParam> extended = new ArrayList<>(messages);668 extended.add(MessageParam.builder()669 .role(MessageParam.Role.USER)670 .content("Please continue")671 .build());672673 response = client.messages().create(674 MessageCreateParams.builder()675 .model(Model.CLAUDE_OPUS_5)676 .maxTokens(1024L)677 .messages(extended)678 .build()679 );680 }681682 return response;683 }684 ```685686 ```php PHP687 function handle_empty_response(Client $client, array $messages)688 {689 $response = $client->messages->create(690 maxTokens: 1024,691 messages: $messages,692 model: 'claude-opus-5',693 );694695 // Check if response is empty696 if ($response->stopReason === 'end_turn' && count($response->content) === 0) {697 // CORRECT: Add a continuation prompt in a NEW user message698 $messages[] = ['role' => 'user', 'content' => 'Please continue'];699700 $response = $client->messages->create(701 maxTokens: 1024,702 messages: $messages,703 model: 'claude-opus-5',704 );705 }706707 return $response;708 }709 ```710711 ```ruby Ruby712 def handle_empty_response(client, messages)713 response = client.messages.create(714 model: "claude-opus-5",715 max_tokens: 1024,716 messages: messages717 )718719 # Check if response is empty720 if response.stop_reason == :end_turn && response.content.empty?721 # CORRECT: Add a continuation prompt in a NEW user message722 messages << { role: "user", content: "Please continue" }723724 response = client.messages.create(725 model: "claude-opus-5",726 max_tokens: 1024,727 messages: messages728 )729 end730731 response732 end733 ```734 </CodeGroup>735736 **Best practices:**737738 1. **Never add text blocks immediately after tool results:** This teaches Claude to expect user input after every tool use.739 2. **Don't retry empty responses without modification:** Sending the empty response back won't help.740 3. **Use continuation prompts as a last resort:** Only if these fixes don't resolve the issue.741</Accordion>742743### max\_tokens744745Claude stopped because it reached the `max_tokens` limit specified in your request.746747<CodeGroup>748 ```bash cURL749 curl https://api.anthropic.com/v1/messages \750 -H "x-api-key: $ANTHROPIC_API_KEY" \751 -H "anthropic-version: 2023-06-01" \752 -H "content-type: application/json" \753 -d '{754 "model": "claude-opus-5",755 "max_tokens": 10,756 "messages": [{"role": "user", "content": "Explain quantum physics"}]757 }' | jq '.stop_reason'758 ```759760 ```bash CLI761 ant messages create \762 --model claude-opus-5 \763 --max-tokens 10 \764 --message '{role: user, content: "Explain quantum physics"}' \765 --format json | jq '.stop_reason'766 ```767768 ```python Python769 client = anthropic.Anthropic()770 # Request with limited tokens771 response = client.messages.create(772 model="claude-opus-5",773 max_tokens=10,774 messages=[{"role": "user", "content": "Explain quantum physics"}],775 )776777 if response.stop_reason == "max_tokens":778 # Response was truncated779 print("Response was cut off at token limit")780 # Consider making another request to continue781 ```782783 ```typescript TypeScript784 const client = new Anthropic();785786 // Request with limited tokens787 const response = await client.messages.create({788 model: "claude-opus-5",789 max_tokens: 10,790 messages: [{ role: "user", content: "Explain quantum physics" }]791 });792793 if (response.stop_reason === "max_tokens") {794 // Response was truncated795 console.log("Response was cut off at token limit");796 // Consider making another request to continue797 }798 ```799800 ```csharp C#801 AnthropicClient client = new();802803 // Request with limited tokens804 var response = await client.Messages.Create(new MessageCreateParams805 {806 Model = Model.ClaudeOpus5,807 MaxTokens = 10,808 Messages = [new() { Role = Role.User, Content = "Explain quantum physics" }]809 });810811 if (response.StopReason == "max_tokens")812 {813 // Response was truncated814 Console.WriteLine("Response was cut off at token limit");815 // Consider making another request to continue816 }817 ```818819 ```go Go820 client := anthropic.NewClient()821822 // Request with limited tokens823 response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{824 Model: anthropic.ModelClaudeOpus5,825 MaxTokens: 10,826 Messages: []anthropic.MessageParam{827 anthropic.NewUserMessage(anthropic.NewTextBlock("Explain quantum physics")),828 },829 })830 if err != nil {831 log.Fatal(err)832 }833834 if response.StopReason == "max_tokens" {835 // Response was truncated836 fmt.Println("Response was cut off at token limit")837 // Consider making another request to continue838 }839 ```840841 ```java Java842 AnthropicClient client = AnthropicOkHttpClient.fromEnv();843844 // Request with limited tokens845 Message response = client.messages().create(846 MessageCreateParams.builder()847 .model(Model.CLAUDE_OPUS_5)848 .maxTokens(10L)849 .addUserMessage("Explain quantum physics")850 .build()851 );852853 if (response.stopReason().map(StopReason.MAX_TOKENS::equals).orElse(false)) {854 // Response was truncated855 IO.println("Response was cut off at token limit");856 // Consider making another request to continue857 }858 ```859860 ```php PHP861 $client = new Client();862863 // Request with limited tokens864 $response = $client->messages->create(865 maxTokens: 10,866 messages: [['role' => 'user', 'content' => 'Explain quantum physics']],867 model: 'claude-opus-5',868 );869870 if ($response->stopReason === 'max_tokens') {871 // Response was truncated872 echo 'Response was cut off at token limit', PHP_EOL;873 // Consider making another request to continue874 }875 ```876877 ```ruby Ruby878 client = Anthropic::Client.new879880 # Request with limited tokens881 response = client.messages.create(882 model: "claude-opus-5",883 max_tokens: 10,884 messages: [{ role: "user", content: "Explain quantum physics" }]885 )886887 if response.stop_reason == :max_tokens888 # Response was truncated889 puts "Response was cut off at token limit"890 # Consider making another request to continue891 end892 ```893</CodeGroup>894895<Accordion title="Incomplete tool use blocks">896 If Claude's response is cut off because it hit the `max_tokens` limit, and the truncated response contains an incomplete tool use block, you'll need to retry the request with a higher `max_tokens` value to get the full tool use.897898 <CodeGroup exclude="shell:cURL">899 ```bash CLI900 RESPONSE=$(ant messages create --max-tokens 1024 --format jsonl < request.yaml)901902 # Check if the response was truncated mid tool use903 STOP_REASON=$(jq -r '.stop_reason' <<<"$RESPONSE")904 LAST_TYPE=$(jq -r '.content[-1].type' <<<"$RESPONSE")905 if [ "$STOP_REASON" = "max_tokens" ] && [ "$LAST_TYPE" = "tool_use" ]; then906 # Retry with a higher max_tokens907 ant messages create --max-tokens 4096 < request.yaml908 fi909 ```910911 ```python Python912 # Check if response was truncated during tool use913 if response.stop_reason == "max_tokens":914 # Check if the last content block is an incomplete tool_use915 last_block = response.content[-1]916 if last_block.type == "tool_use":917 # Send the request with higher max_tokens918 response = client.messages.create(919 model="claude-opus-5",920 max_tokens=4096, # Increased limit921 messages=messages,922 tools=tools,923 )924 ```925926 ```typescript TypeScript927 // Check if response was truncated during tool use928 if (response.stop_reason === "max_tokens") {929 // Check if the last content block is an incomplete tool_use930 const lastBlock = response.content[response.content.length - 1];931 if (lastBlock.type === "tool_use") {932 // Send the request with higher max_tokens933 response = await client.messages.create({934 model: "claude-opus-5",935 max_tokens: 4096, // Increased limit936 messages: messages,937 tools: tools938 });939 }940 }941 ```942943 ```csharp C#944 using System.Linq;945 using Anthropic;946 using Anthropic.Models.Messages;947948 AnthropicClient client = new();949950 var parameters = new MessageCreateParams951 {952 Model = Model.ClaudeOpus5,953 MaxTokens = 1024,954 Messages = messages,955 Tools = tools956 };957958 var response = await client.Messages.Create(parameters);959960 if (response.StopReason == "max_tokens")961 {962 var lastBlock = response.Content.Last();963 if (lastBlock.TryPickToolUse(out _))964 {965 response = await client.Messages.Create(parameters with { MaxTokens = 4096 });966 }967 }968 ```969970 ```go Go971 response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{972 Model: anthropic.ModelClaudeOpus5,973 MaxTokens: 1024,974 Messages: messages,975 Tools: tools,976 })977 if err != nil {978 log.Fatal(err)979 }980981 if response.StopReason == "max_tokens" {982 lastBlock := response.Content[len(response.Content)-1]983 switch lastBlock.AsAny().(type) {984 case anthropic.ToolUseBlock:985 response, err = client.Messages.New(context.TODO(), anthropic.MessageNewParams{986 Model: anthropic.ModelClaudeOpus5,987 MaxTokens: 4096,988 Messages: messages,989 Tools: tools,990 })991 if err != nil {992 log.Fatal(err)993 }994 }995 }996 ```997998 ```java Java999 // Check if response was truncated during tool use1000 if (response.stopReason().isPresent() && response.stopReason().get().equals(StopReason.MAX_TOKENS)) {1001 ContentBlock lastBlock = response.content().get(response.content().size() - 1);1002 if (lastBlock.toolUse().isPresent()) {1003 // Send the request with higher max_tokens1004 response = client.messages().create(1005 MessageCreateParams.builder()1006 .model(Model.CLAUDE_OPUS_5)1007 .maxTokens(4096L) // Increased limit1008 .messages(messages)1009 .tools(tools)1010 .build()1011 );1012 }1013 }1014 ```10151016 ```php PHP1017 $response = $client->messages->create(1018 maxTokens: 1024,1019 messages: $messages,1020 model: 'claude-opus-5',1021 tools: $tools,1022 );10231024 if ($response->stopReason === 'max_tokens') {1025 $lastBlock = end($response->content);1026 if ($lastBlock->type === 'tool_use') {1027 $response = $client->messages->create(1028 maxTokens: 4096,1029 messages: $messages,1030 model: 'claude-opus-5',1031 tools: $tools,1032 );1033 }1034 }1035 ```10361037 ```ruby Ruby1038 response = client.messages.create(1039 model: "claude-opus-5",1040 max_tokens: 1024,1041 messages: messages,1042 tools: tools1043 )10441045 if response.stop_reason == :max_tokens1046 last_block = response.content.last1047 if last_block.type == :tool_use1048 response = client.messages.create(1049 model: "claude-opus-5",1050 max_tokens: 4096,1051 messages: messages,1052 tools: tools1053 )1054 end1055 end1056 ```1057 </CodeGroup>1058</Accordion>10591060### stop\_sequence10611062Claude encountered one of your custom stop sequences.10631064<CodeGroup>1065 ```bash cURL1066 curl https://api.anthropic.com/v1/messages \1067 -H "x-api-key: $ANTHROPIC_API_KEY" \1068 -H "anthropic-version: 2023-06-01" \1069 -H "content-type: application/json" \1070 -d '{1071 "model": "claude-opus-5",1072 "max_tokens": 1024,1073 "stop_sequences": ["END", "STOP"],1074 "messages": [{"role": "user", "content": "Generate text until you say END"}]1075 }' | jq '{stop_reason, stop_sequence}'1076 ```10771078 ```bash CLI1079 ant messages create \1080 --model claude-opus-5 \1081 --max-tokens 1024 \1082 --stop-sequence END --stop-sequence STOP \1083 --message '{role: user, content: "Generate text until you say END"}' \1084 --format json | jq '{stop_reason, stop_sequence}'1085 ```10861087 ```python Python1088 client = anthropic.Anthropic()1089 response = client.messages.create(1090 model="claude-opus-5",1091 max_tokens=1024,1092 stop_sequences=["END", "STOP"],1093 messages=[{"role": "user", "content": "Generate text until you say END"}],1094 )10951096 if response.stop_reason == "stop_sequence":1097 print(f"Stopped at sequence: {response.stop_sequence}")1098 ```10991100 ```typescript TypeScript1101 const client = new Anthropic();11021103 const response = await client.messages.create({1104 model: "claude-opus-5",1105 max_tokens: 1024,1106 stop_sequences: ["END", "STOP"],1107 messages: [{ role: "user", content: "Generate text until you say END" }]1108 });11091110 if (response.stop_reason === "stop_sequence") {1111 console.log(`Stopped at sequence: ${response.stop_sequence}`);1112 }1113 ```11141115 ```csharp C#1116 AnthropicClient client = new();11171118 var response = await client.Messages.Create(new MessageCreateParams1119 {1120 Model = Model.ClaudeOpus5,1121 MaxTokens = 1024,1122 StopSequences = ["END", "STOP"],1123 Messages = [new() { Role = Role.User, Content = "Generate text until you say END" }]1124 });11251126 if (response.StopReason == "stop_sequence")1127 {1128 Console.WriteLine($"Stopped at sequence: {response.StopSequence}");1129 }1130 ```11311132 ```go Go1133 client := anthropic.NewClient()11341135 response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{1136 Model: anthropic.ModelClaudeOpus5,1137 MaxTokens: 1024,1138 StopSequences: []string{"END", "STOP"},1139 Messages: []anthropic.MessageParam{1140 anthropic.NewUserMessage(anthropic.NewTextBlock("Generate text until you say END")),1141 },1142 })1143 if err != nil {1144 log.Fatal(err)1145 }11461147 if response.StopReason == "stop_sequence" {1148 fmt.Printf("Stopped at sequence: %s\n", response.StopSequence)1149 }1150 ```11511152 ```java Java1153 AnthropicClient client = AnthropicOkHttpClient.fromEnv();11541155 Message response = client.messages().create(1156 MessageCreateParams.builder()1157 .model(Model.CLAUDE_OPUS_5)1158 .maxTokens(1024L)1159 .addStopSequence("END")1160 .addStopSequence("STOP")1161 .addUserMessage("Generate text until you say END")1162 .build()1163 );11641165 if (response.stopReason().map(StopReason.STOP_SEQUENCE::equals).orElse(false)) {1166 IO.println("Stopped at sequence: " + response.stopSequence().orElse(""));1167 }1168 ```11691170 ```php PHP1171 $client = new Client();11721173 $response = $client->messages->create(1174 maxTokens: 1024,1175 messages: [['role' => 'user', 'content' => 'Generate text until you say END']],1176 model: 'claude-opus-5',1177 stopSequences: ['END', 'STOP'],1178 );11791180 if ($response->stopReason === 'stop_sequence') {1181 echo "Stopped at sequence: {$response->stopSequence}", PHP_EOL;1182 }1183 ```11841185 ```ruby Ruby1186 client = Anthropic::Client.new11871188 response = client.messages.create(1189 model: "claude-opus-5",1190 max_tokens: 1024,1191 stop_sequences: ["END", "STOP"],1192 messages: [{ role: "user", content: "Generate text until you say END" }]1193 )11941195 if response.stop_reason == :stop_sequence1196 puts "Stopped at sequence: #{response.stop_sequence}"1197 end1198 ```1199</CodeGroup>12001201### tool\_use12021203Claude is calling a tool and expects you to run it.12041205<Note>1206 For most tool use implementations, use the [tool runner](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-runner), which automatically handles tool execution, result formatting, and conversation management.1207</Note>12081209<CodeGroup>1210 ```bash cURL1211 curl https://api.anthropic.com/v1/messages \1212 -H "x-api-key: $ANTHROPIC_API_KEY" \1213 -H "anthropic-version: 2023-06-01" \1214 -H "content-type: application/json" \1215 -d '{1216 "model": "claude-opus-5",1217 "max_tokens": 1024,1218 "tools": [{1219 "name": "get_weather",1220 "description": "Get the current weather in a given location",1221 "input_schema": {1222 "type": "object",1223 "properties": {"location": {"type": "string", "description": "City and state"}},1224 "required": ["location"]1225 }1226 }],1227 "messages": [{"role": "user", "content": "What is the weather in San Francisco?"}]1228 }' | jq '.stop_reason, (.content[] | select(.type == "tool_use"))'1229 ```12301231 ```bash CLI1232 ant messages create --format json <<'YAML' | jq '.stop_reason, (.content[] | select(.type == "tool_use"))'1233 model: claude-opus-51234 max_tokens: 10241235 messages:1236 - role: user1237 content: What is the weather in San Francisco?1238 tools:1239 - name: get_weather1240 description: Get the current weather in a given location1241 input_schema:1242 type: object1243 properties:1244 location: {type: string, description: City and state}1245 required: [location]1246 YAML1247 ```12481249 ```python Python1250 client = anthropic.Anthropic()1251 weather_tool = {1252 "name": "get_weather",1253 "description": "Get the current weather in a given location",1254 "input_schema": {1255 "type": "object",1256 "properties": {1257 "location": {"type": "string", "description": "City and state"},1258 },1259 "required": ["location"],1260 },1261 }126212631264 def execute_tool(name, tool_input):1265 """Execute a tool and return the result."""1266 return f"Weather in {tool_input.get('location', 'unknown')}: 72°F"126712681269 response = client.messages.create(1270 model="claude-opus-5",1271 max_tokens=1024,1272 tools=[weather_tool],1273 messages=[{"role": "user", "content": "What is the weather in San Francisco?"}],1274 )12751276 if response.stop_reason == "tool_use":1277 # Extract and execute the tool1278 for block in response.content:1279 if block.type == "tool_use":1280 result = execute_tool(block.name, block.input)1281 # Return result to Claude for final response1282 ```12831284 ```typescript TypeScript1285 const client = new Anthropic();1286 const weatherTool: Anthropic.Tool = {1287 name: "get_weather",1288 description: "Get the current weather in a given location",1289 input_schema: {1290 type: "object",1291 properties: {1292 location: { type: "string", description: "City and state" }1293 },1294 required: ["location"]1295 }1296 };12971298 function executeTool(name: string, input: Record<string, string>): string {1299 return `Weather in ${input.location ?? "unknown"}: 72°F`;1300 }13011302 const response = await client.messages.create({1303 model: "claude-opus-5",1304 max_tokens: 1024,1305 tools: [weatherTool],1306 messages: [{ role: "user", content: "What is the weather in San Francisco?" }]1307 });13081309 if (response.stop_reason === "tool_use") {1310 // Extract and execute the tool1311 for (const block of response.content) {1312 if (block.type === "tool_use") {1313 const result = executeTool(block.name, block.input as Record<string, string>);1314 // Return result to Claude for final response1315 }1316 }1317 }1318 ```13191320 ```csharp C#1321 AnthropicClient client = new();13221323 var weatherTool = new Tool1324 {1325 Name = "get_weather",1326 Description = "Get the current weather in a given location",1327 InputSchema = new InputSchema1328 {1329 Properties = new Dictionary<string, JsonElement>1330 {1331 ["location"] = JsonSerializer.SerializeToElement(1332 new { type = "string", description = "City and state" }1333 ),1334 },1335 Required = ["location"]1336 }1337 };13381339 var response = await client.Messages.Create(new MessageCreateParams1340 {1341 Model = Model.ClaudeOpus5,1342 MaxTokens = 1024,1343 Tools = [weatherTool],1344 Messages = [new() { Role = Role.User, Content = "What is the weather in San Francisco?" }]1345 });13461347 if (response.StopReason == "tool_use")1348 {1349 // Extract and execute the tool1350 foreach (var block in response.Content)1351 {1352 if (block.TryPickToolUse(out var toolUse))1353 {1354 // Execute toolUse.Name with toolUse.Input and return the result to Claude1355 }1356 }1357 }1358 ```13591360 ```go Go1361 client := anthropic.NewClient()13621363 weatherTool := anthropic.ToolParam{1364 Name: "get_weather",1365 Description: anthropic.String("Get the current weather in a given location"),1366 InputSchema: anthropic.ToolInputSchemaParam{1367 Properties: map[string]any{1368 "location": map[string]string{"type": "string", "description": "City and state"},1369 },1370 Required: []string{"location"},1371 },1372 }13731374 response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{1375 Model: anthropic.ModelClaudeOpus5,1376 MaxTokens: 1024,1377 Tools: []anthropic.ToolUnionParam{{OfTool: &weatherTool}},1378 Messages: []anthropic.MessageParam{1379 anthropic.NewUserMessage(anthropic.NewTextBlock("What is the weather in San Francisco?")),1380 },1381 })1382 if err != nil {1383 log.Fatal(err)1384 }13851386 if response.StopReason == "tool_use" {1387 // Extract and execute the tool1388 for _, block := range response.Content {1389 if toolUse, ok := block.AsAny().(anthropic.ToolUseBlock); ok {1390 fmt.Println(toolUse.Name, toolUse.Input)1391 // Return result to Claude for final response1392 }1393 }1394 }1395 ```13961397 ```java Java1398 void main() {1399 AnthropicClient client = AnthropicOkHttpClient.fromEnv();14001401 Tool weatherTool = Tool.builder()1402 .name("get_weather")1403 .description("Get the current weather in a given location")1404 .inputSchema(Tool.InputSchema.builder()1405 .properties(JsonValue.from(Map.of(1406 "location", Map.of("type", "string", "description", "City and state")1407 )))1408 .putAdditionalProperty("required", JsonValue.from(List.of("location")))1409 .build())1410 .build();14111412 Message response = client.messages().create(1413 MessageCreateParams.builder()1414 .model(Model.CLAUDE_OPUS_5)1415 .maxTokens(1024L)1416 .addTool(weatherTool)1417 .addUserMessage("What is the weather in San Francisco?")1418 .build()1419 );14201421 if (response.stopReason().map(StopReason.TOOL_USE::equals).orElse(false)) {1422 // Extract and execute the tool1423 for (ContentBlock block : response.content()) {1424 block.toolUse().ifPresent(toolUse -> {1425 // Execute toolUse.name() with toolUse.input() and return the result to Claude1426 });1427 }1428 }1429 ```14301431 ```php PHP1432 $client = new Client();14331434 $weatherTool = [1435 'name' => 'get_weather',1436 'description' => 'Get the current weather in a given location',1437 'input_schema' => [1438 'type' => 'object',1439 'properties' => [1440 'location' => ['type' => 'string', 'description' => 'City and state'],1441 ],1442 'required' => ['location'],1443 ],1444 ];14451446 $response = $client->messages->create(1447 maxTokens: 1024,1448 messages: [['role' => 'user', 'content' => 'What is the weather in San Francisco?']],1449 model: 'claude-opus-5',1450 tools: [$weatherTool],1451 );14521453 if ($response->stopReason === 'tool_use') {1454 // Extract and execute the tool1455 foreach ($response->content as $block) {1456 if ($block->type === 'tool_use') {1457 // Execute $block->name with $block->input and return the result to Claude1458 }1459 }1460 }1461 ```14621463 ```ruby Ruby1464 client = Anthropic::Client.new14651466 weather_tool = {1467 name: "get_weather",1468 description: "Get the current weather in a given location",1469 input_schema: {1470 type: "object",1471 properties: {1472 location: { type: "string", description: "City and state" }1473 },1474 required: ["location"]1475 }1476 }14771478 response = client.messages.create(1479 model: "claude-opus-5",1480 max_tokens: 1024,1481 tools: [weather_tool],1482 messages: [{ role: "user", content: "What is the weather in San Francisco?" }]1483 )14841485 if response.stop_reason == :tool_use1486 # Extract and execute the tool1487 response.content.each do |block|1488 next unless block.type == :tool_use1489 # Execute block.name with block.input and return the result to Claude1490 end1491 end1492 ```1493</CodeGroup>14941495A `tool_use` response can also contain a `server_tool_use` block whose `id` has no matching result block. That server tool call is not finished, and this response does not carry its result. In the common case, Claude calls a [server tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools) and one of your client tools in the same group of parallel tool calls: the API returns without running the server tool so that you can run the client tools first. There is no other marker for the state; detect it by checking each `server_tool_use` or `mcp_tool_use` block's `id` for a matching result block.14961497<Note>1498 With [programmatic tool calling](https://platform.claude.com/docs/en/agents-and-tools/tool-use/programmatic-tool-calling), the same response shape means something different. The client `tool_use` block comes from code that is running in the `code_execution` tool rather than from Claude directly, and its `caller` field names the `code_execution` block that called it. That code has already started: it is paused waiting for your `tool_result` blocks, and sending them resumes the execution instead of starting a deferred tool. The `code_execution` block's own result block arrives once the code finishes, which can take more than one round of tool results. The follow-up user message itself is the same in both cases; with programmatic tool calling, also pass back the `id` from the response's `container` field, as that page shows.1499</Note>15001501```json A mixed tool_use response1502{1503 "stop_reason": "tool_use",1504 "content": [1505 {1506 "type": "server_tool_use",1507 "id": "srvtoolu_01HxbWnMRmbWyMfUtJKC45rA",1508 "name": "web_search",1509 "input": { "query": "example article" }1510 },1511 {1512 "type": "tool_use",1513 "id": "toolu_01PjgRJLbXrXEMZwDNYLnBqk",1514 "name": "run_command",1515 "input": { "command": "uname -a" }1516 }1517 ]1518}1519```15201521The continuation is a user message of `tool_result` blocks, one for every `tool_use` block in the response (see [Handle tool calls](https://platform.claude.com/docs/en/agents-and-tools/tool-use/handle-tool-calls)), with two extra rules: that message must contain nothing except the `tool_result` blocks, and the request must keep the same `tools` array. A resume request that no longer defines the waiting server tool fails with a 400 whose message ends ``but no `web_search` tool was provided``. The API attaches your results to the still-open assistant turn, runs the deferred server tool (for paused code execution, resumes it), and continues the turn. For a server tool Claude called directly, the next response's `content` starts with the result block that answers the previous response's `server_tool_use` `id`.15221523```json The follow-up user message1524{1525 "role": "user",1526 "content": [1527 {1528 "type": "tool_result",1529 "tool_use_id": "toolu_01PjgRJLbXrXEMZwDNYLnBqk",1530 "content": "Linux demo-host 6.8.0-52-generic x86_64 GNU/Linux"1531 }1532 ]1533}1534```15351536Adding anything after the `tool_result` blocks in that user message, such as text, ends the assistant turn; for a server tool Claude called directly, the request then fails with a 400 `invalid_request_error` that names the unresolved server tool:15371538```text wrap1539`web_search` tool use with id `srvtoolu_01HxbWnMRmbWyMfUtJKC45rA` was found without a corresponding `web_search_tool_result` block1540```15411542Leaving out a `tool_result`, or putting one after other content, fails earlier with the standard `tool_use ids were found without tool_result blocks immediately after` error instead. To give Claude more input, send it as a separate user message after the turn completes.15431544### pause\_turn15451546Returned when the server-side sampling loop reaches its iteration limit while executing [server tools](https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools) such as web search. The default limit is 10 iterations per request.15471548When this happens, the response may contain a `server_tool_use` block without a corresponding result block. To let Claude finish processing, continue the conversation by sending the response back as-is. A response that leaves a client `tool_use` block waiting on you never has a `stop_reason` of `pause_turn`: when Claude stops to call your tools, `stop_reason` is [`tool_use`](https://platform.claude.com/docs/en/build-with-claude/handling-stop-reasons#tool-use), and you continue it by sending the client `tool_result` blocks instead of the response itself.15491550<CodeGroup>1551 ```bash cURL1552 # The SDKs handle continuation directly. With cURL, inspect stop_reason1553 # on the response and re-POST with the assistant content appended.1554 curl https://api.anthropic.com/v1/messages \1555 -H "x-api-key: $ANTHROPIC_API_KEY" \1556 -H "anthropic-version: 2023-06-01" \1557 -H "content-type: application/json" \1558 -d '{1559 "model": "claude-opus-5",1560 "max_tokens": 4096,1561 "tools": [{"type": "web_search_20250305", "name": "web_search"}],1562 "messages": [{"role": "user", "content": "Search for latest AI news"}]1563 }' | jq '{stop_reason, content}'1564 ```15651566 ```bash CLI1567 # Inspect stop_reason; if it is pause_turn, re-run with the assistant1568 # response appended to --message.1569 ant messages create --format json <<'YAML' | jq '{stop_reason, content}'1570 model: claude-opus-51571 max_tokens: 40961572 tools:1573 - {type: web_search_20250305, name: web_search}1574 messages:1575 - {role: user, content: "Search for latest AI news"}1576 YAML1577 ```15781579 ```python Python1580 response = client.messages.create(1581 model="claude-opus-5",1582 max_tokens=4096,1583 tools=[{"type": "web_search_20250305", "name": "web_search"}],1584 messages=[{"role": "user", "content": "Search for latest AI news"}],1585 )15861587 if response.stop_reason == "pause_turn":1588 # Continue the conversation by sending the response back1589 messages = [1590 {"role": "user", "content": "Search for latest AI news"},1591 {"role": "assistant", "content": response.content},1592 ]1593 continuation = client.messages.create(1594 model="claude-opus-5",1595 max_tokens=4096,1596 messages=messages,1597 tools=[{"type": "web_search_20250305", "name": "web_search"}],1598 )1599 ```16001601 ```typescript TypeScript1602 const response = await client.messages.create({1603 model: "claude-opus-5",1604 max_tokens: 4096,1605 tools: [{ type: "web_search_20250305", name: "web_search" }],1606 messages: [{ role: "user", content: "Search for latest AI news" }]1607 });16081609 if (response.stop_reason === "pause_turn") {1610 // Continue the conversation by sending the response back1611 const continuation = await client.messages.create({1612 model: "claude-opus-5",1613 max_tokens: 4096,1614 tools: [{ type: "web_search_20250305", name: "web_search" }],1615 messages: [1616 { role: "user", content: "Search for latest AI news" },1617 { role: "assistant", content: response.content }1618 ]1619 });1620 }1621 ```16221623 ```csharp C#1624 List<ToolUnion> tools = [new ToolUnion(new WebSearchTool20250305())];1625 MessageParam userMessage = new() { Role = Role.User, Content = "Search for latest AI news" };16261627 var response = await client.Messages.Create(new MessageCreateParams1628 {1629 Model = Model.ClaudeOpus5,1630 MaxTokens = 4096,1631 Tools = tools,1632 Messages = [userMessage]1633 });16341635 if (response.StopReason == "pause_turn")1636 {1637 // Continue the conversation by sending the response back1638 var continuation = await client.Messages.Create(new MessageCreateParams1639 {1640 Model = Model.ClaudeOpus5,1641 MaxTokens = 4096,1642 Tools = tools,1643 Messages =1644 [1645 userMessage,1646 new()1647 {1648 Role = Role.Assistant,1649 Content = response.Content.Select(block => new ContentBlockParam(block.Json)).ToList()1650 }1651 ]1652 });1653 }1654 ```16551656 ```go Go1657 tools := []anthropic.ToolUnionParam{1658 {OfWebSearchTool20250305: &anthropic.WebSearchTool20250305Param{}},1659 }1660 userMessage := anthropic.NewUserMessage(anthropic.NewTextBlock("Search for latest AI news"))16611662 response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{1663 Model: anthropic.ModelClaudeOpus5,1664 MaxTokens: 4096,1665 Tools: tools,1666 Messages: []anthropic.MessageParam{userMessage},1667 })1668 if err != nil {1669 log.Fatal(err)1670 }16711672 if response.StopReason == "pause_turn" {1673 // Continue the conversation by sending the response back1674 var contentParams []anthropic.ContentBlockParamUnion1675 for _, block := range response.Content {1676 contentParams = append(contentParams, block.ToParam())1677 }1678 continuation, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{1679 Model: anthropic.ModelClaudeOpus5,1680 MaxTokens: 4096,1681 Tools: tools,1682 Messages: []anthropic.MessageParam{userMessage, anthropic.NewAssistantMessage(contentParams...)},1683 })1684 if err != nil {1685 log.Fatal(err)1686 }1687 _ = continuation1688 }1689 ```16901691 ```java Java1692 Message response = client.messages().create(1693 MessageCreateParams.builder()1694 .model(Model.CLAUDE_OPUS_5)1695 .maxTokens(4096L)1696 .addTool(WebSearchTool20250305.builder().build())1697 .addUserMessage("Search for latest AI news")1698 .build()1699 );17001701 if (response.stopReason().map(StopReason.PAUSE_TURN::equals).orElse(false)) {1702 // Continue the conversation by sending the response back1703 Message continuation = client.messages().create(1704 MessageCreateParams.builder()1705 .model(Model.CLAUDE_OPUS_5)1706 .maxTokens(4096L)1707 .addTool(WebSearchTool20250305.builder().build())1708 .addUserMessage("Search for latest AI news")1709 .addMessage(response)1710 .build()1711 );1712 }1713 ```17141715 ```php PHP1716 $tools = [['type' => 'web_search_20250305', 'name' => 'web_search']];1717 $userMessage = ['role' => 'user', 'content' => 'Search for latest AI news'];17181719 $response = $client->messages->create(1720 maxTokens: 4096,1721 messages: [$userMessage],1722 model: 'claude-opus-5',1723 tools: $tools,1724 );17251726 if ($response->stopReason === 'pause_turn') {1727 // Continue the conversation by sending the response back1728 $continuation = $client->messages->create(1729 maxTokens: 4096,1730 messages: [1731 $userMessage,1732 ['role' => 'assistant', 'content' => $response->content],1733 ],1734 model: 'claude-opus-5',1735 tools: $tools,1736 );1737 }1738 ```17391740 ```ruby Ruby1741 tools = [{ type: "web_search_20250305", name: "web_search" }]1742 user_message = { role: "user", content: "Search for latest AI news" }17431744 response = client.messages.create(1745 model: "claude-opus-5",1746 max_tokens: 4096,1747 tools: tools,1748 messages: [user_message]1749 )17501751 if response.stop_reason == :pause_turn1752 # Continue the conversation by sending the response back1753 continuation = client.messages.create(1754 model: "claude-opus-5",1755 max_tokens: 4096,1756 tools: tools,1757 messages: [user_message, { role: "assistant", content: response.content }]1758 )1759 end1760 ```1761</CodeGroup>17621763<Note>1764 Your application should handle `pause_turn` in any agent loop that uses server tools. Add the assistant's response to your messages array and make another API request to let Claude continue.1765</Note>17661767### refusal17681769Claude declined to generate a response. Safety classifiers return this stop reason as a normal HTTP 200 response, not an error.17701771<CodeGroup>1772 ```bash cURL1773 curl https://api.anthropic.com/v1/messages \1774 -H "x-api-key: $ANTHROPIC_API_KEY" \1775 -H "anthropic-version: 2023-06-01" \1776 -H "content-type: application/json" \1777 -d '{1778 "model": "claude-opus-5",1779 "max_tokens": 1024,1780 "messages": [{"role": "user", "content": "[Unsafe request]"}]1781 }' | jq '{stop_reason, stop_details}'1782 ```17831784 ```bash CLI1785 ant messages create \1786 --model claude-opus-5 \1787 --max-tokens 1024 \1788 --message '{role: user, content: "[Unsafe request]"}' \1789 --format json | jq '{stop_reason, stop_details}'1790 ```17911792 ```python Python1793 client = anthropic.Anthropic()1794 response = client.messages.create(1795 model="claude-opus-5",1796 max_tokens=1024,1797 messages=[{"role": "user", "content": "[Unsafe request]"}],1798 )17991800 if response.stop_reason == "refusal":1801 # Claude declined to respond1802 print("Claude was unable to process this request")1803 # Consider rephrasing or modifying the request1804 ```18051806 ```typescript TypeScript1807 const client = new Anthropic();18081809 const response = await client.messages.create({1810 model: "claude-opus-5",1811 max_tokens: 1024,1812 messages: [{ role: "user", content: "[Unsafe request]" }]1813 });18141815 if (response.stop_reason === "refusal") {1816 // Claude declined to respond1817 console.log("Claude was unable to process this request");1818 // Consider rephrasing or modifying the request1819 }1820 ```18211822 ```csharp C#1823 AnthropicClient client = new();18241825 var response = await client.Messages.Create(new MessageCreateParams1826 {1827 Model = Model.ClaudeOpus5,1828 MaxTokens = 1024,1829 Messages = [new() { Role = Role.User, Content = "[Unsafe request]" }]1830 });18311832 if (response.StopReason == "refusal")1833 {1834 // Claude declined to respond1835 Console.WriteLine("Claude was unable to process this request");1836 // Consider rephrasing or modifying the request1837 }1838 ```18391840 ```go Go1841 client := anthropic.NewClient()18421843 response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{1844 Model: anthropic.ModelClaudeOpus5,1845 MaxTokens: 1024,1846 Messages: []anthropic.MessageParam{1847 anthropic.NewUserMessage(anthropic.NewTextBlock("[Unsafe request]")),1848 },1849 })1850 if err != nil {1851 log.Fatal(err)1852 }18531854 if response.StopReason == "refusal" {1855 // Claude declined to respond1856 fmt.Println("Claude was unable to process this request")1857 // Consider rephrasing or modifying the request1858 }1859 ```18601861 ```java Java1862 AnthropicClient client = AnthropicOkHttpClient.fromEnv();18631864 Message response = client.messages().create(1865 MessageCreateParams.builder()1866 .model(Model.CLAUDE_OPUS_5)1867 .maxTokens(1024L)1868 .addUserMessage("[Unsafe request]")1869 .build()1870 );18711872 if (response.stopReason().map(StopReason.REFUSAL::equals).orElse(false)) {1873 // Claude declined to respond1874 IO.println("Claude was unable to process this request");1875 // Consider rephrasing or modifying the request1876 }1877 ```18781879 ```php PHP1880 $client = new Client();18811882 $response = $client->messages->create(1883 maxTokens: 1024,1884 messages: [['role' => 'user', 'content' => '[Unsafe request]']],1885 model: 'claude-opus-5',1886 );18871888 if ($response->stopReason === 'refusal') {1889 // Claude declined to respond1890 echo 'Claude was unable to process this request', PHP_EOL;1891 // Consider rephrasing or modifying the request1892 }1893 ```18941895 ```ruby Ruby1896 client = Anthropic::Client.new18971898 response = client.messages.create(1899 model: "claude-opus-5",1900 max_tokens: 1024,1901 messages: [{ role: "user", content: "[Unsafe request]" }]1902 )19031904 if response.stop_reason == :refusal1905 # Claude declined to respond1906 puts "Claude was unable to process this request"1907 # Consider rephrasing or modifying the request1908 end1909 ```1910</CodeGroup>19111912<Tip>1913 If you encounter `refusal` stop reasons frequently while using Claude Sonnet 4.5 or Claude Opus 4.1 (the latter [retired, except on Bedrock and Google Cloud](https://platform.claude.com/docs/en/about-claude/model-deprecations)), you can try updating your API calls to use Haiku 4.5 (`claude-haiku-4-5-20251001`), which has different usage restrictions. Learn more about [understanding Sonnet 4.5's API safety filters](https://support.claude.com/en/articles/12449294-understanding-sonnet-4-5-s-api-safety-filters).1914</Tip>19151916On a refusal, the `stop_details` object identifies the policy category that triggered it. The categories and the full refusal response shape are covered on [Refusals and fallback](https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback#refusal-response). `stop_details` is `null` for all stop reasons other than `refusal`.19171918A refused request on Claude Fable 5.1, Claude Fable 5, or Claude Opus 5 can usually be served by retrying on another Claude model. [Refusals and fallback](https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback) shows how to set up that retry, server-side or in your client. If you build the retry yourself from Claude Fable 5.1, Claude Fable 5, or Claude Opus 5, [fallback credit](https://platform.claude.com/docs/en/build-with-claude/fallback-credit) covers how to avoid paying the prompt-cache cost twice.19191920### model\_context\_window\_exceeded19211922Claude stopped because it reached the model's context window limit. This lets you request the maximum possible tokens without knowing the exact input size.19231924<Note>1925 This stop reason is currently typed only in the SDKs' `beta` namespace, so the following examples call `client.beta.messages` and use the `Beta`-prefixed types. On Sonnet 4.5 and newer models the API returns this value without a beta header. For earlier models, add the `model-context-window-exceeded-2025-08-26` beta header to enable it.1926</Note>19271928<CodeGroup>1929 ```bash cURL1930 curl https://api.anthropic.com/v1/messages \1931 -H "x-api-key: $ANTHROPIC_API_KEY" \1932 -H "anthropic-version: 2023-06-01" \1933 -H "content-type: application/json" \1934 -d '{1935 "model": "claude-opus-5",1936 "max_tokens": 20000,1937 "messages": [{"role": "user", "content": "Large input that uses most of context window..."}]1938 }' | jq '.stop_reason'1939 ```19401941 ```bash CLI1942 ant messages create \1943 --model claude-opus-5 \1944 --max-tokens 20000 \1945 --message '{role: user, content: "Large input that uses most of context window..."}' \1946 --format json | jq '.stop_reason'1947 ```19481949 ```python Python1950 # Request with maximum tokens to get as much as possible1951 response = client.beta.messages.create(1952 model="claude-opus-5",1953 max_tokens=20000, # Python SDK requires streaming for max_tokens above ~21k1954 messages=[1955 {"role": "user", "content": "Large input that uses most of context window..."}1956 ],1957 )19581959 if response.stop_reason == "model_context_window_exceeded":1960 # Response hit context window limit before max_tokens1961 print("Response reached model's context window limit")1962 # The response is still valid but was limited by context window1963 ```19641965 ```typescript TypeScript1966 // Request with maximum tokens to get as much as possible1967 const response = await client.beta.messages.create({1968 model: "claude-opus-5",1969 max_tokens: 20000,1970 messages: [{ role: "user", content: "Large input that uses most of context window..." }]1971 });19721973 if (response.stop_reason === "model_context_window_exceeded") {1974 // Response hit context window limit before max_tokens1975 console.log("Response reached model's context window limit");1976 // The response is still valid but was limited by context window1977 }1978 ```19791980 ```csharp C#1981 using Anthropic.Models.Beta.Messages;1982 using Model = Anthropic.Models.Messages.Model;19831984 // Request with maximum tokens to get as much as possible1985 var response = await client.Beta.Messages.Create(new MessageCreateParams1986 {1987 Model = Model.ClaudeOpus5,1988 MaxTokens = 20000,1989 Messages = [new() { Role = Role.User, Content = "Large input that uses most of context window..." }]1990 });19911992 if (response.StopReason?.Value() == BetaStopReason.ModelContextWindowExceeded)1993 {1994 // Response hit context window limit before max_tokens1995 Console.WriteLine("Response reached model's context window limit");1996 // The response is still valid but was limited by context window1997 }1998 ```19992000 ```go Go2001 // Request with maximum tokens to get as much as possible2002 response, err := client.Beta.Messages.New(context.TODO(), anthropic.BetaMessageNewParams{2003 Model: anthropic.ModelClaudeOpus5,2004 MaxTokens: 20000,2005 Messages: []anthropic.BetaMessageParam{2006 anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock("Large input that uses most of context window...")),2007 },2008 })2009 if err != nil {2010 log.Fatal(err)2011 }20122013 if response.StopReason == anthropic.BetaStopReasonModelContextWindowExceeded {2014 // Response hit context window limit before max_tokens2015 fmt.Println("Response reached model's context window limit")2016 // The response is still valid but was limited by context window2017 }2018 ```20192020 ```java Java2021 import com.anthropic.models.beta.messages.BetaMessage;2022 import com.anthropic.models.beta.messages.BetaStopReason;2023 import com.anthropic.models.beta.messages.MessageCreateParams;20242025 // Request with maximum tokens to get as much as possible2026 BetaMessage response = client.beta().messages().create(2027 MessageCreateParams.builder()2028 .model(Model.CLAUDE_OPUS_5)2029 .maxTokens(20000L)2030 .addUserMessage("Large input that uses most of context window...")2031 .build()2032 );20332034 if (response.stopReason().map(BetaStopReason.MODEL_CONTEXT_WINDOW_EXCEEDED::equals).orElse(false)) {2035 // Response hit context window limit before max_tokens2036 IO.println("Response reached model's context window limit");2037 // The response is still valid but was limited by context window2038 }2039 ```20402041 ```php PHP2042 // Request with maximum tokens to get as much as possible2043 $response = $client->beta->messages->create(2044 maxTokens: 20000,2045 messages: [['role' => 'user', 'content' => 'Large input that uses most of context window...']],2046 model: 'claude-opus-5',2047 );20482049 if ($response->stopReason === 'model_context_window_exceeded') {2050 // Response hit context window limit before max_tokens2051 echo 'Response reached model\'s context window limit', PHP_EOL;2052 // The response is still valid but was limited by context window2053 }2054 ```20552056 ```ruby Ruby2057 # Request with maximum tokens to get as much as possible2058 response = client.beta.messages.create(2059 model: "claude-opus-5",2060 max_tokens: 20000,2061 messages: [{ role: "user", content: "Large input that uses most of context window..." }]2062 )20632064 if response.stop_reason == :model_context_window_exceeded2065 # Response hit context window limit before max_tokens2066 puts "Response reached model's context window limit"2067 # The response is still valid but was limited by context window2068 end2069 ```2070</CodeGroup>20712072## Best practices for handling stop reasons20732074### Always check stop\_reason20752076Make it a habit to check the `stop_reason` in your response handling logic:20772078<CodeGroup exclude="shell">2079 ```python Python2080 def handle_response(response):2081 match response.stop_reason:2082 case "tool_use":2083 return handle_tool_use(response)2084 case "max_tokens":2085 return handle_truncation(response)2086 case "model_context_window_exceeded":2087 return handle_context_limit(response)2088 case "pause_turn":2089 return handle_pause(response)2090 case "refusal":2091 return handle_refusal(response)2092 case _:2093 # Handle end_turn and other cases2094 return next(2095 (block.text for block in response.content if block.type == "text"),2096 "",2097 )2098 ```20992100 ```typescript TypeScript2101 function handleResponse(response: Anthropic.Beta.BetaMessage): string {2102 switch (response.stop_reason) {2103 case "tool_use":2104 return handleToolUse(response);2105 case "max_tokens":2106 return handleTruncation(response);2107 case "model_context_window_exceeded":2108 return handleContextLimit(response);2109 case "pause_turn":2110 return handlePause(response);2111 case "refusal":2112 return handleRefusal(response);2113 default: {2114 // Handle end_turn and other cases2115 const textBlock = response.content.find(2116 (block): block is Anthropic.Beta.BetaTextBlock => block.type === "text"2117 );2118 return textBlock?.text ?? "";2119 }2120 }2121 }2122 ```21232124 ```csharp C#2125 static string HandleResponse(BetaMessage response)2126 {2127 return response.StopReason?.Value() switch2128 {2129 BetaStopReason.ToolUse => HandleToolUse(response),2130 BetaStopReason.MaxTokens => HandleTruncation(response),2131 BetaStopReason.ModelContextWindowExceeded => HandleContextLimit(response),2132 BetaStopReason.PauseTurn => HandlePause(response),2133 BetaStopReason.Refusal => HandleRefusal(response),2134 // Handle end_turn and other cases2135 _ => response.Content.Select(b => b.Value).OfType<BetaTextBlock>().FirstOrDefault()?.Text ?? "",2136 };2137 }2138 ```21392140 ```go Go2141 func handleResponse(response *anthropic.BetaMessage) string {2142 switch response.StopReason {2143 case anthropic.BetaStopReasonToolUse:2144 return handleToolUse(response)2145 case anthropic.BetaStopReasonMaxTokens:2146 return handleTruncation(response)2147 case anthropic.BetaStopReasonModelContextWindowExceeded:2148 return handleContextLimit(response)2149 case anthropic.BetaStopReasonPauseTurn:2150 return handlePause(response)2151 case anthropic.BetaStopReasonRefusal:2152 return handleRefusal(response)2153 default:2154 // Handle end_turn and other cases2155 for _, block := range response.Content {2156 if textBlock, ok := block.AsAny().(anthropic.BetaTextBlock); ok {2157 return textBlock.Text2158 }2159 }2160 return ""2161 }2162 }2163 ```21642165 ```java Java2166 static String handleResponse(BetaMessage response) {2167 BetaStopReason reason = response.stopReason().orElse(BetaStopReason.END_TURN);2168 if (reason.equals(BetaStopReason.TOOL_USE)) {2169 return handleToolUse(response);2170 } else if (reason.equals(BetaStopReason.MAX_TOKENS)) {2171 return handleTruncation(response);2172 } else if (reason.equals(BetaStopReason.MODEL_CONTEXT_WINDOW_EXCEEDED)) {2173 return handleContextLimit(response);2174 } else if (reason.equals(BetaStopReason.PAUSE_TURN)) {2175 return handlePause(response);2176 } else if (reason.equals(BetaStopReason.REFUSAL)) {2177 return handleRefusal(response);2178 }2179 // Handle end_turn and other cases2180 return response.content().stream()2181 .filter(BetaContentBlock::isText)2182 .findFirst()2183 .map(block -> block.asText().text())2184 .orElse("");2185 }2186 ```21872188 ```php PHP2189 function handle_response($response): string2190 {2191 return match ($response->stopReason) {2192 'tool_use' => handle_tool_use($response),2193 'max_tokens' => handle_truncation($response),2194 'model_context_window_exceeded' => handle_context_limit($response),2195 'pause_turn' => handle_pause($response),2196 'refusal' => handle_refusal($response),2197 // Handle end_turn and other cases2198 default => array_find($response->content, static fn ($block): bool => $block->type === 'text')?->text ?? '',2199 };2200 }2201 ```22022203 ```ruby Ruby2204 def handle_response(response)2205 case response.stop_reason2206 when :tool_use then handle_tool_use(response)2207 when :max_tokens then handle_truncation(response)2208 when :model_context_window_exceeded then handle_context_limit(response)2209 when :pause_turn then handle_pause(response)2210 when :refusal then handle_refusal(response)2211 else2212 # Handle end_turn and other cases2213 response.content.find { it.type == :text }&.text2214 end2215 end2216 ```2217</CodeGroup>22182219### Handle truncated responses gracefully22202221When a response is truncated because of token limits or the context window, append a notice so the reader knows the output is incomplete. To continue generating from where the response left off instead, see [Ensuring complete responses](https://platform.claude.com/docs/en/build-with-claude/handling-stop-reasons#ensuring-complete-responses).22222223<CodeGroup exclude="shell">2224 ```python Python2225 def handle_truncated_response(response):2226 text = next((block.text for block in response.content if block.type == "text"), "")2227 if response.stop_reason in ["max_tokens", "model_context_window_exceeded"]:2228 if response.stop_reason == "max_tokens":2229 note = "[Response truncated due to max_tokens limit]"2230 else:2231 note = "[Response truncated due to context window limit]"2232 return f"{text}\n\n{note}"2233 return text2234 ```22352236 ```typescript TypeScript2237 function handleTruncatedResponse(response: Anthropic.Beta.BetaMessage): string {2238 const textBlock = response.content.find(2239 (block): block is Anthropic.Beta.BetaTextBlock => block.type === "text"2240 );2241 const text = textBlock?.text ?? "";22422243 if (2244 response.stop_reason === "max_tokens" ||2245 response.stop_reason === "model_context_window_exceeded"2246 ) {2247 const note =2248 response.stop_reason === "max_tokens"2249 ? "[Response truncated due to max_tokens limit]"2250 : "[Response truncated due to context window limit]";2251 return `${text}\n\n${note}`;2252 }2253 return text;2254 }2255 ```22562257 ```csharp C#2258 static string HandleTruncatedResponse(BetaMessage response)2259 {2260 var text = response.Content.Select(b => b.Value).OfType<BetaTextBlock>().FirstOrDefault()?.Text ?? "";2261 var reason = response.StopReason?.Value();22622263 if (reason is BetaStopReason.MaxTokens or BetaStopReason.ModelContextWindowExceeded)2264 {2265 var note = reason == BetaStopReason.MaxTokens2266 ? "[Response truncated due to max_tokens limit]"2267 : "[Response truncated due to context window limit]";2268 return $"{text}\n\n{note}";2269 }2270 return text;2271 }2272 ```22732274 ```go Go2275 func handleTruncatedResponse(response *anthropic.BetaMessage) string {2276 text := ""2277 for _, block := range response.Content {2278 if textBlock, ok := block.AsAny().(anthropic.BetaTextBlock); ok {2279 text = textBlock.Text2280 break2281 }2282 }22832284 if response.StopReason == anthropic.BetaStopReasonMaxTokens ||2285 response.StopReason == anthropic.BetaStopReasonModelContextWindowExceeded {2286 note := "[Response truncated due to context window limit]"2287 if response.StopReason == anthropic.BetaStopReasonMaxTokens {2288 note = "[Response truncated due to max_tokens limit]"2289 }2290 return text + "\n\n" + note2291 }2292 return text2293 }2294 ```22952296 ```java Java2297 static String handleTruncatedResponse(BetaMessage response) {2298 String text = response.content().stream()2299 .filter(BetaContentBlock::isText)2300 .findFirst()2301 .map(block -> block.asText().text())2302 .orElse("");2303 BetaStopReason reason = response.stopReason().orElse(BetaStopReason.END_TURN);23042305 if (reason.equals(BetaStopReason.MAX_TOKENS)2306 || reason.equals(BetaStopReason.MODEL_CONTEXT_WINDOW_EXCEEDED)) {2307 String note = reason.equals(BetaStopReason.MAX_TOKENS)2308 ? "[Response truncated due to max_tokens limit]"2309 : "[Response truncated due to context window limit]";2310 return text + "\n\n" + note;2311 }2312 return text;2313 }2314 ```23152316 ```php PHP2317 function handle_truncated_response($response): string2318 {2319 $text = array_find($response->content, static fn ($block): bool => $block->type === 'text')?->text ?? '';23202321 if (in_array($response->stopReason, ['max_tokens', 'model_context_window_exceeded'], true)) {2322 $note = $response->stopReason === 'max_tokens'2323 ? '[Response truncated due to max_tokens limit]'2324 : '[Response truncated due to context window limit]';2325 return "{$text}\n\n{$note}";2326 }2327 return $text;2328 }2329 ```23302331 ```ruby Ruby2332 def handle_truncated_response(response)2333 text = response.content.find { it.type == :text }&.text23342335 if [:max_tokens, :model_context_window_exceeded].include?(response.stop_reason)2336 note = if response.stop_reason == :max_tokens2337 "[Response truncated due to max_tokens limit]"2338 else2339 "[Response truncated due to context window limit]"2340 end2341 return "#{text}\n\n#{note}"2342 end2343 text2344 end2345 ```2346</CodeGroup>23472348### Implement retry logic for pause\_turn23492350When using [server tools](https://platform.claude.com/docs/en/agents-and-tools/tool-use/server-tools), the API may return `pause_turn` if the server-side sampling loop reaches its iteration limit (default 10). Handle this by continuing the conversation:23512352<CodeGroup exclude="shell">2353 ```python Python2354 def handle_server_tool_conversation(client, user_query, tools, max_continuations=5):2355 """2356 Handle server tool conversations that may require multiple continuations.23572358 The server runs a sampling loop when executing server tools. If the loop2359 reaches its iteration limit, the API returns pause_turn. Continue the2360 conversation by sending the response back to let Claude finish.2361 """2362 messages = [{"role": "user", "content": user_query}]23632364 for _ in range(max_continuations):2365 response = client.messages.create(2366 model="claude-opus-5", max_tokens=4096, messages=messages, tools=tools2367 )23682369 if response.stop_reason != "pause_turn":2370 # Claude finished processing - return the final response2371 return response23722373 # pause_turn: replace the full message list to maintain alternating roles2374 messages = [2375 {"role": "user", "content": user_query},2376 {"role": "assistant", "content": response.content},2377 ]23782379 # Reached max continuations - return the last response2380 return response2381 ```23822383 ```typescript TypeScript2384 async function handleServerToolConversation(2385 client: Anthropic,2386 userQuery: string,2387 tools: Anthropic.ToolUnion[],2388 maxContinuations = 52389 ): Promise<Anthropic.Message> {2390 let messages: Anthropic.MessageParam[] = [{ role: "user", content: userQuery }];2391 let response: Anthropic.Message;23922393 for (let i = 0; i < maxContinuations; i++) {2394 response = await client.messages.create({2395 model: "claude-opus-5",2396 max_tokens: 4096,2397 messages,2398 tools2399 });24002401 if (response.stop_reason !== "pause_turn") {2402 // Claude finished processing - return the final response2403 return response;2404 }24052406 // pause_turn: replace the full message list to maintain alternating roles2407 messages = [2408 { role: "user", content: userQuery },2409 { role: "assistant", content: response.content }2410 ];2411 }24122413 // Reached max continuations - return the last response2414 return response!;2415 }2416 ```24172418 ```csharp C#2419 static async Task<Message> HandleServerToolConversation(2420 AnthropicClient client,2421 string userQuery,2422 List<ToolUnion> tools,2423 int maxContinuations = 5)2424 {2425 List<MessageParam> messages = [new() { Role = Role.User, Content = userQuery }];2426 Message response = null!;24272428 for (var i = 0; i < maxContinuations; i++)2429 {2430 response = await client.Messages.Create(new MessageCreateParams2431 {2432 Model = Model.ClaudeOpus5,2433 MaxTokens = 4096,2434 Messages = messages,2435 Tools = tools2436 });24372438 if (response.StopReason != "pause_turn")2439 {2440 // Claude finished processing - return the final response2441 return response;2442 }24432444 // pause_turn: replace the full message list to maintain alternating roles2445 messages =2446 [2447 new() { Role = Role.User, Content = userQuery },2448 new()2449 {2450 Role = Role.Assistant,2451 Content = response.Content.Select(block => new ContentBlockParam(block.Json)).ToList()2452 }2453 ];2454 }24552456 // Reached max continuations - return the last response2457 return response;2458 }2459 ```24602461 ```go Go2462 func handleServerToolConversation(2463 client anthropic.Client,2464 userQuery string,2465 tools []anthropic.ToolUnionParam,2466 maxContinuations int,2467 ) (*anthropic.Message, error) {2468 messages := []anthropic.MessageParam{anthropic.NewUserMessage(anthropic.NewTextBlock(userQuery))}2469 var response *anthropic.Message2470 var err error24712472 for range maxContinuations {2473 response, err = client.Messages.New(context.TODO(), anthropic.MessageNewParams{2474 Model: anthropic.ModelClaudeOpus5,2475 MaxTokens: 4096,2476 Messages: messages,2477 Tools: tools,2478 })2479 if err != nil {2480 return nil, err2481 }24822483 if response.StopReason != "pause_turn" {2484 // Claude finished processing - return the final response2485 return response, nil2486 }24872488 // pause_turn: replace the full message list to maintain alternating roles2489 var contentParams []anthropic.ContentBlockParamUnion2490 for _, block := range response.Content {2491 contentParams = append(contentParams, block.ToParam())2492 }2493 messages = []anthropic.MessageParam{2494 anthropic.NewUserMessage(anthropic.NewTextBlock(userQuery)),2495 anthropic.NewAssistantMessage(contentParams...),2496 }2497 }24982499 // Reached max continuations - return the last response2500 return response, nil2501 }2502 ```25032504 ```java Java2505 static Message handleServerToolConversation(2506 AnthropicClient client,2507 String userQuery,2508 List<Tool> tools,2509 int maxContinuations2510 ) {2511 Message response = null;25122513 for (int i = 0; i < maxContinuations; i++) {2514 // Rebuild the params each iteration so messages aren't accumulated2515 MessageCreateParams.Builder params = MessageCreateParams.builder()2516 .model(Model.CLAUDE_OPUS_5)2517 .maxTokens(4096L)2518 .addUserMessage(userQuery);2519 tools.forEach(params::addTool);2520 if (response != null) {2521 params.addMessage(response);2522 }25232524 response = client.messages().create(params.build());25252526 if (!response.stopReason().map(StopReason.PAUSE_TURN::equals).orElse(false)) {2527 // Claude finished processing - return the final response2528 return response;2529 }2530 // pause_turn: loop again and send the response back2531 }25322533 // Reached max continuations - return the last response2534 return response;2535 }2536 ```25372538 ```php PHP2539 function handle_server_tool_conversation(2540 Client $client,2541 string $userQuery,2542 array $tools,2543 int $maxContinuations = 52544 ) {2545 $messages = [['role' => 'user', 'content' => $userQuery]];2546 $response = null;25472548 for ($i = 0; $i < $maxContinuations; $i++) {2549 $response = $client->messages->create(2550 maxTokens: 4096,2551 messages: $messages,2552 model: 'claude-opus-5',2553 tools: $tools,2554 );25552556 if ($response->stopReason !== 'pause_turn') {2557 // Claude finished processing - return the final response2558 return $response;2559 }25602561 // pause_turn: replace the full message list to maintain alternating roles2562 $messages = [2563 ['role' => 'user', 'content' => $userQuery],2564 ['role' => 'assistant', 'content' => $response->content],2565 ];2566 }25672568 // Reached max continuations - return the last response2569 return $response;2570 }2571 ```25722573 ```ruby Ruby2574 def handle_server_tool_conversation(client, user_query, tools, max_continuations: 5)2575 messages = [{ role: "user", content: user_query }]2576 response = nil25772578 max_continuations.times do2579 response = client.messages.create(2580 model: "claude-opus-5",2581 max_tokens: 4096,2582 messages: messages,2583 tools: tools2584 )25852586 # Claude finished processing - return the final response2587 return response unless response.stop_reason == :pause_turn25882589 # pause_turn: replace the full message list to maintain alternating roles2590 messages = [2591 { role: "user", content: user_query },2592 { role: "assistant", content: response.content }2593 ]2594 end25952596 # Reached max continuations - return the last response2597 response2598 end2599 ```2600</CodeGroup>26012602## Stop reasons vs. errors26032604It's important to distinguish between `stop_reason` values and actual errors:26052606### Stop reasons (successful responses)26072608* Part of the response body2609* Indicate why generation stopped normally2610* Response contains valid content26112612### Errors (failed requests)26132614* HTTP status codes 4xx or 5xx2615* Indicate request processing failures2616* Response contains error details26172618<CodeGroup>2619 ```bash cURL2620 # cURL exits non-zero on HTTP errors with --fail-with-body; inspect2621 # $? for errors and stop_reason for successful responses.2622 curl --fail-with-body -sS https://api.anthropic.com/v1/messages \2623 -H "x-api-key: $ANTHROPIC_API_KEY" \2624 -H "anthropic-version: 2023-06-01" \2625 -H "content-type: application/json" \2626 -d '{2627 "model": "claude-opus-5",2628 "max_tokens": 1024,2629 "messages": [{"role": "user", "content": "Hello!"}]2630 }' | jq '.stop_reason'2631 ```26322633 ```bash CLI2634 # The CLI exits non-zero on API errors; stop_reason appears on success.2635 ant messages create \2636 --model claude-opus-5 \2637 --max-tokens 1024 \2638 --message '{role: user, content: "Hello!"}' \2639 --format json | jq '.stop_reason'2640 ```26412642 ```python Python2643 client = anthropic.Anthropic()26442645 try:2646 response = client.messages.create(2647 model="claude-opus-5",2648 max_tokens=1024,2649 messages=[{"role": "user", "content": "Hello!"}],2650 )26512652 # Handle successful response with stop_reason2653 if response.stop_reason == "max_tokens":2654 print("Response was truncated")26552656 except anthropic.APIStatusError as e:2657 # Handle actual errors2658 match e.status_code:2659 case 429:2660 print("Rate limit exceeded")2661 case 500:2662 print("Server error")2663 ```26642665 ```typescript TypeScript2666 const client = new Anthropic();26672668 try {2669 const response = await client.messages.create({2670 model: "claude-opus-5",2671 max_tokens: 1024,2672 messages: [{ role: "user", content: "Hello!" }]2673 });26742675 // Handle successful response with stop_reason2676 if (response.stop_reason === "max_tokens") {2677 console.log("Response was truncated");2678 }2679 } catch (err) {2680 // Handle actual errors2681 if (err instanceof Anthropic.APIError) {2682 switch (err.status) {2683 case 429:2684 console.log("Rate limit exceeded");2685 break;2686 case 500:2687 console.log("Server error");2688 break;2689 }2690 } else {2691 throw err;2692 }2693 }2694 ```26952696 ```csharp C#2697 AnthropicClient client = new();26982699 try2700 {2701 var response = await client.Messages.Create(new MessageCreateParams2702 {2703 Model = Model.ClaudeOpus5,2704 MaxTokens = 1024,2705 Messages = [new() { Role = Role.User, Content = "Hello!" }]2706 });27072708 // Handle successful response with stop_reason2709 if (response.StopReason == "max_tokens")2710 {2711 Console.WriteLine("Response was truncated");2712 }2713 }2714 catch (AnthropicRateLimitException)2715 {2716 // Handle actual errors2717 Console.WriteLine("Rate limit exceeded");2718 }2719 catch (Anthropic5xxException)2720 {2721 Console.WriteLine("Server error");2722 }2723 ```27242725 ```go Go2726 client := anthropic.NewClient()27272728 response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{2729 Model: anthropic.ModelClaudeOpus5,2730 MaxTokens: 1024,2731 Messages: []anthropic.MessageParam{2732 anthropic.NewUserMessage(anthropic.NewTextBlock("Hello!")),2733 },2734 })2735 if err != nil {2736 // Handle actual errors2737 var apiErr *anthropic.Error2738 if errors.As(err, &apiErr) {2739 switch apiErr.StatusCode {2740 case 429:2741 fmt.Println("Rate limit exceeded")2742 case 500:2743 fmt.Println("Server error")2744 }2745 }2746 log.Fatal(err)2747 }27482749 // Handle successful response with stop_reason2750 if response.StopReason == "max_tokens" {2751 fmt.Println("Response was truncated")2752 }2753 ```27542755 ```java Java2756 AnthropicClient client = AnthropicOkHttpClient.fromEnv();27572758 try {2759 Message response = client.messages().create(2760 MessageCreateParams.builder()2761 .model(Model.CLAUDE_OPUS_5)2762 .maxTokens(1024L)2763 .addUserMessage("Hello!")2764 .build()2765 );27662767 // Handle successful response with stop_reason2768 if (response.stopReason().map(StopReason.MAX_TOKENS::equals).orElse(false)) {2769 IO.println("Response was truncated");2770 }2771 } catch (RateLimitException e) {2772 // Handle actual errors2773 IO.println("Rate limit exceeded");2774 } catch (AnthropicServiceException e) {2775 if (e.statusCode() == 500) {2776 IO.println("Server error");2777 }2778 }2779 ```27802781 ```php PHP2782 $client = new Client();27832784 try {2785 $response = $client->messages->create(2786 maxTokens: 1024,2787 messages: [['role' => 'user', 'content' => 'Hello!']],2788 model: 'claude-opus-5',2789 );27902791 // Handle successful response with stop_reason2792 if ($response->stopReason === 'max_tokens') {2793 echo 'Response was truncated', PHP_EOL;2794 }2795 } catch (RateLimitException $e) {2796 // Handle actual errors2797 echo 'Rate limit exceeded', PHP_EOL;2798 } catch (InternalServerException $e) {2799 echo 'Server error', PHP_EOL;2800 }2801 ```28022803 ```ruby Ruby2804 client = Anthropic::Client.new28052806 begin2807 response = client.messages.create(2808 model: "claude-opus-5",2809 max_tokens: 1024,2810 messages: [{ role: "user", content: "Hello!" }]2811 )28122813 # Handle successful response with stop_reason2814 if response.stop_reason == :max_tokens2815 puts "Response was truncated"2816 end2817 rescue Anthropic::Errors::RateLimitError2818 # Handle actual errors2819 puts "Rate limit exceeded"2820 rescue Anthropic::Errors::APIStatusError => e2821 puts "Server error" if e.status == 5002822 end2823 ```2824</CodeGroup>28252826## Streaming considerations28272828When using streaming, `stop_reason` is:28292830* `null` in the initial `message_start` event2831* Provided in the `message_delta` event2832* Not provided in any other events28332834<CodeGroup>2835 ```bash cURL2836 # The message_delta event in the SSE stream carries stop_reason.2837 curl --no-buffer https://api.anthropic.com/v1/messages \2838 -H "x-api-key: $ANTHROPIC_API_KEY" \2839 -H "anthropic-version: 2023-06-01" \2840 -H "content-type: application/json" \2841 -d '{2842 "model": "claude-opus-5",2843 "max_tokens": 1024,2844 "stream": true,2845 "messages": [{"role": "user", "content": "Hello!"}]2846 }'2847 ```28482849 ```bash CLI2850 # stop_reason appears in the message_delta event.2851 ant messages create --stream --format jsonl \2852 --model claude-opus-5 \2853 --max-tokens 1024 \2854 --message '{role: user, content: "Hello!"}' |2855 jq -c 'select(.type == "message_delta") | .delta.stop_reason'2856 ```28572858 ```python Python2859 client = anthropic.Anthropic()28602861 with client.messages.stream(2862 model="claude-opus-5",2863 max_tokens=1024,2864 messages=[{"role": "user", "content": "Hello!"}],2865 ) as stream:2866 for event in stream:2867 if event.type == "message_delta":2868 stop_reason = event.delta.stop_reason2869 if stop_reason:2870 print(f"Stream ended with: {stop_reason}")2871 ```28722873 ```typescript TypeScript2874 const client = new Anthropic();28752876 const stream = client.messages.stream({2877 model: "claude-opus-5",2878 max_tokens: 1024,2879 messages: [{ role: "user", content: "Hello!" }]2880 });28812882 for await (const event of stream) {2883 if (event.type === "message_delta" && event.delta.stop_reason) {2884 console.log(`Stream ended with: ${event.delta.stop_reason}`);2885 }2886 }2887 ```28882889 ```csharp C#2890 AnthropicClient client = new();28912892 var parameters = new MessageCreateParams2893 {2894 Model = Model.ClaudeOpus5,2895 MaxTokens = 1024,2896 Messages = [new() { Role = Role.User, Content = "Hello!" }]2897 };28982899 await foreach (var streamEvent in client.Messages.CreateStreaming(parameters))2900 {2901 switch (streamEvent.Value)2902 {2903 case RawMessageDeltaEvent deltaEvent when deltaEvent.Delta.StopReason is not null:2904 Console.WriteLine($"Stream ended with: {deltaEvent.Delta.StopReason}");2905 break;2906 }2907 }2908 ```29092910 ```go Go2911 client := anthropic.NewClient()29122913 stream := client.Messages.NewStreaming(context.TODO(), anthropic.MessageNewParams{2914 Model: anthropic.ModelClaudeOpus5,2915 MaxTokens: 1024,2916 Messages: []anthropic.MessageParam{2917 anthropic.NewUserMessage(anthropic.NewTextBlock("Hello!")),2918 },2919 })29202921 // Accumulate events into the final Message, which carries stop_reason.2922 message := anthropic.Message{}2923 for stream.Next() {2924 if err := message.Accumulate(stream.Current()); err != nil {2925 log.Fatal(err)2926 }2927 }2928 if err := stream.Err(); err != nil {2929 log.Fatal(err)2930 }29312932 if message.StopReason != "" {2933 fmt.Printf("Stream ended with: %s\n", message.StopReason)2934 }2935 ```29362937 ```java Java2938 AnthropicClient client = AnthropicOkHttpClient.fromEnv();29392940 MessageCreateParams params = MessageCreateParams.builder()2941 .model(Model.CLAUDE_OPUS_5)2942 .maxTokens(1024L)2943 .addUserMessage("Hello!")2944 .build();29452946 // Accumulate events into the final Message, which carries stop_reason.2947 MessageAccumulator accumulator = MessageAccumulator.create();2948 try (StreamResponse<RawMessageStreamEvent> streamResponse =2949 client.messages().createStreaming(params)) {2950 streamResponse.stream().forEach(accumulator::accumulate);2951 }29522953 accumulator.message().stopReason().ifPresent(stopReason ->2954 IO.println("Stream ended with: " + stopReason)2955 );2956 ```29572958 ```php PHP2959 $client = new Client();29602961 $stream = $client->messages->createStream(2962 maxTokens: 1024,2963 messages: [['role' => 'user', 'content' => 'Hello!']],2964 model: 'claude-opus-5',2965 );29662967 foreach ($stream as $event) {2968 if ($event instanceof \Anthropic\Messages\RawMessageDeltaEvent && $event->delta->stopReason !== null) {2969 echo "Stream ended with: {$event->delta->stopReason}", PHP_EOL;2970 }2971 }2972 ```29732974 ```ruby Ruby2975 client = Anthropic::Client.new29762977 stream = client.messages.stream(2978 model: "claude-opus-5",2979 max_tokens: 1024,2980 messages: [{ role: "user", content: "Hello!" }]2981 )29822983 stream.each do |event|2984 next unless event.type == :message_delta2985 stop_reason = event.delta.stop_reason2986 puts "Stream ended with: #{stop_reason}" if stop_reason2987 end2988 ```2989</CodeGroup>29902991## Common patterns29922993### Handling tool use workflows29942995<Tip>2996 **Simpler with tool runner:** The following example shows manual tool handling. For most use cases, the [tool runner](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-runner) automatically handles tool execution with much less code.2997</Tip>29982999<CodeGroup exclude="shell">3000 ```python Python3001 def complete_tool_workflow(client, user_query, tools):3002 messages = [{"role": "user", "content": user_query}]30033004 while True:3005 response = client.messages.create(3006 model="claude-opus-5", max_tokens=1024, messages=messages, tools=tools3007 )30083009 if response.stop_reason == "tool_use":3010 # Execute tools and continue3011 tool_results = execute_tools(response.content)3012 messages.append({"role": "assistant", "content": response.content})3013 messages.append({"role": "user", "content": tool_results})3014 else:3015 # Final response3016 return response3017 ```30183019 ```typescript TypeScript3020 async function completeToolWorkflow(3021 client: Anthropic,3022 userQuery: string,3023 tools: Anthropic.ToolUnion[]3024 ): Promise<Anthropic.Message> {3025 const messages: Anthropic.MessageParam[] = [{ role: "user", content: userQuery }];30263027 while (true) {3028 const response = await client.messages.create({3029 model: "claude-opus-5",3030 max_tokens: 1024,3031 messages,3032 tools3033 });30343035 if (response.stop_reason === "tool_use") {3036 // Execute tools and continue3037 const toolResults = executeTools(response.content);3038 messages.push({ role: "assistant", content: response.content });3039 messages.push({ role: "user", content: toolResults });3040 } else {3041 // Final response3042 return response;3043 }3044 }3045 }3046 ```30473048 ```csharp C#3049 static async Task<Message> CompleteToolWorkflow(3050 AnthropicClient client,3051 string userQuery,3052 List<ToolUnion> tools)3053 {3054 List<MessageParam> messages = [new() { Role = Role.User, Content = userQuery }];30553056 while (true)3057 {3058 var response = await client.Messages.Create(new MessageCreateParams3059 {3060 Model = Model.ClaudeOpus5,3061 MaxTokens = 1024,3062 Messages = messages,3063 Tools = tools3064 });30653066 if (response.StopReason == "tool_use")3067 {3068 // Execute tools and continue3069 var toolResults = ExecuteTools(response.Content);3070 messages.Add(new()3071 {3072 Role = Role.Assistant,3073 Content = response.Content.Select(block => new ContentBlockParam(block.Json)).ToList()3074 });3075 messages.Add(new() { Role = Role.User, Content = toolResults });3076 }3077 else3078 {3079 // Final response3080 return response;3081 }3082 }3083 }3084 ```30853086 ```go Go3087 func completeToolWorkflow(3088 client anthropic.Client,3089 userQuery string,3090 tools []anthropic.ToolUnionParam,3091 ) (*anthropic.Message, error) {3092 messages := []anthropic.MessageParam{anthropic.NewUserMessage(anthropic.NewTextBlock(userQuery))}30933094 for {3095 response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{3096 Model: anthropic.ModelClaudeOpus5,3097 MaxTokens: 1024,3098 Messages: messages,3099 Tools: tools,3100 })3101 if err != nil {3102 return nil, err3103 }31043105 if response.StopReason != "tool_use" {3106 // Final response3107 return response, nil3108 }31093110 // Execute tools and continue3111 toolResults := executeTools(response.Content)3112 var contentParams []anthropic.ContentBlockParamUnion3113 for _, block := range response.Content {3114 contentParams = append(contentParams, block.ToParam())3115 }3116 messages = append(messages, anthropic.NewAssistantMessage(contentParams...))3117 messages = append(messages, anthropic.NewUserMessage(toolResults...))3118 }3119 }3120 ```31213122 ```java Java3123 static Message completeToolWorkflow(3124 AnthropicClient client,3125 String userQuery,3126 List<Tool> tools3127 ) {3128 List<MessageParam> messages = new ArrayList<>();3129 messages.add(MessageParam.builder().role(MessageParam.Role.USER).content(userQuery).build());31303131 while (true) {3132 MessageCreateParams.Builder params = MessageCreateParams.builder()3133 .model(Model.CLAUDE_OPUS_5)3134 .maxTokens(1024L)3135 .messages(messages);3136 tools.forEach(params::addTool);31373138 Message response = client.messages().create(params.build());31393140 if (!response.stopReason().map(StopReason.TOOL_USE::equals).orElse(false)) {3141 // Final response3142 return response;3143 }31443145 // Execute tools and continue3146 List<ToolResultBlockParam> toolResults = executeTools(response.content());3147 messages.add(response.toParam());3148 messages.add(MessageParam.builder()3149 .role(MessageParam.Role.USER)3150 .contentOfBlockParams(toolResults.stream().map(ContentBlockParam::ofToolResult).toList())3151 .build());3152 }3153 }3154 ```31553156 ```php PHP3157 function complete_tool_workflow(Client $client, string $userQuery, array $tools)3158 {3159 $messages = [['role' => 'user', 'content' => $userQuery]];31603161 while (true) {3162 $response = $client->messages->create(3163 maxTokens: 1024,3164 messages: $messages,3165 model: 'claude-opus-5',3166 tools: $tools,3167 );31683169 if ($response->stopReason !== 'tool_use') {3170 // Final response3171 return $response;3172 }31733174 // Execute tools and continue3175 $toolResults = execute_tools($response->content);3176 $messages[] = ['role' => 'assistant', 'content' => $response->content];3177 $messages[] = ['role' => 'user', 'content' => $toolResults];3178 }3179 }3180 ```31813182 ```ruby Ruby3183 def complete_tool_workflow(client, user_query, tools)3184 messages = [{ role: "user", content: user_query }]31853186 loop do3187 response = client.messages.create(3188 model: "claude-opus-5",3189 max_tokens: 1024,3190 messages: messages,3191 tools: tools3192 )31933194 # Final response3195 return response unless response.stop_reason == :tool_use31963197 # Execute tools and continue3198 tool_results = execute_tools(response.content)3199 messages << { role: "assistant", content: response.content }3200 messages << { role: "user", content: tool_results }3201 end3202 end3203 ```3204</CodeGroup>32053206### Ensuring complete responses32073208<CodeGroup exclude="shell">3209 ```python Python3210 def get_complete_response(client, prompt, max_attempts=3):3211 messages = [{"role": "user", "content": prompt}]3212 full_response = ""32133214 for _ in range(max_attempts):3215 response = client.messages.create(3216 model="claude-opus-5", messages=messages, max_tokens=40963217 )32183219 full_response += next(3220 (block.text for block in response.content if block.type == "text"), ""3221 )32223223 if response.stop_reason != "max_tokens":3224 break32253226 # Continue from where it left off3227 messages = [3228 {"role": "user", "content": prompt},3229 {"role": "assistant", "content": full_response},3230 {"role": "user", "content": "Please continue from where you left off."},3231 ]32323233 return full_response3234 ```32353236 ```typescript TypeScript3237 async function getCompleteResponse(3238 client: Anthropic,3239 prompt: string,3240 maxAttempts = 33241 ): Promise<string> {3242 let messages: Anthropic.MessageParam[] = [{ role: "user", content: prompt }];3243 let fullResponse = "";32443245 for (let i = 0; i < maxAttempts; i++) {3246 const response = await client.messages.create({3247 model: "claude-opus-5",3248 max_tokens: 4096,3249 messages3250 });32513252 const textBlock = response.content.find(3253 (block): block is Anthropic.TextBlock => block.type === "text"3254 );3255 fullResponse += textBlock?.text ?? "";32563257 if (response.stop_reason !== "max_tokens") {3258 break;3259 }32603261 // Continue from where it left off3262 messages = [3263 { role: "user", content: prompt },3264 { role: "assistant", content: fullResponse },3265 { role: "user", content: "Please continue from where you left off." }3266 ];3267 }32683269 return fullResponse;3270 }3271 ```32723273 ```csharp C#3274 static async Task<string> GetCompleteResponse(AnthropicClient client, string prompt, int maxAttempts = 3)3275 {3276 List<MessageParam> messages = [new() { Role = Role.User, Content = prompt }];3277 var fullResponse = "";32783279 for (var i = 0; i < maxAttempts; i++)3280 {3281 var response = await client.Messages.Create(new MessageCreateParams3282 {3283 Model = Model.ClaudeOpus5,3284 MaxTokens = 4096,3285 Messages = messages3286 });32873288 foreach (var block in response.Content)3289 {3290 if (block.TryPickText(out var textBlock))3291 {3292 fullResponse += textBlock.Text;3293 break;3294 }3295 }32963297 if (response.StopReason != "max_tokens")3298 {3299 break;3300 }33013302 // Continue from where it left off3303 messages =3304 [3305 new() { Role = Role.User, Content = prompt },3306 new() { Role = Role.Assistant, Content = fullResponse },3307 new() { Role = Role.User, Content = "Please continue from where you left off." }3308 ];3309 }33103311 return fullResponse;3312 }3313 ```33143315 ```go Go3316 func getCompleteResponse(client anthropic.Client, prompt string, maxAttempts int) (string, error) {3317 messages := []anthropic.MessageParam{anthropic.NewUserMessage(anthropic.NewTextBlock(prompt))}3318 fullResponse := ""33193320 for range maxAttempts {3321 response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{3322 Model: anthropic.ModelClaudeOpus5,3323 MaxTokens: 4096,3324 Messages: messages,3325 })3326 if err != nil {3327 return "", err3328 }33293330 for _, block := range response.Content {3331 if textBlock, ok := block.AsAny().(anthropic.TextBlock); ok {3332 fullResponse += textBlock.Text3333 break3334 }3335 }33363337 if response.StopReason != "max_tokens" {3338 break3339 }33403341 // Continue from where it left off3342 messages = []anthropic.MessageParam{3343 anthropic.NewUserMessage(anthropic.NewTextBlock(prompt)),3344 anthropic.NewAssistantMessage(anthropic.NewTextBlock(fullResponse)),3345 anthropic.NewUserMessage(anthropic.NewTextBlock("Please continue from where you left off.")),3346 }3347 }33483349 return fullResponse, nil3350 }3351 ```33523353 ```java Java3354 static String getCompleteResponse(AnthropicClient client, String prompt, int maxAttempts) {3355 List<MessageParam> messages = List.of(3356 MessageParam.builder().role(MessageParam.Role.USER).content(prompt).build()3357 );3358 StringBuilder fullResponse = new StringBuilder();33593360 for (int i = 0; i < maxAttempts; i++) {3361 Message response = client.messages().create(3362 MessageCreateParams.builder()3363 .model(Model.CLAUDE_OPUS_5)3364 .maxTokens(4096L)3365 .messages(messages)3366 .build()3367 );33683369 response.content().stream()3370 .filter(ContentBlock::isText)3371 .findFirst()3372 .ifPresent(block -> fullResponse.append(block.asText().text()));33733374 if (!response.stopReason().map(StopReason.MAX_TOKENS::equals).orElse(false)) {3375 break;3376 }33773378 // Continue from where it left off3379 messages = List.of(3380 MessageParam.builder().role(MessageParam.Role.USER).content(prompt).build(),3381 MessageParam.builder().role(MessageParam.Role.ASSISTANT).content(fullResponse.toString()).build(),3382 MessageParam.builder().role(MessageParam.Role.USER).content("Please continue from where you left off.").build()3383 );3384 }33853386 return fullResponse.toString();3387 }3388 ```33893390 ```php PHP3391 function get_complete_response(Client $client, string $prompt, int $maxAttempts = 3): string3392 {3393 $messages = [['role' => 'user', 'content' => $prompt]];3394 $fullResponse = '';33953396 for ($i = 0; $i < $maxAttempts; $i++) {3397 $response = $client->messages->create(3398 maxTokens: 4096,3399 messages: $messages,3400 model: 'claude-opus-5',3401 );34023403 $fullResponse .= array_find($response->content, static fn ($block): bool => $block->type === 'text')?->text ?? '';34043405 if ($response->stopReason !== 'max_tokens') {3406 break;3407 }34083409 // Continue from where it left off3410 $messages = [3411 ['role' => 'user', 'content' => $prompt],3412 ['role' => 'assistant', 'content' => $fullResponse],3413 ['role' => 'user', 'content' => 'Please continue from where you left off.'],3414 ];3415 }34163417 return $fullResponse;3418 }3419 ```34203421 ```ruby Ruby3422 def get_complete_response(client, prompt, max_attempts: 3)3423 messages = [{ role: "user", content: prompt }]3424 full_response = +""34253426 max_attempts.times do3427 response = client.messages.create(3428 model: "claude-opus-5",3429 max_tokens: 4096,3430 messages: messages3431 )34323433 full_response << response.content.find { it.type == :text }&.text.to_s34343435 break unless response.stop_reason == :max_tokens34363437 # Continue from where it left off3438 messages = [3439 { role: "user", content: prompt },3440 { role: "assistant", content: full_response },3441 { role: "user", content: "Please continue from where you left off." }3442 ]3443 end34443445 full_response3446 end3447 ```3448</CodeGroup>34493450### Getting maximum tokens without knowing input size34513452With the `model_context_window_exceeded` stop reason, you can request the maximum possible tokens without calculating input size:34533454<CodeGroup exclude="shell">3455 ```python Python3456 def get_max_possible_tokens(client, prompt):3457 """3458 Get as many tokens as possible within the model's context window3459 without needing to calculate input token count3460 """3461 response = client.beta.messages.create(3462 model="claude-opus-5",3463 messages=[{"role": "user", "content": prompt}],3464 max_tokens=20000, # Python SDK requires streaming for max_tokens above ~21k3465 )34663467 match response.stop_reason:3468 case "model_context_window_exceeded":3469 # Got the maximum possible tokens given input size3470 print(3471 f"Generated {response.usage.output_tokens} tokens (context limit reached)"3472 )3473 case "max_tokens":3474 # Got exactly the requested tokens3475 print(3476 f"Generated {response.usage.output_tokens} tokens (max_tokens reached)"3477 )3478 case _:3479 # Natural completion3480 print(3481 f"Generated {response.usage.output_tokens} tokens (natural completion)"3482 )34833484 return next((block.text for block in response.content if block.type == "text"), "")3485 ```34863487 ```typescript TypeScript3488 async function getMaxPossibleTokens(client: Anthropic, prompt: string): Promise<string> {3489 const response = await client.beta.messages.create({3490 model: "claude-opus-5",3491 max_tokens: 20000,3492 messages: [{ role: "user", content: prompt }]3493 });34943495 const tokens = response.usage.output_tokens;3496 switch (response.stop_reason) {3497 case "model_context_window_exceeded":3498 // Got the maximum possible tokens given input size3499 console.log(`Generated ${tokens} tokens (context limit reached)`);3500 break;3501 case "max_tokens":3502 // Got exactly the requested tokens3503 console.log(`Generated ${tokens} tokens (max_tokens reached)`);3504 break;3505 default:3506 // Natural completion3507 console.log(`Generated ${tokens} tokens (natural completion)`);3508 }35093510 const textBlock = response.content.find(3511 (block): block is Anthropic.Beta.BetaTextBlock => block.type === "text"3512 );3513 return textBlock?.text ?? "";3514 }3515 ```35163517 ```csharp C#3518 using Anthropic.Models.Beta.Messages;3519 using Model = Anthropic.Models.Messages.Model;35203521 static async Task<string> GetMaxPossibleTokens(AnthropicClient client, string prompt)3522 {3523 var response = await client.Beta.Messages.Create(new MessageCreateParams3524 {3525 Model = Model.ClaudeOpus5,3526 MaxTokens = 20000,3527 Messages = [new() { Role = Role.User, Content = prompt }]3528 });35293530 var tokens = response.Usage.OutputTokens;3531 var reason = response.StopReason?.Value();3532 if (reason == BetaStopReason.ModelContextWindowExceeded)3533 {3534 // Got the maximum possible tokens given input size3535 Console.WriteLine($"Generated {tokens} tokens (context limit reached)");3536 }3537 else if (reason == BetaStopReason.MaxTokens)3538 {3539 // Got exactly the requested tokens3540 Console.WriteLine($"Generated {tokens} tokens (max_tokens reached)");3541 }3542 else3543 {3544 // Natural completion3545 Console.WriteLine($"Generated {tokens} tokens (natural completion)");3546 }35473548 return response.Content.Select(b => b.Value).OfType<BetaTextBlock>().FirstOrDefault()?.Text ?? "";3549 }3550 ```35513552 ```go Go3553 func getMaxPossibleTokens(client anthropic.Client, prompt string) (string, error) {3554 response, err := client.Beta.Messages.New(context.TODO(), anthropic.BetaMessageNewParams{3555 Model: anthropic.ModelClaudeOpus5,3556 MaxTokens: 20000,3557 Messages: []anthropic.BetaMessageParam{3558 anthropic.NewBetaUserMessage(anthropic.NewBetaTextBlock(prompt)),3559 },3560 })3561 if err != nil {3562 return "", err3563 }35643565 tokens := response.Usage.OutputTokens3566 switch response.StopReason {3567 case anthropic.BetaStopReasonModelContextWindowExceeded:3568 // Got the maximum possible tokens given input size3569 fmt.Printf("Generated %d tokens (context limit reached)\n", tokens)3570 case anthropic.BetaStopReasonMaxTokens:3571 // Got exactly the requested tokens3572 fmt.Printf("Generated %d tokens (max_tokens reached)\n", tokens)3573 default:3574 // Natural completion3575 fmt.Printf("Generated %d tokens (natural completion)\n", tokens)3576 }35773578 for _, block := range response.Content {3579 if textBlock, ok := block.AsAny().(anthropic.BetaTextBlock); ok {3580 return textBlock.Text, nil3581 }3582 }3583 return "", nil3584 }3585 ```35863587 ```java Java3588 import com.anthropic.models.beta.messages.BetaContentBlock;3589 import com.anthropic.models.beta.messages.BetaMessage;3590 import com.anthropic.models.beta.messages.BetaStopReason;3591 import com.anthropic.models.beta.messages.MessageCreateParams;35923593 static String getMaxPossibleTokens(AnthropicClient client, String prompt) {3594 BetaMessage response = client.beta().messages().create(3595 MessageCreateParams.builder()3596 .model(Model.CLAUDE_OPUS_5)3597 .maxTokens(20000L)3598 .addUserMessage(prompt)3599 .build()3600 );36013602 long tokens = response.usage().outputTokens();3603 BetaStopReason reason = response.stopReason().orElse(BetaStopReason.END_TURN);3604 if (reason.equals(BetaStopReason.MODEL_CONTEXT_WINDOW_EXCEEDED)) {3605 // Got the maximum possible tokens given input size3606 IO.println("Generated " + tokens + " tokens (context limit reached)");3607 } else if (reason.equals(BetaStopReason.MAX_TOKENS)) {3608 // Got exactly the requested tokens3609 IO.println("Generated " + tokens + " tokens (max_tokens reached)");3610 } else {3611 // Natural completion3612 IO.println("Generated " + tokens + " tokens (natural completion)");3613 }36143615 return response.content().stream()3616 .filter(BetaContentBlock::isText)3617 .findFirst()3618 .map(block -> block.asText().text())3619 .orElse("");3620 }3621 ```36223623 ```php PHP3624 function get_max_possible_tokens(Client $client, string $prompt): string3625 {3626 $response = $client->beta->messages->create(3627 maxTokens: 20000,3628 messages: [['role' => 'user', 'content' => $prompt]],3629 model: 'claude-opus-5',3630 );36313632 $tokens = $response->usage->outputTokens;3633 echo match ($response->stopReason) {3634 // Got the maximum possible tokens given input size3635 'model_context_window_exceeded' => "Generated {$tokens} tokens (context limit reached)",3636 // Got exactly the requested tokens3637 'max_tokens' => "Generated {$tokens} tokens (max_tokens reached)",3638 // Natural completion3639 default => "Generated {$tokens} tokens (natural completion)",3640 }, PHP_EOL;36413642 return array_find($response->content, static fn ($block): bool => $block->type === 'text')?->text ?? '';3643 }3644 ```36453646 ```ruby Ruby3647 def get_max_possible_tokens(client, prompt)3648 response = client.beta.messages.create(3649 model: "claude-opus-5",3650 max_tokens: 20000,3651 messages: [{ role: "user", content: prompt }]3652 )36533654 tokens = response.usage.output_tokens3655 case response.stop_reason3656 when :model_context_window_exceeded3657 # Got the maximum possible tokens given input size3658 puts "Generated #{tokens} tokens (context limit reached)"3659 when :max_tokens3660 # Got exactly the requested tokens3661 puts "Generated #{tokens} tokens (max_tokens reached)"3662 else3663 # Natural completion3664 puts "Generated #{tokens} tokens (natural completion)"3665 end36663667 response.content.find { it.type == :text }.text3668 end3669 ```3670</CodeGroup>36713672## Next steps36733674<CardGroup cols={2}>3675 <Card title="Refusals and fallback" icon="arrows-clockwise" href="https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback">3676 Retry refused requests on a fallback model, server-side or in your client.3677 </Card>36783679 <Card title="Tool Runner (SDK)" icon="wrench" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-runner">3680 Let the SDK manage the `tool_use` loop, result formatting, and retries for you.3681 </Card>36823683 <Card title="Streaming messages" icon="lightning" href="https://platform.claude.com/docs/en/build-with-claude/streaming">3684 Read `stop_reason` from the `message_delta` event when streaming.3685 </Card>36863687 <Card title="Errors" icon="info" href="https://platform.claude.com/docs/en/api/errors">3688 Handle 4xx and 5xx HTTP errors, which are distinct from stop reasons.3689 </Card>3690</CardGroup>3691