Workflow-002: Tool Use Implementation
FreshSource: Building with the Claude API
Document Control
| Field | Value |
|---|---|
| Workflow ID | WF-002 |
| Version | 1.0 |
| Status | Active |
| Last Updated | 2024-12 |
Overview
Implement function calling to extend Claude with custom tools.
Tool Use Flow
Step 1: Define Tools
python
tools = [
{
"name": "get_weather",
"description": "Get current weather for a location",
"input_schema": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "City and state, e.g. San Francisco, CA"
},
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "Temperature unit"
}
},
"required": ["location"]
}
}
]Step 2: Make Request with Tools
python
import anthropic
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
tools=tools,
messages=[
{"role": "user", "content": "What's the weather in Boston?"}
]
)Step 3: Handle Tool Use
python
def process_response(response):
for block in response.content:
if block.type == "tool_use":
# Execute the tool
result = execute_tool(block.name, block.input)
# Return result to Claude
return continue_with_result(
response,
block.id,
result
)
elif block.type == "text":
return block.textTool Response Handling
TEXT BLOCK:
json
{
"type": "text",
"text": "Let me check the weather for you."
}TOOL_USE BLOCK:
json
{
"type": "tool_use",
"id": "toolu_01ABC...",
"name": "get_weather",
"input": {"location": "Boston, MA"}
}Step 4: Continue Conversation
python
def continue_with_result(original_response, tool_id, result):
return client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
tools=tools,
messages=[
{"role": "user", "content": "What's the weather?"},
{"role": "assistant", "content": original_response.content},
{
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": tool_id,
"content": json.dumps(result)
}
]
}
]
)Multi-Tool Pattern
Tool Design Best Practices
| Practice | Description |
|---|---|
| Clear names | get_user_info not getUserInfo |
| Good descriptions | Explain what tool does AND when to use |
| Minimal parameters | Only request what's needed |
| Enum when possible | Restrict to valid values |
| Error handling | Return helpful error messages |
Verification Checklist
- [ ] Tool schema defined with descriptions
- [ ] Response handling covers all block types
- [ ] Tool execution implemented
- [ ] Result formatting correct
- [ ] Multi-turn conversation works
- [ ] Errors handled gracefully