| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from anthropic import Anthropic |
| 4 |
from anthropic.types import ToolParam, MessageParam |
| 5 |
|
| 6 |
client = Anthropic() |
| 7 |
|
| 8 |
user_message: MessageParam = { |
| 9 |
"role": "user", |
| 10 |
"content": "What is the weather in SF?", |
| 11 |
} |
| 12 |
tools: list[ToolParam] = [ |
| 13 |
{ |
| 14 |
"name": "get_weather", |
| 15 |
"description": "Get the weather for a specific location", |
| 16 |
"input_schema": { |
| 17 |
"type": "object", |
| 18 |
"properties": {"location": {"type": "string"}}, |
| 19 |
}, |
| 20 |
} |
| 21 |
] |
| 22 |
|
| 23 |
message = client.messages.create( |
| 24 |
model="claude-sonnet-5-5", |
| 25 |
max_tokens=1024, |
| 26 |
messages=[user_message], |
| 27 |
tools=tools, |
| 28 |
) |
| 29 |
print(f"Initial response: {message.model_dump_json(indent=2)}") |
| 30 |
|
| 31 |
assert message.stop_reason == "tool_use" |
| 32 |
|
| 33 |
tool = next(c for c in message.content if c.type == "tool_use") |
| 34 |
response = client.messages.create( |
| 35 |
model="claude-sonnet-5-5", |
| 36 |
max_tokens=1024, |
| 37 |
messages=[ |
| 38 |
user_message, |
| 39 |
{"role": message.role, "content": message.content}, |
| 40 |
{ |
| 41 |
"role": "user", |
| 42 |
"content": [ |
| 43 |
{ |
| 44 |
"type": "tool_result", |
| 45 |
"tool_use_id": tool.id, |
| 46 |
"content": [{"type": "text", "text": "The weather is 73f"}], |
| 47 |
} |
| 48 |
], |
| 49 |
}, |
| 50 |
], |
| 51 |
tools=tools, |
| 52 |
) |
| 53 |
print(f"\nFinal response: {response.model_dump_json(indent=2)}") |