用途:为 Claude API 实现基于 Server-Sent Events(SSE)的实时流式响应,适用于实时用户界面、长时间生成、渐进式输出展示、带流式的工具调用以及扩展思考可视化。
主要能力:提供 SSE 事件流说明(message_start、content_block_start、content_block_delta、content_block_stop、message_delta、message_stop);支持文本增量(text_delta)、工具输入增量(input_json_delta)、思考增量(thinking_delta)与签名增量(signature_delta);给出 Python 与 TypeScript 的基础流式与事件式实现示例。
使用方式:Python 用 anthropic 客户端的 client.messages.stream(...) 配合 stream.text_stream 或遍历事件;TypeScript 用 @anthropic-ai/sdk 的 client.messages.stream(...) 并 await stream.finalMessage()。工具调用须累积 partial_json,在 content_block_stop 后再解析,切勿流中解析。扩展思考用 thinking={"type":"adaptive"},max_tokens 需较大。
限制与注意:HTTP 200 也可能出现 error 事件,需处理 overloaded_error;可重试错误包括 529、429、500、502、503,建议指数退避;读超时建议不小于 60 秒;连接空闲不超过 5 分钟。其余内容(如计费、平台详情)暂未提供。