SPB Git

Repository Public

streaming.md 49.8 KB 1,539 lines markdown

1---2title: Streaming messages3url: https://platform.claude.com/docs/en/build-with-claude/streaming4description: Stream Messages API responses incrementally with server-sent events, including text, tool use, and extended thinking deltas.5---67When creating a Message, you can set `"stream": true` to incrementally stream the response using [server-sent events](https://developer.mozilla.org/en-US/Web/API/Server-sent%5Fevents/Using%5Fserver-sent%5Fevents) (SSE).89## Streaming with SDKs1011The [Python SDK](https://github.com/anthropics/anthropic-sdk-python) and [TypeScript SDK](https://github.com/anthropics/anthropic-sdk-typescript) offer multiple ways of streaming. The [PHP SDK](https://github.com/anthropics/anthropic-sdk-php) provides streaming through `createStream()`. The Python SDK allows both sync and async streams. See the documentation in each SDK for details.1213<CodeGroup>14  ```bash CLI15  ant messages create --stream --format jsonl \16    --model claude-opus-5 \17    --max-tokens 1024 \18    --message '{role: user, content: "Hello"}' \19    | jq -rj 'select(.delta.type? == "text_delta") | .delta.text'20  ```2122  ```python Python23  client = anthropic.Anthropic()2425  with client.messages.stream(26      max_tokens=1024,27      messages=[{"role": "user", "content": "Hello"}],28      model="claude-opus-5",29  ) as stream:30      for text in stream.text_stream:31          print(text, end="", flush=True)32  ```3334  ```typescript TypeScript35  const client = new Anthropic();3637  await client.messages38    .stream({39      messages: [{ role: "user", content: "Hello" }],40      model: "claude-opus-5",41      max_tokens: 102442    })43    .on("text", (text) => {44      console.log(text);45    });46  ```4748  ```csharp C#49  AnthropicClient client = new();5051  var parameters = new MessageCreateParams52  {53      Model = Model.ClaudeOpus5,54      MaxTokens = 1024,55      Messages = [new() { Role = Role.User, Content = "Hello" }]56  };5758  await foreach (var msg in client.Messages.CreateStreaming(parameters))59  {60      Console.Write(msg);61  }62  ```6364  ```go Go65  client := anthropic.NewClient()6667  stream := client.Messages.NewStreaming(context.TODO(), anthropic.MessageNewParams{68  	Model:     anthropic.ModelClaudeOpus5,69  	MaxTokens: 1024,70  	Messages: []anthropic.MessageParam{71  		anthropic.NewUserMessage(anthropic.NewTextBlock("Hello")),72  	},73  })7475  for stream.Next() {76  	event := stream.Current()77  	switch eventVariant := event.AsAny().(type) {78  	case anthropic.ContentBlockDeltaEvent:79  		switch deltaVariant := eventVariant.Delta.AsAny().(type) {80  		case anthropic.TextDelta:81  			fmt.Print(deltaVariant.Text)82  		}83  	}84  }85  if err := stream.Err(); err != nil {86  	log.Fatal(err)87  }88  ```8990  ```java Java91  AnthropicClient client = AnthropicOkHttpClient.fromEnv();9293  MessageCreateParams params = MessageCreateParams.builder()94      .model(Model.CLAUDE_OPUS_5)95      .maxTokens(1024L)96      .addUserMessage("Hello")97      .build();9899  try (var streamResponse = client.messages().createStreaming(params)) {100      streamResponse.stream().forEach(event -> {101          event.contentBlockDelta().ifPresent(deltaEvent ->102              deltaEvent.delta().text().ifPresent(td ->103                  System.out.print(td.text())104              )105          );106      });107  }108  ```109110  ```php PHP111  $client = new Client();112113  $stream = $client->messages->createStream(114      maxTokens: 1024,115      messages: [116          ['role' => 'user', 'content' => 'Hello']117      ],118      model: 'claude-opus-5',119  );120121  foreach ($stream as $message) {122      echo $message;123  }124  ```125126  ```ruby Ruby127  client = Anthropic::Client.new128129  stream = client.messages.stream(130    model: "claude-opus-5",131    max_tokens: 1024,132    messages: [{ role: "user", content: "Hello" }]133  )134135  stream.text.each { |text| print(text) }136  ```137</CodeGroup>138139## Get the final message without handling events140141If you don't need to process text as it arrives, the SDKs provide a way to use streaming internally while returning the complete `Message` object, identical to what `.create()` returns. This is especially useful for requests with large `max_tokens` values, where the SDKs require streaming to avoid HTTP timeouts.142143<CodeGroup>144  ```bash CLI145  # The ant CLI's --stream flag emits one event per line and does not146  # accumulate into a final Message. For long generations, stream the147  # raw events:148  ant messages create --stream --format jsonl <<'YAML'149  model: claude-opus-5150  max_tokens: 128000151  messages:152    - role: user153      content: Write a detailed analysis...154  YAML155  ```156157  ```python Python158  client = anthropic.Anthropic()159160  with client.messages.stream(161      max_tokens=128000,162      messages=[{"role": "user", "content": "Write a detailed analysis..."}],163      model="claude-opus-5",164  ) as stream:165      message = stream.get_final_message()166167  for block in message.content:168      if block.type == "text":169          print(block.text)170  ```171172  ```typescript TypeScript173  const client = new Anthropic();174175  const stream = client.messages.stream({176    max_tokens: 128000,177    messages: [{ role: "user", content: "Write a detailed analysis..." }],178    model: "claude-opus-5"179  });180181  const message = await stream.finalMessage();182  const textBlock = message.content.find((block) => block.type === "text");183  if (textBlock && textBlock.type === "text") {184    console.log(textBlock.text);185  }186  ```187188  ```csharp C#189  AnthropicClient client = new();190191  var parameters = new MessageCreateParams192  {193      Model = Model.ClaudeOpus5,194      MaxTokens = 128000,195      Messages = [new() { Role = Role.User, Content = "Write a detailed analysis..." }]196  };197198  var fullText = "";199  await foreach (var msg in client.Messages.CreateStreaming(parameters))200  {201      fullText += msg;202  }203204  Console.WriteLine(fullText);205  ```206207  ```go Go208  client := anthropic.NewClient()209210  stream := client.Messages.NewStreaming(context.TODO(), anthropic.MessageNewParams{211  	Model:     anthropic.ModelClaudeOpus5,212  	MaxTokens: 128000,213  	Messages: []anthropic.MessageParam{214  		anthropic.NewUserMessage(anthropic.NewTextBlock("Write a detailed analysis...")),215  	},216  })217218  message := anthropic.Message{}219  for stream.Next() {220  	event := stream.Current()221  	if err := message.Accumulate(event); err != nil {222  		log.Fatal(err)223  	}224  }225  if err := stream.Err(); err != nil {226  	log.Fatal(err)227  }228229  for _, block := range message.Content {230  	if textBlock, ok := block.AsAny().(anthropic.TextBlock); ok {231  		fmt.Println(textBlock.Text)232  	}233  }234  ```235236  ```java Java237  AnthropicClient client = AnthropicOkHttpClient.fromEnv();238239  MessageCreateParams params = MessageCreateParams.builder()240      .model(Model.CLAUDE_OPUS_5)241      .maxTokens(128000L)242      .addUserMessage("Write a detailed analysis...")243      .build();244245  MessageAccumulator accumulator = MessageAccumulator.create();246  try (var streamResponse = client.messages().createStreaming(params)) {247      streamResponse.stream().forEach(accumulator::accumulate);248  }249250  Message message = accumulator.message();251  message.content().stream()252      .flatMap(block -> block.text().stream())253      .forEach(textBlock -> System.out.println(textBlock.text()));254  ```255256  ```php PHP257  $client = new Client();258259  $stream = $client->messages->createStream(260      maxTokens: 128000,261      messages: [262          ['role' => 'user', 'content' => 'Write a detailed analysis...']263      ],264      model: 'claude-opus-5',265  );266267  $fullText = '';268  foreach ($stream as $event) {269      if ($event->type === 'content_block_delta' && $event->delta->type === 'text_delta') {270          $fullText .= $event->delta->text;271      }272  }273274  echo $fullText;275  ```276277  ```ruby Ruby278  client = Anthropic::Client.new279280  message = client.messages.stream(281    model: "claude-opus-5",282    max_tokens: 128000,283    messages: [{ role: "user", content: "Write a detailed analysis..." }]284  ).accumulated_message285286  message.content.each do |block|287    puts block.text if block.type == :text288  end289  ```290</CodeGroup>291292The `.stream()` call keeps the HTTP connection alive with server-sent events, then `.get_final_message()` (Python) or `.finalMessage()` (TypeScript) accumulates all events and returns the complete `Message` object. In Go, you call `message.Accumulate(event)` inside the stream loop to build the same complete `Message`. In Java, use `MessageAccumulator.create()` and call `accumulator.accumulate(event)` on each event. In C#, await the stream's `.Aggregate()` extension method to get the complete `Message`, or pass a `MessageContentAggregator` to `.CollectAsync()` to aggregate while handling events. In Ruby, call `.accumulated_message` on the stream. In the PHP SDK, you iterate over stream events manually to accumulate the response.293294## Event types295296Each server-sent event includes a named event type and associated JSON data. Each event uses an SSE event name (for example, `event: message_stop`), and includes the matching event `type` in its data.297298Each stream uses the following event flow:2993001. `message_start`: contains a `Message` object with empty `content`. Under the [`thinking-binding-controls-2026-08-01`](https://platform.claude.com/docs/en/build-with-claude/thinking#preserved-thinking-controls) beta header, this `Message` object also carries the `input_transformations` array. After a mid-stream [server-side fallback](https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback#server-side-fallback), the final `message_delta` event carries the array again with the serving model's entries.3012. A series of content blocks, each of which has a `content_block_start`, one or more `content_block_delta` events, and a `content_block_stop` event. Each content block has an `index` that corresponds to its index in the final Message `content` array. One exception: during [server-side fallback](https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback#server-side-fallback) responses, a `fallback` content block arrives at each model boundary as a `content_block_start` and `content_block_stop` pair with no deltas in between.3023. One or more `message_delta` events, indicating top-level changes to the final `Message` object.3034. A final `message_stop` event.304305<Warning>306  The token counts shown in the `usage` field of the `message_delta` event are *cumulative*.307</Warning>308309### Ping events310311Event streams may also include any number of `ping` events.312313### Error events314315The API may occasionally send [errors](https://platform.claude.com/docs/en/api/errors) in the event stream. For example, during periods of high usage, you may receive an `overloaded_error`, which would normally correspond to an HTTP 529 in a non-streaming context:316317```sse Example error318event: error319data: {"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}}320```321322### Other events323324In accordance with the [versioning policy](https://platform.claude.com/docs/en/api/versioning), new event types may be added, and your code should handle unknown event types gracefully.325326## Content block delta types327328Each `content_block_delta` event contains a `delta` of a type that updates the `content` block at a given `index`.329330### Text delta331332A `text` content block delta looks like:333334```sse Text delta335event: content_block_delta336data: {"type": "content_block_delta","index": 0,"delta": {"type": "text_delta", "text": "ello frien"}}337```338339### Input JSON delta340341The deltas for `tool_use` content blocks correspond to updates for the `input` field of the block. To support maximum granularity, the deltas are *partial JSON strings*, whereas the final `tool_use.input` is always an *object*.342343You can accumulate the string deltas and parse the JSON once you receive a `content_block_stop` event, by using a library like [Pydantic](https://docs.pydantic.dev/latest/concepts/json/#partial-json-parsing) to do partial JSON parsing, or by using the [SDKs](https://platform.claude.com/docs/en/cli-sdks-libraries/overview), which provide helpers to access parsed incremental values.344345A `tool_use` content block delta looks like:346347```sse Input JSON delta348event: content_block_delta349data: {"type": "content_block_delta","index": 1,"delta": {"type": "input_json_delta","partial_json": "{\"location\": \"San Fra"}}}350```351352Note: Current models only support emitting one complete key and value property from `input` at a time. As such, when using tools, there may be delays between streaming events while the model is working. Once an `input` key and value are accumulated, they are emitted as multiple `content_block_delta` events with chunked partial JSON so that the format can automatically support finer granularity in future models.353354### Thinking delta355356When using [thinking](https://platform.claude.com/docs/en/build-with-claude/thinking#streaming-thinking) with streaming enabled, you'll receive thinking content through `thinking_delta` events. These deltas correspond to the `thinking` field of the `thinking` content blocks.357358For thinking content, a special `signature_delta` event is sent just before the `content_block_stop` event. This signature is used to verify the integrity of the thinking block.359360When `display: "omitted"` is set on the thinking configuration, no thinking text is streamed. The thinking block opens, receives a `thinking_delta` with an empty `thinking` string and then a single `signature_delta`, and closes. With `display: "updates"` (beta), reasoning blocks stream the same way, and only the [progress updates](https://platform.claude.com/docs/en/build-with-claude/thinking#progress-updates) that some models write between tool calls stream `thinking_delta` events that carry text. See [Controlling thinking display](https://platform.claude.com/docs/en/build-with-claude/thinking#controlling-thinking-display).361362A typical thinking delta looks like:363364```sse Thinking delta365event: content_block_delta366data: {"type": "content_block_delta", "index": 0, "delta": {"type": "thinking_delta", "thinking": "I need to find the GCD of 1071 and 462 using the Euclidean algorithm.\n\n1071 = 2 × 462 + 147"}}367```368369The signature delta looks like:370371```sse Signature delta372event: content_block_delta373data: {"type": "content_block_delta", "index": 0, "delta": {"type": "signature_delta", "signature": "EqQBCgIYAhIM1gbcDa9GJwZA2b3hGgxBdjrkzLoky3dl1pkiMOYds..."}}374```375376## Full HTTP stream response377378Use the [client SDKs](https://platform.claude.com/docs/en/cli-sdks-libraries/overview) when using streaming mode. However, if you are building a direct API integration, you need to handle these events yourself.379380A stream response consists of:3813821. A `message_start` event3833842. Potentially multiple content blocks, each of which contains:385386   * A `content_block_start` event387   * Potentially multiple `content_block_delta` events388   * A `content_block_stop` event3893903. One or more `message_delta` events3913924. A `message_stop` event393394There may be `ping` events dispersed throughout the response as well. See [Event types](https://platform.claude.com/docs/en/build-with-claude/streaming#event-types) for more details on the format.395396### Basic streaming request397398<CodeGroup>399  ```bash cURL400  curl https://api.anthropic.com/v1/messages \401    -H "anthropic-version: 2023-06-01" \402    -H "content-type: application/json" \403    -H "x-api-key: $ANTHROPIC_API_KEY" \404    -d '{405      "model": "claude-opus-5",406      "messages": [{"role": "user", "content": "Hello"}],407      "max_tokens": 256,408      "stream": true409    }'410  ```411412  ```bash CLI413  ant messages create --stream --format jsonl \414    --model claude-opus-5 \415    --max-tokens 256 \416    --message '{role: user, content: Hello}'417  ```418419  ```python Python420  client = anthropic.Anthropic()421422  with client.messages.stream(423      model="claude-opus-5",424      messages=[{"role": "user", "content": "Hello"}],425      max_tokens=256,426  ) as stream:427      for text in stream.text_stream:428          print(text, end="", flush=True)429  ```430431  ```typescript TypeScript432  const client = new Anthropic();433434  const stream = client.messages.stream({435    model: "claude-opus-5",436    messages: [{ role: "user", content: "Hello" }],437    max_tokens: 256438  });439440  for await (const event of stream) {441    if (event.type === "content_block_delta" && event.delta.type === "text_delta") {442      process.stdout.write(event.delta.text);443    }444  }445  ```446447  ```csharp C#448  AnthropicClient client = new();449450  var parameters = new MessageCreateParams451  {452      Model = Model.ClaudeOpus5,453      MaxTokens = 256,454      Messages = [new() { Role = Role.User, Content = "Hello" }]455  };456457  await foreach (var msg in client.Messages.CreateStreaming(parameters))458  {459      Console.Write(msg);460  }461  ```462463  ```go Go464  client := anthropic.NewClient()465466  stream := client.Messages.NewStreaming(context.TODO(), anthropic.MessageNewParams{467  	Model:     anthropic.ModelClaudeOpus5,468  	MaxTokens: 256,469  	Messages: []anthropic.MessageParam{470  		anthropic.NewUserMessage(anthropic.NewTextBlock("Hello")),471  	},472  })473474  for stream.Next() {475  	event := stream.Current()476  	switch eventVariant := event.AsAny().(type) {477  	case anthropic.ContentBlockDeltaEvent:478  		switch deltaVariant := eventVariant.Delta.AsAny().(type) {479  		case anthropic.TextDelta:480  			fmt.Print(deltaVariant.Text)481  		}482  	}483  }484  if err := stream.Err(); err != nil {485  	log.Fatal(err)486  }487  ```488489  ```java Java490  AnthropicClient client = AnthropicOkHttpClient.fromEnv();491492  MessageCreateParams params = MessageCreateParams.builder()493      .model(Model.CLAUDE_OPUS_5)494      .maxTokens(256L)495      .addUserMessage("Hello")496      .build();497498  try (var streamResponse = client.messages().createStreaming(params)) {499      streamResponse.stream().forEach(event -> {500          event.contentBlockDelta().ifPresent(deltaEvent ->501              deltaEvent.delta().text().ifPresent(td ->502                  System.out.print(td.text())503              )504          );505      });506  }507  ```508509  ```php PHP510  $client = new Client();511512  $stream = $client->messages->createStream(513      maxTokens: 256,514      messages: [515          ['role' => 'user', 'content' => 'Hello']516      ],517      model: 'claude-opus-5',518  );519520  foreach ($stream as $message) {521      echo $message;522  }523  ```524525  ```ruby Ruby526  client = Anthropic::Client.new527528  stream = client.messages.stream(529    model: "claude-opus-5",530    messages: [{ role: "user", content: "Hello" }],531    max_tokens: 256532  )533534  stream.text.each { |text| print(text) }535  ```536</CodeGroup>537538```sse Response539event: message_start540data: {"type": "message_start", "message": {"id": "msg_1nZdL29xx5MUA1yADyHTEsnR8uuvGzszyY", "type": "message", "role": "assistant", "content": [], "model": "claude-opus-5", "stop_reason": null, "stop_sequence": null, "usage": {"input_tokens": 25, "output_tokens": 1}}}541542event: content_block_start543data: {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}544545event: ping546data: {"type": "ping"}547548event: content_block_delta549data: {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "Hello"}}550551event: content_block_delta552data: {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "!"}}553554event: content_block_stop555data: {"type": "content_block_stop", "index": 0}556557event: message_delta558data: {"type": "message_delta", "delta": {"stop_reason": "end_turn", "stop_sequence":null}, "usage": {"output_tokens": 15}}559560event: message_stop561data: {"type": "message_stop"}562563```564565### Streaming request with tool use566567<Tip>568  Tool use supports [fine-grained streaming](https://platform.claude.com/docs/en/agents-and-tools/tool-use/fine-grained-tool-streaming) for parameter values. Enable it per tool with `eager_input_streaming`.569</Tip>570571This request asks Claude to use a tool to report the weather.572573<CodeGroup>574  ```bash cURL575    curl https://api.anthropic.com/v1/messages \576      -H "content-type: application/json" \577      -H "x-api-key: $ANTHROPIC_API_KEY" \578      -H "anthropic-version: 2023-06-01" \579      -d '{580        "model": "claude-opus-5",581        "max_tokens": 1024,582        "tools": [583          {584            "name": "get_weather",585            "description": "Get the current weather in a given location",586            "input_schema": {587              "type": "object",588              "properties": {589                "location": {590                  "type": "string",591                  "description": "The city and state, e.g. San Francisco, CA"592                }593              },594              "required": ["location"]595            }596          }597        ],598        "tool_choice": {"type": "any"},599        "messages": [600          {601            "role": "user",602            "content": "What is the weather like in San Francisco?"603          }604        ],605        "stream": true606      }'607  ```608609  ```bash CLI610  ant messages create --stream --format jsonl <<'YAML'611  model: claude-opus-5612  max_tokens: 1024613  tools:614    - name: get_weather615      description: Get the current weather in a given location616      input_schema:617        type: object618        properties:619          location:620            type: string621            description: The city and state, e.g. San Francisco, CA622        required:623          - location624  tool_choice:625    type: any626  messages:627    - role: user628      content: What is the weather like in San Francisco?629  YAML630  ```631632  ```python Python633  client = anthropic.Anthropic()634635  tools = [636      {637          "name": "get_weather",638          "description": "Get the current weather in a given location",639          "input_schema": {640              "type": "object",641              "properties": {642                  "location": {643                      "type": "string",644                      "description": "The city and state, e.g. San Francisco, CA",645                  }646              },647              "required": ["location"],648          },649      }650  ]651652  with client.messages.stream(653      model="claude-opus-5",654      max_tokens=1024,655      tools=tools,656      tool_choice={"type": "any"},657      messages=[658          {"role": "user", "content": "What is the weather like in San Francisco?"}659      ],660  ) as stream:661      for text in stream.text_stream:662          print(text, end="", flush=True)663  ```664665  ```typescript TypeScript666  const client = new Anthropic();667668  const tools: Anthropic.Tool[] = [669    {670      name: "get_weather",671      description: "Get the current weather in a given location",672      input_schema: {673        type: "object",674        properties: {675          location: {676            type: "string",677            description: "The city and state, e.g. San Francisco, CA"678          }679        },680        required: ["location"]681      }682    }683  ];684685  const stream = client.messages.stream({686    model: "claude-opus-5",687    max_tokens: 1024,688    tools: tools,689    tool_choice: { type: "any" },690    messages: [691      {692        role: "user",693        content: "What is the weather like in San Francisco?"694      }695    ]696  });697698  for await (const event of stream) {699    if (event.type === "content_block_delta" && event.delta.type === "text_delta") {700      process.stdout.write(event.delta.text);701    }702  }703  ```704705  ```csharp C#706  AnthropicClient client = new();707708  var parameters = new MessageCreateParams709  {710      Model = Model.ClaudeOpus5,711      MaxTokens = 1024,712      Tools = [713          new ToolUnion(new Tool()714          {715              Name = "get_weather",716              Description = "Get the current weather in a given location",717              InputSchema = new InputSchema()718              {719                  Properties = new Dictionary<string, JsonElement>720                  {721                      ["location"] = JsonSerializer.SerializeToElement(new { type = "string", description = "The city and state, e.g. San Francisco, CA" }),722                  },723                  Required = ["location"],724              },725          }),726      ],727      ToolChoice = new ToolChoiceAny(),728      Messages = [729          new() { Role = Role.User, Content = "What is the weather like in San Francisco?" }730      ]731  };732733  await foreach (var msg in client.Messages.CreateStreaming(parameters))734  {735      Console.Write(msg);736  }737  ```738739  ```go Go740  client := anthropic.NewClient()741742  stream := client.Messages.NewStreaming(context.TODO(), anthropic.MessageNewParams{743  	Model:     anthropic.ModelClaudeOpus5,744  	MaxTokens: 1024,745  	Tools: []anthropic.ToolUnionParam{746  		{OfTool: &anthropic.ToolParam{747  			Name:        "get_weather",748  			Description: anthropic.String("Get the current weather in a given location"),749  			InputSchema: anthropic.ToolInputSchemaParam{750  				Properties: map[string]any{751  					"location": map[string]any{752  						"type":        "string",753  						"description": "The city and state, e.g. San Francisco, CA",754  					},755  				},756  				Required: []string{"location"},757  			},758  		}},759  	},760  	ToolChoice: anthropic.ToolChoiceUnionParam{OfAny: &anthropic.ToolChoiceAnyParam{}},761  	Messages: []anthropic.MessageParam{762  		anthropic.NewUserMessage(anthropic.NewTextBlock("What is the weather like in San Francisco?")),763  	},764  })765766  for stream.Next() {767  	event := stream.Current()768  	switch eventVariant := event.AsAny().(type) {769  	case anthropic.ContentBlockDeltaEvent:770  		switch deltaVariant := eventVariant.Delta.AsAny().(type) {771  		case anthropic.TextDelta:772  			fmt.Print(deltaVariant.Text)773  		}774  	}775  }776  if err := stream.Err(); err != nil {777  	log.Fatal(err)778  }779  ```780781  ```java Java782  AnthropicClient client = AnthropicOkHttpClient.fromEnv();783784  MessageCreateParams params = MessageCreateParams.builder()785      .model(Model.CLAUDE_OPUS_5)786      .maxTokens(1024L)787      .addTool(Tool.builder()788          .name("get_weather")789          .description("Get the current weather in a given location")790          .inputSchema(Tool.InputSchema.builder()791              .properties(JsonValue.from(Map.of(792                  "location", Map.of(793                      "type", "string",794                      "description", "The city and state, e.g. San Francisco, CA"795                  )796              )))797              .putAdditionalProperty("required", JsonValue.from(List.of("location")))798              .build())799          .build())800      .toolChoice(ToolChoice.ofAny(ToolChoiceAny.builder().build()))801      .addUserMessage("What is the weather like in San Francisco?")802      .build();803804  try (var streamResponse = client.messages().createStreaming(params)) {805      streamResponse.stream().forEach(event -> {806          event.contentBlockDelta().ifPresent(deltaEvent ->807              deltaEvent.delta().text().ifPresent(td ->808                  System.out.print(td.text())809              )810          );811      });812  }813  ```814815  ```php PHP816  $client = new Client();817818  $stream = $client->messages->createStream(819      maxTokens: 1024,820      messages: [821          ['role' => 'user', 'content' => 'What is the weather like in San Francisco?']822      ],823      model: 'claude-opus-5',824      toolChoice: ['type' => 'any'],825      tools: [826          [827              'name' => 'get_weather',828              'description' => 'Get the current weather in a given location',829              'input_schema' => [830                  'type' => 'object',831                  'properties' => [832                      'location' => [833                          'type' => 'string',834                          'description' => 'The city and state, e.g. San Francisco, CA'835                      ]836                  ],837                  'required' => ['location']838              ]839          ]840      ],841  );842843  foreach ($stream as $message) {844      echo $message;845  }846  ```847848  ```ruby Ruby849  client = Anthropic::Client.new850851  tools = [852    {853      name: "get_weather",854      description: "Get the current weather in a given location",855      input_schema: {856        type: "object",857        properties: {858          location: {859            type: "string",860            description: "The city and state, e.g. San Francisco, CA"861          }862        },863        required: ["location"]864      }865    }866  ]867868  stream = client.messages.stream(869    model: "claude-opus-5",870    max_tokens: 1024,871    tools: tools,872    tool_choice: { type: "any" },873    messages: [874      { role: "user", content: "What is the weather like in San Francisco?" }875    ]876  )877878  stream.text.each { |text| print(text) }879  ```880</CodeGroup>881882```sse Response883event: message_start884data: {"type":"message_start","message":{"id":"msg_014p7gG3wDgGV9EUtLvnow3U","type":"message","role":"assistant","model":"claude-opus-5","stop_sequence":null,"usage":{"input_tokens":472,"output_tokens":2},"content":[],"stop_reason":null}}885886event: content_block_start887data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}888889event: ping890data: {"type": "ping"}891892event: content_block_delta893data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Okay"}}894895event: content_block_delta896data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":","}}897898event: content_block_delta899data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":" let"}}900901event: content_block_delta902data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"'s"}}903904event: content_block_delta905data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":" check"}}906907event: content_block_delta908data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":" the"}}909910event: content_block_delta911data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":" weather"}}912913event: content_block_delta914data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":" for"}}915916event: content_block_delta917data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":" San"}}918919event: content_block_delta920data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":" Francisco"}}921922event: content_block_delta923data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":","}}924925event: content_block_delta926data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":" CA"}}927928event: content_block_delta929data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":":"}}930931event: content_block_stop932data: {"type":"content_block_stop","index":0}933934event: content_block_start935data: {"type":"content_block_start","index":1,"content_block":{"type":"tool_use","id":"toolu_01T1x1fJ34qAmk2tNTrN7Up6","name":"get_weather","input":{}}}936937event: content_block_delta938data: {"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":""}}939940event: content_block_delta941data: {"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":"{\"location\":"}}942943event: content_block_delta944data: {"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":" \"San"}}945946event: content_block_delta947data: {"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":" Francisc"}}948949event: content_block_delta950data: {"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":"o,"}}951952event: content_block_delta953data: {"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":" CA\"}"}}954955event: content_block_stop956data: {"type":"content_block_stop","index":1}957958event: message_delta959data: {"type":"message_delta","delta":{"stop_reason":"tool_use","stop_sequence":null},"usage":{"output_tokens":89}}960961event: message_stop962data: {"type":"message_stop"}963```964965### Streaming request with thinking966967This request enables thinking with streaming. The `display: "summarized"` setting streams a condensed summary of Claude's reasoning rather than the full chain of thought.968969<CodeGroup>970  ```bash cURL971  curl https://api.anthropic.com/v1/messages \972    -H "x-api-key: $ANTHROPIC_API_KEY" \973    -H "anthropic-version: 2023-06-01" \974    -H "content-type: application/json" \975    -d '{976      "model": "claude-opus-5",977      "max_tokens": 20000,978      "stream": true,979      "thinking": {980        "type": "adaptive",981        "display": "summarized"982      },983      "messages": [984        {985          "role": "user",986          "content": "What is the greatest common divisor of 1071 and 462?"987        }988      ]989    }'990  ```991992  ```bash CLI993  ant messages create --stream --format jsonl \994    --model claude-opus-5 \995    --max-tokens 20000 \996    --thinking '{type: adaptive, display: summarized}' \997    --message '{role: user, content: What is the greatest common divisor of 1071 and 462?}'998  ```9991000  ```python Python1001  client = anthropic.Anthropic()10021003  with client.messages.stream(1004      model="claude-opus-5",1005      max_tokens=20000,1006      thinking={"type": "adaptive", "display": "summarized"},1007      messages=[1008          {1009              "role": "user",1010              "content": "What is the greatest common divisor of 1071 and 462?",1011          }1012      ],1013  ) as stream:1014      for event in stream:1015          if event.type == "content_block_delta":1016              delta = event.delta1017              match delta.type:1018                  case "thinking_delta":1019                      print(delta.thinking, end="", flush=True)1020                  case "text_delta":1021                      print(delta.text, end="", flush=True)1022  ```10231024  ```typescript TypeScript1025  const client = new Anthropic();10261027  const stream = client.messages.stream({1028    model: "claude-opus-5",1029    max_tokens: 20000,1030    thinking: { type: "adaptive", display: "summarized" },1031    messages: [1032      {1033        role: "user",1034        content: "What is the greatest common divisor of 1071 and 462?"1035      }1036    ]1037  });10381039  for await (const event of stream) {1040    if (event.type === "content_block_delta") {1041      switch (event.delta.type) {1042        case "thinking_delta":1043          process.stdout.write(event.delta.thinking);1044          break;1045        case "text_delta":1046          process.stdout.write(event.delta.text);1047          break;1048      }1049    }1050  }1051  ```10521053  ```csharp C#1054  using Anthropic;1055  using Anthropic.Models.Messages;10561057  AnthropicClient client = new();10581059  var parameters = new MessageCreateParams1060  {1061      Model = Model.ClaudeOpus5,1062      MaxTokens = 20000,1063      Thinking = new ThinkingConfigAdaptive { Display = Display.Summarized },1064      Messages = [new() { Role = Role.User, Content = "What is the greatest common divisor of 1071 and 462?" }]1065  };10661067  await foreach (var msg in client.Messages.CreateStreaming(parameters))1068  {1069      Console.Write(msg);1070  }1071  ```10721073  ```go Go1074  client := anthropic.NewClient()10751076  stream := client.Messages.NewStreaming(context.TODO(), anthropic.MessageNewParams{1077  	Model:     anthropic.ModelClaudeOpus5,1078  	MaxTokens: 20000,1079  	Thinking: anthropic.ThinkingConfigParamUnion{1080  		OfAdaptive: &anthropic.ThinkingConfigAdaptiveParam{1081  			Display: anthropic.ThinkingConfigAdaptiveDisplaySummarized,1082  		},1083  	},1084  	Messages: []anthropic.MessageParam{1085  		anthropic.NewUserMessage(anthropic.NewTextBlock("What is the greatest common divisor of 1071 and 462?")),1086  	},1087  })10881089  for stream.Next() {1090  	event := stream.Current()1091  	switch eventVariant := event.AsAny().(type) {1092  	case anthropic.ContentBlockDeltaEvent:1093  		switch deltaVariant := eventVariant.Delta.AsAny().(type) {1094  		case anthropic.ThinkingDelta:1095  			fmt.Print(deltaVariant.Thinking)1096  		case anthropic.TextDelta:1097  			fmt.Print(deltaVariant.Text)1098  		}1099  	}1100  }1101  if err := stream.Err(); err != nil {1102  	log.Fatal(err)1103  }1104  ```11051106  ```java Java1107  AnthropicClient client = AnthropicOkHttpClient.fromEnv();11081109  MessageCreateParams params = MessageCreateParams.builder()1110      .model(Model.CLAUDE_OPUS_5)1111      .maxTokens(20000L)1112      .thinking(ThinkingConfigAdaptive.builder()1113          .display(ThinkingConfigAdaptive.Display.SUMMARIZED)1114          .build())1115      .addUserMessage("What is the greatest common divisor of 1071 and 462?")1116      .build();11171118  try (var streamResponse = client.messages().createStreaming(params)) {1119      streamResponse.stream().forEach(event -> {1120          event.contentBlockDelta().ifPresent(deltaEvent -> {1121              deltaEvent.delta().thinking().ifPresent(td ->1122                  IO.print(td.thinking())1123              );1124              deltaEvent.delta().text().ifPresent(td ->1125                  IO.print(td.text())1126              );1127          });1128      });1129  }1130  ```11311132  ```php PHP1133  $client = new Client();11341135  $stream = $client->messages->createStream(1136      maxTokens: 20000,1137      messages: [1138          ['role' => 'user', 'content' => 'What is the greatest common divisor of 1071 and 462?']1139      ],1140      model: 'claude-opus-5',1141      thinking: ['type' => 'adaptive', 'display' => 'summarized'],1142  );11431144  foreach ($stream as $message) {1145      echo $message;1146  }1147  ```11481149  ```ruby Ruby1150  client = Anthropic::Client.new11511152  stream = client.messages.stream(1153    model: "claude-opus-5",1154    max_tokens: 20000,1155    thinking: { type: "adaptive", display: "summarized" },1156    messages: [1157      { role: "user", content: "What is the greatest common divisor of 1071 and 462?" }1158    ]1159  )11601161  stream.each do |event|1162    if event.is_a?(Anthropic::Models::RawContentBlockDeltaEvent)1163      delta = event.delta1164      case delta1165      when Anthropic::Models::ThinkingDelta1166        print(delta.thinking)1167      when Anthropic::Models::TextDelta1168        print(delta.text)1169      end1170    end1171  end1172  ```1173</CodeGroup>11741175```sse Response1176event: message_start1177data: {"type": "message_start", "message": {"id": "msg_01...", "type": "message", "role": "assistant", "content": [], "model": "claude-opus-5", "stop_reason": null, "stop_sequence": null}}11781179event: content_block_start1180data: {"type": "content_block_start", "index": 0, "content_block": {"type": "thinking", "thinking": "", "signature": ""}}11811182event: content_block_delta1183data: {"type": "content_block_delta", "index": 0, "delta": {"type": "thinking_delta", "thinking": "I need to find the GCD of 1071 and 462 using the Euclidean algorithm.\n\n1071 = 2 × 462 + 147"}}11841185event: content_block_delta1186data: {"type": "content_block_delta", "index": 0, "delta": {"type": "thinking_delta", "thinking": "\n462 = 3 × 147 + 21"}}11871188event: content_block_delta1189data: {"type": "content_block_delta", "index": 0, "delta": {"type": "thinking_delta", "thinking": "\n147 = 7 × 21 + 0"}}11901191event: content_block_delta1192data: {"type": "content_block_delta", "index": 0, "delta": {"type": "thinking_delta", "thinking": "\nThe remainder is 0, so GCD(1071, 462) = 21."}}11931194event: content_block_delta1195data: {"type": "content_block_delta", "index": 0, "delta": {"type": "signature_delta", "signature": "EqQBCgIYAhIM1gbcDa9GJwZA2b3hGgxBdjrkzLoky3dl1pkiMOYds..."}}11961197event: content_block_stop1198data: {"type": "content_block_stop", "index": 0}11991200event: content_block_start1201data: {"type": "content_block_start", "index": 1, "content_block": {"type": "text", "text": ""}}12021203event: content_block_delta1204data: {"type": "content_block_delta", "index": 1, "delta": {"type": "text_delta", "text": "The greatest common divisor of 1071 and 462 is **21**."}}12051206event: content_block_stop1207data: {"type": "content_block_stop", "index": 1}12081209event: message_delta1210data: {"type": "message_delta", "delta": {"stop_reason": "end_turn", "stop_sequence": null}}12111212event: message_stop1213data: {"type": "message_stop"}1214```12151216### Streaming request with web search tool use12171218This request asks Claude to search the web for current weather information.12191220<CodeGroup>1221  ```bash cURL1222  curl https://api.anthropic.com/v1/messages \1223    -H "x-api-key: $ANTHROPIC_API_KEY" \1224    -H "anthropic-version: 2023-06-01" \1225    -H "content-type: application/json" \1226    -d '{1227      "model": "claude-opus-5",1228      "max_tokens": 1024,1229      "stream": true,1230      "tools": [1231        {1232          "type": "web_search_20250305",1233          "name": "web_search",1234          "max_uses": 51235        }1236      ],1237      "messages": [1238        {1239          "role": "user",1240          "content": "What is the weather like in New York City today?"1241        }1242      ]1243    }'1244  ```12451246  ```bash CLI1247  ant messages create --stream --format jsonl \1248    --model claude-opus-5 \1249    --max-tokens 1024 \1250    --tool '{type: web_search_20250305, name: web_search, max_uses: 5}' \1251    --message '{role: user, content: What is the weather like in New York City today?}'1252  ```12531254  ```python Python1255  client = anthropic.Anthropic()12561257  with client.messages.stream(1258      model="claude-opus-5",1259      max_tokens=1024,1260      tools=[{"type": "web_search_20250305", "name": "web_search", "max_uses": 5}],1261      messages=[1262          {"role": "user", "content": "What is the weather like in New York City today?"}1263      ],1264  ) as stream:1265      for text in stream.text_stream:1266          print(text, end="", flush=True)1267  ```12681269  ```typescript TypeScript1270  const client = new Anthropic();12711272  const stream = client.messages.stream({1273    model: "claude-opus-5",1274    max_tokens: 1024,1275    tools: [{ type: "web_search_20250305", name: "web_search", max_uses: 5 }],1276    messages: [{ role: "user", content: "What is the weather like in New York City today?" }]1277  });12781279  for await (const event of stream) {1280    if (event.type === "content_block_delta" && event.delta.type === "text_delta") {1281      process.stdout.write(event.delta.text);1282    }1283  }1284  ```12851286  ```csharp C#1287  using Anthropic;1288  using Anthropic.Models.Messages;12891290  AnthropicClient client = new();12911292  var parameters = new MessageCreateParams1293  {1294      Model = Model.ClaudeOpus5,1295      MaxTokens = 1024,1296      Tools = [new ToolUnion(new WebSearchTool20250305() { MaxUses = 5 })],1297      Messages = [new() { Role = Role.User, Content = "What is the weather like in New York City today?" }]1298  };12991300  await foreach (var msg in client.Messages.CreateStreaming(parameters))1301  {1302      Console.Write(msg);1303  }1304  ```13051306  ```go Go1307  client := anthropic.NewClient()13081309  stream := client.Messages.NewStreaming(context.TODO(), anthropic.MessageNewParams{1310  	Model:     anthropic.ModelClaudeOpus5,1311  	MaxTokens: 1024,1312  	Tools: []anthropic.ToolUnionParam{1313  		{1314  			OfWebSearchTool20250305: &anthropic.WebSearchTool20250305Param{1315  				MaxUses: anthropic.Int(5),1316  			},1317  		},1318  	},1319  	Messages: []anthropic.MessageParam{1320  		anthropic.NewUserMessage(anthropic.NewTextBlock("What is the weather like in New York City today?")),1321  	},1322  })13231324  for stream.Next() {1325  	event := stream.Current()1326  	switch eventVariant := event.AsAny().(type) {1327  	case anthropic.ContentBlockDeltaEvent:1328  		switch deltaVariant := eventVariant.Delta.AsAny().(type) {1329  		case anthropic.TextDelta:1330  			fmt.Print(deltaVariant.Text)1331  		}1332  	}1333  }1334  if err := stream.Err(); err != nil {1335  	log.Fatal(err)1336  }1337  ```13381339  ```java Java1340  AnthropicClient client = AnthropicOkHttpClient.fromEnv();13411342  MessageCreateParams params = MessageCreateParams.builder()1343      .model(Model.CLAUDE_OPUS_5)1344      .maxTokens(1024L)1345      .addTool(WebSearchTool20250305.builder()1346          .maxUses(5L)1347          .build())1348      .addUserMessage("What is the weather like in New York City today?")1349      .build();13501351  try (var streamResponse = client.messages().createStreaming(params)) {1352      streamResponse.stream().forEach(event -> {1353          event.contentBlockDelta().ifPresent(deltaEvent ->1354              deltaEvent.delta().text().ifPresent(td ->1355                  System.out.print(td.text())1356              )1357          );1358      });1359  }1360  ```13611362  ```php PHP1363  $client = new Client();13641365  $stream = $client->messages->createStream(1366      maxTokens: 1024,1367      messages: [1368          ['role' => 'user', 'content' => 'What is the weather like in New York City today?']1369      ],1370      model: 'claude-opus-5',1371      tools: [1372          ['type' => 'web_search_20250305', 'name' => 'web_search', 'max_uses' => 5]1373      ],1374  );13751376  foreach ($stream as $message) {1377      echo $message;1378  }1379  ```13801381  ```ruby Ruby1382  client = Anthropic::Client.new13831384  stream = client.messages.stream(1385    model: :"claude-opus-5",1386    max_tokens: 1024,1387    tools: [1388      {1389        type: "web_search_20250305",1390        name: "web_search",1391        max_uses: 51392      }1393    ],1394    messages: [1395      {1396        role: "user",1397        content: "What is the weather like in New York City today?"1398      }1399    ]1400  )14011402  stream.text.each { |text| print(text) }1403  ```1404</CodeGroup>14051406```sse Response1407event: message_start1408data: {"type":"message_start","message":{"id":"msg_01G...","type":"message","role":"assistant","model":"claude-opus-5","content":[],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":2679,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"output_tokens":3}}}14091410event: content_block_start1411data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}14121413event: content_block_delta1414data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"I'll check"}}14151416event: content_block_delta1417data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":" the current weather in New York City for you"}}14181419event: ping1420data: {"type": "ping"}14211422event: content_block_delta1423data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"."}}14241425event: content_block_stop1426data: {"type":"content_block_stop","index":0}14271428event: content_block_start1429data: {"type":"content_block_start","index":1,"content_block":{"type":"server_tool_use","id":"srvtoolu_014hJH82Qum7Td6UV8gDXThB","name":"web_search","input":{}}}14301431event: content_block_delta1432data: {"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":""}}14331434event: content_block_delta1435data: {"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":"{\"query"}}14361437event: content_block_delta1438data: {"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":"\":"}}14391440event: content_block_delta1441data: {"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":" \"weather"}}14421443event: content_block_delta1444data: {"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":" NY"}}14451446event: content_block_delta1447data: {"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":"C to"}}14481449event: content_block_delta1450data: {"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":"day\"}"}}14511452event: content_block_stop1453data: {"type":"content_block_stop","index":1 }14541455event: content_block_start1456data: {"type":"content_block_start","index":2,"content_block":{"type":"web_search_tool_result","tool_use_id":"srvtoolu_014hJH82Qum7Td6UV8gDXThB","content":[{"type":"web_search_result","title":"Weather in New York City in May 2025 (New York) - detailed Weather Forecast for a month","url":"https://world-weather.info/forecast/usa/new_york/may-2025/","encrypted_content":"Ev0DCioIAxgCIiQ3NmU4ZmI4OC1k...","page_age":null},...]}}14571458event: content_block_stop1459data: {"type":"content_block_stop","index":2}14601461event: content_block_start1462data: {"type":"content_block_start","index":3,"content_block":{"type":"text","text":""}}14631464event: content_block_delta1465data: {"type":"content_block_delta","index":3,"delta":{"type":"text_delta","text":"Here's the current weather information for New York"}}14661467event: content_block_delta1468data: {"type":"content_block_delta","index":3,"delta":{"type":"text_delta","text":" City:\n\n# Weather"}}14691470event: content_block_delta1471data: {"type":"content_block_delta","index":3,"delta":{"type":"text_delta","text":" in New York City"}}14721473event: content_block_delta1474data: {"type":"content_block_delta","index":3,"delta":{"type":"text_delta","text":"\n\n"}}14751476...14771478event: content_block_stop1479data: {"type":"content_block_stop","index":17}14801481event: message_delta1482data: {"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"input_tokens":10682,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"output_tokens":510,"server_tool_use":{"web_search_requests":1}}}14831484event: message_stop1485data: {"type":"message_stop"}1486```14871488## Error recovery14891490### Claude 4.5 and earlier14911492For Claude 4.5 models and earlier, you can recover a streaming request that was interrupted because of network issues, timeouts, or other errors by resuming from where the stream was interrupted. This approach saves you from re-processing the entire response.14931494The basic recovery strategy involves:149514961. **Capture the partial response:** Save all content that was successfully received before the error occurred.14972. **Construct a continuation request:** Create a new API request that includes the partial assistant response as the beginning of a new assistant message.14983. **Resume streaming:** Continue receiving the rest of the response from where it was interrupted.14991500### Claude 4.6 and later15011502For Claude 4.6 and later models, the same capture-and-resume strategy applies, but step 2 changes: instead of placing the partial response in an assistant message, add a user message that instructs the model to continue from where it left off.150315041. **Capture the partial response:** Save all content that was successfully received before the error occurred.15052. **Construct a continuation request:** Create a new API request with a user message containing the partial response and an instruction to continue, for example:1506   ```text Sample prompt wrap1507   Your previous response was interrupted and ended with [previous_response]. Continue from where you left off.1508   ```15093. **Resume streaming:** Continue receiving the rest of the response from where it was interrupted.15101511### Error recovery best practices151215131. **Use SDK features:** Leverage the SDK's built-in message accumulation and error handling capabilities.15142. **Handle content types:** Be aware that messages can contain multiple content blocks (`text`, `tool_use`, `thinking`). Tool use and extended thinking blocks cannot be partially recovered. You can resume streaming from the most recent text block.15151516## Next steps15171518<CardGroup cols={2}>1519  <Card title="Stop reasons and fallback" icon="list" href="https://platform.claude.com/docs/en/build-with-claude/handling-stop-reasons">1520    Handle each `stop_reason` value once a stream completes.1521  </Card>15221523  <Card title="Fine-grained tool streaming" icon="wrench" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/fine-grained-tool-streaming">1524    Stream tool input JSON without server-side buffering for lower latency.1525  </Card>15261527  <Card title="Thinking" icon="brain" href="https://platform.claude.com/docs/en/build-with-claude/thinking">1528    Stream thinking output with `thinking_delta` and `signature_delta` events.1529  </Card>15301531  <Card title="Client SDKs" icon="code" href="https://platform.claude.com/docs/en/cli-sdks-libraries/overview">1532    Use the official SDKs, which handle streaming, accumulation, and reconnection for you.1533  </Card>15341535  <Card title="Batch processing" icon="stack" href="https://platform.claude.com/docs/en/build-with-claude/batch-processing">1536    Process large volumes of requests asynchronously when you don't need real-time responses.1537  </Card>1538</CardGroup>1539
Files main
Menu

Theme