| 1 |
import asyncio |
| 2 |
|
| 3 |
from anthropic import AsyncAnthropic |
| 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 |
async for chunk in stream: |
| 25 |
if chunk.type == "content_block_delta" and chunk.delta.type == "text_delta": |
| 26 |
print(chunk.delta.text, end="", flush=True) |
| 27 |
|
| 28 |
# Track when web search is being used |
| 29 |
elif chunk.type == "content_block_start" and chunk.content_block.type == "web_search_tool_result": |
| 30 |
print("\n[Web search started...]", end="", flush=True) |
| 31 |
|
| 32 |
elif chunk.type == "content_block_stop" and chunk.content_block.type == "web_search_tool_result": |
| 33 |
print("[Web search completed]", end="\n\n", flush=True) |
| 34 |
|
| 35 |
message = await stream.get_final_message() |
| 36 |
|
| 37 |
print("\n\nFinal usage statistics:") |
| 38 |
print(f"Input tokens: {message.usage.input_tokens}") |
| 39 |
print(f"Output tokens: {message.usage.output_tokens}") |
| 40 |
|
| 41 |
if message.usage.server_tool_use: |
| 42 |
print(f"Web search requests: {message.usage.server_tool_use.web_search_requests}") |
| 43 |
else: |
| 44 |
print("No web search requests recorded in usage") |
| 45 |
|
| 46 |
# Rather than parsing the web search results structure (which varies), |
| 47 |
# we'll just show the complete message structure for debugging |
| 48 |
print("\nMessage Content Types:") |
| 49 |
for i, block in enumerate(message.content): |
| 50 |
print(f"Content Block {i + 1}: Type = {block.type}") |
| 51 |
|
| 52 |
print("\nComplete message structure (JSON):") |
| 53 |
print(message.model_dump_json(indent=2)) |
| 54 |
|
| 55 |
|
| 56 |
if __name__ == "__main__": |
| 57 |
asyncio.run(main()) |