()
| 4 | |
| 5 | |
| 6 | async def main() -> None: |
| 7 | client = AsyncAnthropic() |
| 8 | |
| 9 | print("Claude with Web Search (Streaming)") |
| 10 | print("==================================") |
| 11 | |
| 12 | # Create an async stream with web search enabled |
| 13 | async with client.beta.messages.stream( |
| 14 | model="claude-sonnet-5", |
| 15 | max_tokens=1024, |
| 16 | messages=[{"role": "user", "content": "What's the weather in New York?"}], |
| 17 | tools=[ |
| 18 | { |
| 19 | "name": "web_search", |
| 20 | "type": "web_search_20250305", |
| 21 | } |
| 22 | ], |
| 23 | ) as stream: |
| 24 | # Process streaming events |
| 25 | async for chunk in stream: |
| 26 | # Print text deltas as they arrive |
| 27 | if chunk.type == "content_block_delta" and chunk.delta.type == "text_delta": |
| 28 | print(chunk.delta.text, end="", flush=True) |
| 29 | |
| 30 | # Track when web search is being used |
| 31 | elif chunk.type == "content_block_start" and chunk.content_block.type == "web_search_tool_result": |
| 32 | print("\n[Web search started...]", end="", flush=True) |
| 33 | |
| 34 | elif chunk.type == "content_block_stop" and chunk.content_block.type == "web_search_tool_result": |
| 35 | print("[Web search completed]", end="\n\n", flush=True) |
| 36 | |
| 37 | # Get the final complete message |
| 38 | message = await stream.get_final_message() |
| 39 | |
| 40 | print("\n\nFinal usage statistics:") |
| 41 | print(f"Input tokens: {message.usage.input_tokens}") |
| 42 | print(f"Output tokens: {message.usage.output_tokens}") |
| 43 | |
| 44 | if message.usage.server_tool_use: |
| 45 | print(f"Web search requests: {message.usage.server_tool_use.web_search_requests}") |
| 46 | else: |
| 47 | print("No web search requests recorded in usage") |
| 48 | |
| 49 | # Rather than parsing the web search results structure (which varies), |
| 50 | # we'll just show the complete message structure for debugging |
| 51 | print("\nMessage Content Types:") |
| 52 | for i, block in enumerate(message.content): |
| 53 | print(f"Content Block {i + 1}: Type = {block.type}") |
| 54 | |
| 55 | # Show the entire message structure as JSON for debugging |
| 56 | print("\nComplete message structure (JSON):") |
| 57 | print(message.model_dump_json(indent=2)) |
| 58 | |
| 59 | |
| 60 | if __name__ == "__main__": |
no test coverage detected