Learn AI · Foundations
Function Calling Explained
Function calling is how LLMs trigger your code. Here's how it actually works under the hood, and how to design tools that the model uses correctly.
Key takeaways
- 1Function calling is just structured output with a contract.
- 2The model doesn't run code — it suggests what to run, you execute.
- 3Tool design (clear names, narrow scope, typed args) determines success more than model choice.
- 4Always validate tool arguments before execution. The model can return malformed args.
- 5All major providers support it: OpenAI, Anthropic (tool use), Gemini, open-weights via templates.
The protocol
Function calling is a contract between your code and the model:
- You provide a list of functions, each with a name, description, and JSON-schema parameter spec.
- You send the user's message + the function specs to the model.
- The model either responds with text or with a structured "call function X with args Y."
- You execute the function (or refuse to).
- You feed the result back to the model as a new message.
- The model produces a final answer using the result.
That loop is the entire pattern. Agents are this loop run iteratively.
A function definition (Anthropic-style)
{
"name": "search_docs",
"description": "Search internal documentation. Returns up to 10 most relevant chunks.",
"input_schema": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "Natural-language search query"
},
"max_results": {
"type": "integer",
"description": "Number of results, 1-10",
"default": 5
}
},
"required": ["query"]
}
}
The model sees this and learns: there's a tool called search_docs; it takes a query and optionally a max_results; it returns documentation chunks.
Tool design — what actually matters
The single biggest determinant of agent reliability is tool quality. Good tools:
- Have one clear job —
send_emailnotdo_communication. - Are typed — string, integer, enum, not "any."
- Have helpful descriptions — describe behavior + edge cases + return format.
- Return useful errors — "file not found at /path/x" beats a 500.
- Are idempotent when possible — safer for retries.
Bad tools (vague names, overlapping scopes, wide-open parameters) cause the model to misuse them, get confused, or loop.
Always validate
The model can return malformed arguments. Don't trust:
def execute_tool(call):
args = json.loads(call.arguments)
# Validate against schema BEFORE executing
if not Schema(...).is_valid(args):
return {"error": "Invalid arguments"}
return real_execute(args)
Schema-on-receive is your last line of defense.
The tool-use loop in pseudocode
messages = [user_message]
while True:
response = model.complete(messages, tools=tools)
if response.stop_reason == "end_turn":
return response.text
if response.stop_reason == "tool_use":
for call in response.tool_calls:
result = execute_tool(call)
messages.append({"role": "tool", "tool_call_id": call.id, "content": result})
That's an agent. Add a max-iteration cap and logging and you have a production loop.
Cross-provider differences (briefly)
- OpenAI:
tools=[...], response hastool_callslist. - Anthropic:
tools=[...], response hascontentblocks of typetool_use. - Gemini: similar shape; Google calls them "function declarations."
- Open-weights: most modern templates (Llama 3.x, Qwen, DeepSeek) support tool use; the format is provider-specific.
The shape varies; the concept is identical.
When NOT to use it
- For simple deterministic transforms (use code).
- For pure factual recall (use RAG).
- When latency is critical and the tool round-trip dominates (consider doing the work locally).
Function calling is the bridge between LLMs and the world. Get the tools right and you have an agent. Get them wrong and you have a chatbot that wanders.
Common misconceptions
The wrong-but-common takes worth correcting.
Myth
Function calling means the model executes code.
Reality
The model returns a structured tool call (function name + arguments). Your code executes it. Always.
Myth
More tools = smarter agent.
Reality
Past ~5–10 tools, the model gets confused. Better to compose smaller agents with focused tool sets.
Myth
Tool descriptions are just for humans.
Reality
The model reads them. They're prompts. Treat them as carefully as any system message.
Real-world use cases
Database queries
Let the model construct SQL or API queries from natural language.
External API integration
Stripe charges, Slack messages, calendar events — anywhere the model needs side effects.
Multi-step agents
Search → fetch → summarize → act. Each step is a function call.
Open
Structured extraction
Use tool definitions as a schema for extracting entities, dates, sentiments from text.
Frequently asked questions
Watch
Hand-picked videos from official + trusted channels. Opens in a new tab.
Related on AIKnowHub
Concept
AI Agents Explained
Agents are LLMs that can take actions in a loop. Here's what that actually means, where they shine, and where they fall over.
Concept
MCP Explained
The Model Context Protocol is the USB-C of AI tooling. Here's what it is, why it matters, and how to think about it.
Concept
Structured Outputs Explained
Structured outputs make models return valid JSON every time — no more parsing failures, no more 'almost JSON.' Here's how they work and when to use them.
Learning Path
AI Agent Builder Roadmap
The path from 'I built a chatbot' to 'I built an agent that runs unsupervised.' For builders, not lurkers.
Tool Guide
Dify Guide
The definitive guide to Dify for low-code AI apps — RAG chatbots, agent workflows, MCP import, self-host vs cloud, and when to pick it over Flowise or n8n.
Tool Guide
n8n Guide
The definitive guide to n8n for AI workflows — self-host vs cloud, agent nodes, LLM chaining, code escape hatches, and when to pick it over Zapier or Make.