Anthropic Tool Use (Function Calling) Integration for Your App
Imagine a CRM manager spending 20–30 minutes gathering deal history, recent contacts, and open tasks before a meeting. With 50 managers, that's 1000 hours per month lost to routine. Tool Use from Anthropic turns Claude into an assistant that searches CRM, sends emails, and creates tasks in seconds — without risking SQL injection or exposing code. Claude doesn't execute code; it returns structured JSON with the tool name and arguments. Your application does the real work and returns the result. This is the foundation for agents working with live data.
Our engineers have over 5 years of commercial AI development and 50+ successful projects with RAG and Function Calling. We guarantee production-ready code with logging, retries, and monitoring. Contact us — we'll implement Tool Use in 3 days.
What Problems Does Tool Use Solve?
Without Tool Use, the model is limited to text generation. To get data from a database, you either give it direct SQL access (dangerous) or manually parse its responses and execute code. Tool Use solves both:
- Security: the model returns only JSON; the application controls execution.
- Reliability: JSON Schema defines argument formats, reducing errors.
- Performance: parallel tool calls cut agent response time by 2–3 times.
Additionally, Tool Use reduces model hallucinations with factual data — the model relies on real execution results, not its internal knowledge cutoff.
Basic Tool Use Loop
import anthropic
import json
from typing import Any
client = anthropic.Anthropic()
# Define tools
TOOLS = [
{
"name": "search_database",
"description": "Search customers in CRM by parameters",
"input_schema": {
"type": "object",
"properties": {
"query": {"type": "string", "description": "Search query"},
"limit": {"type": "integer", "description": "Number of results", "default": 10},
"status": {
"type": "string",
"enum": ["active", "churned", "trial"],
"description": "Filter by status"
}
},
"required": ["query"]
}
},
{
"name": "send_email",
"description": "Send email to customer",
"input_schema": {
"type": "object",
"properties": {
"to": {"type": "string"},
"subject": {"type": "string"},
"body": {"type": "string"},
},
"required": ["to", "subject", "body"]
}
}
]
# Tool dispatcher
def execute_tool(tool_name: str, tool_input: dict) -> Any:
if tool_name == "search_database":
return search_crm(**tool_input)
elif tool_name == "send_email":
return send_email_via_smtp(**tool_input)
raise ValueError(f"Unknown tool: {tool_name}")
def run_agent(user_message: str) -> str:
"""Full agentic loop with tool use"""
messages = [{"role": "user", "content": user_message}]
while True:
response = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=4096,
tools=TOOLS,
messages=messages,
)
# No tool calls — return final answer
if response.stop_reason == "end_turn":
for block in response.content:
if hasattr(block, "text"):
return block.text
return ""
# Process tool_use blocks
tool_results = []
for block in response.content:
if block.type == "tool_use":
print(f"Calling tool: {block.name}({block.input})")
result = execute_tool(block.name, block.input)
tool_results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": json.dumps(result, ensure_ascii=False),
})
messages.append({"role": "assistant", "content": response.content})
messages.append({"role": "user", "content": tool_results})
Why Use Parallel Calls?
Executing multiple tools simultaneously speeds up the agent. When the model returns several tool_use blocks in one response, run them in parallel via asyncio. This reduces total time to the maximum among all tools. With three independent tools taking 0.5, 1.2, and 0.8 seconds, a synchronous approach takes 2.5 seconds, async takes 1.2 seconds — a 2–3x gain.
import asyncio
async def execute_tool_async(tool_name: str, tool_input: dict) -> tuple[str, Any]:
"""Asynchronous tool execution"""
result = await asyncio.to_thread(execute_tool, tool_name, tool_input)
return tool_name, result
async def run_agent_async(user_message: str) -> str:
messages = [{"role": "user", "content": user_message}]
while True:
response = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=4096,
tools=TOOLS,
messages=messages,
)
if response.stop_reason == "end_turn":
return next((b.text for b in response.content if hasattr(b, "text")), "")
# Run all tools in parallel
tool_use_blocks = [b for b in response.content if b.type == "tool_use"]
results = await asyncio.gather(*[
execute_tool_async(b.name, b.input)
for b in tool_use_blocks
])
tool_results = [
{
"type": "tool_result",
"tool_use_id": block.id,
"content": json.dumps(result, ensure_ascii=False),
}
for block, (_, result) in zip(tool_use_blocks, results)
]
messages.append({"role": "assistant", "content": response.content})
messages.append({"role": "user", "content": tool_results})
Synchronous vs. Async Loop Comparison
| Characteristic | Synchronous Loop | Async Loop |
|---|---|---|
| Tool execution | Sequential | Parallel |
| Latency for N tools | Sum of N times | Max time of one tool |
| Code complexity | Low | Medium (asyncio) |
| When to use | Tools depend on each other | Tools are independent |
How to Force a Tool Call?
# tool_choice="required" — Claude must call at least one tool
# tool_choice={"type": "tool", "name": "..."} — call a specific tool
response = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=1024,
tools=TOOLS,
tool_choice={"type": "tool", "name": "search_database"},
messages=[{"role": "user", "content": "Find customers with trial status"}],
)
Forcing a call is useful when you need to guarantee a critical action — for example, create a task or send a notification. The model can then return the call result without additional text.
How to Handle Tool Errors?
Errors are a natural part of production. Never end the dialogue on failure. Instead, pass the error description back to the model: it can choose another tool or ask for clarification. Step-by-step:
- Wrap the tool call in try-except.
- On success, add result to
tool_resultswithtype: "tool_result". - On exception, add a block with
is_error: Trueand the error text. - Send tool_results to the model and continue the loop.
# Return errors to the model — it adapts behavior
try:
result = execute_tool(block.name, block.input)
tool_results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": json.dumps(result),
})
except Exception as e:
tool_results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": f"Error: {str(e)}",
"is_error": True, # Model knows about the error and can adjust
})
Example full response with error:
{
"type": "tool_result",
"tool_use_id": "toolu_abc123",
"content": "Error: Connection timeout to database",
"is_error": true
}
The Claude model, upon receiving such a result, can suggest retrying or using another tool.
Practical Case: CRM Assistant
From our practice: a client — a large retail chain with a sales department of 50 managers. Preparing for a client meeting took 20–30 minutes: collecting deal history, recent contacts, open tasks. We deployed an assistant on Claude with tools:
-
get_customer_info— customer profile -
get_deal_history— deal history -
get_recent_activities— recent actions -
create_task— create a task -
get_calendar— free slots
Result: meeting preparation — 2 minutes via dialogue with the assistant. Time savings: 28 minutes per meeting. With an average manager salary of $30/hour, that's $14 saved per meeting, and with 10 meetings per day — $140 daily. Project payback — 3 months due to time savings from senior managers. Additionally, data entry errors dropped by 75% — tools work strictly by schemas.
What's Included in the Work
| Stage | Content | Estimated Time |
|---|---|---|
| Analysis | Define tool schemas based on business logic, agree on JSON Schema | 1 day |
| Development | Implement tool dispatcher with typing, set up async execution via asyncio | 2-3 days |
| Testing | Error handling and retries with feedback to model, unit tests | 1 day |
| Documentation | Deployment and support description, team training (up to 3 hours) | 1 day |
Timelines
- Basic tool use loop with 2-3 tools: 2–3 days
- Parallel calls + error handling: 1–2 days
- Production-ready with logging and retry: 1 week
Get a consultation on integration — we'll assess your project in 1 day and propose an optimal architecture. Our certified ML engineers have experience with OpenAI, Claude, Gemini, and open-source models. Write to us — let's discuss your scenario.







