import json
from anthropic import Anthropic
client = Anthropic(
base_url="https://www.samuraiapi.in/api",
api_key="YOUR_SAMURAI_KEY"
)
tools = [
{
"name": "get_weather",
"description": "Get the current weather for a city",
"input_schema": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "The city name, e.g. 'Tokyo'"
},
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "Temperature unit"
}
},
"required": ["city"]
}
}
]
# Step 1: Send initial message with tools
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
tools=tools,
messages=[{"role": "user", "content": "What's the weather in Tokyo?"}]
)
# Step 2: Check if Claude wants to use a tool
if response.stop_reason == "tool_use":
tool_use = next(b for b in response.content if b.type == "tool_use")
print(f"Claude called: {tool_use.name}({tool_use.input})")
# Step 3: Execute the tool
def get_weather(city: str, unit: str = "celsius"):
return {"city": city, "temperature": 18, "condition": "Partly cloudy", "unit": unit}
result = get_weather(**tool_use.input)
# Step 4: Send the result back
final = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
tools=tools,
messages=[
{"role": "user", "content": "What's the weather in Tokyo?"},
{"role": "assistant", "content": response.content},
{
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": tool_use.id,
"content": json.dumps(result)
}
]
}
]
)
print(final.content[0].text)
# => "The current weather in Tokyo is 18°C and partly cloudy."