Skip to main content

Tool Use

import anthropic

client = anthropic.Anthropic(api_key="your-api-key", base_url="https://aisupermarket.work")

tools = [
{
"name": "get_weather",
"description": "Get the weather for a specified city",
"input_schema": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "City name"}
},
"required": ["city"]
}
}
]

response = client.messages.create(
model="claude-opus-4-7",
max_tokens=1024,
tools=tools,
messages=[{"role": "user", "content": "What is the weather in Guangzhou today?"}]
)

for block in response.content:
if block.type == "tool_use":
print(f"Tool call: {block.name}, args: {block.input}")

Complete Tool Calling Loop

import anthropic

client = anthropic.Anthropic(api_key="your-api-key", base_url="https://aisupermarket.work")

def get_weather(city: str) -> str:
return f"{city} is sunny today, 25°C"

tools = [
{
"name": "get_weather",
"description": "Get the weather for a specified city",
"input_schema": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"]
}
}
]

messages = [{"role": "user", "content": "What is the weather in Beijing?"}]

while True:
response = client.messages.create(
model="claude-opus-4-7",
max_tokens=1024,
tools=tools,
messages=messages
)

if response.stop_reason == "end_turn":
print(response.content[0].text)
break

tool_results = []
for block in response.content:
if block.type == "tool_use":
result = get_weather(**block.input)
tool_results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": result
})

messages.append({"role": "assistant", "content": response.content})
messages.append({"role": "user", "content": tool_results})