python --version
pip install anthropic
export ANTHROPIC_API_KEY=...
Use the Anthropic API for streaming responses, tool use, and vision with Claude claude-3-5-sonnet.
1 import os 2 import json 3 import anthropic 4 5 client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"]) 6 7 # ── 1. Streaming response ─────────────────────────────────────────── 8 print("=== Streaming ===") 9 with client.messages.stream( 10 model="claude-3-5-haiku-20241022", 11 max_tokens=300, 12 messages=[{"role": "user", "content": "Write a haiku about distributed systems."}], 13 ) as stream: 14 for text in stream.text_stream: 15 print(text, end="", flush=True) 16 print() 17 18 # ── 2. Tool use ───────────────────────────────────────────────────── 19 print(" 20 === Tool Use ===") 21 tools = [ 22 { 23 "name": "get_weather", 24 "description": "Get current weather for a city", 25 "input_schema": { 26 "type": "object", 27 "properties": { 28 "city": {"type": "string", "description": "City name"}, 29 "units": {"type": "string", "enum": ["celsius", "fahrenheit"]}, 30 }, 31 "required": ["city"], 32 }, 33 } 34 ] 35 36 response = client.messages.create( 37 model="claude-3-5-haiku-20241022", 38 max_tokens=300, 39 tools=tools, 40 messages=[{"role": "user", "content": "What's the weather in Tokyo?"}], 41 ) 42 43 # Check for tool use 44 for block in response.content: 45 if block.type == "tool_use": 46 print(f"Tool called: {block.name}") 47 print(f"Input: {json.dumps(block.input, indent=2)}") 48 49 # Simulate tool execution 50 tool_result = {"temperature": 22, "condition": "Partly cloudy", "units": "celsius"} 51 52 # Continue conversation with tool result 53 follow_up = client.messages.create( 54 model="claude-3-5-haiku-20241022", 55 max_tokens=200, 56 tools=tools, 57 messages=[ 58 {"role": "user", "content": "What's the weather in Tokyo?"}, 59 {"role": "assistant", "content": response.content}, 60 { 61 "role": "user", 62 "content": [{ 63 "type": "tool_result", 64 "tool_use_id": block.id, 65 "content": json.dumps(tool_result), 66 }], 67 }, 68 ], 69 ) 70 print(f"Final: {follow_up.content[0].text}") 71 elif block.type == "text": 72 print(f"Text: {block.text}") 73
Sign in to share your feedback and join the discussion.