Search Tutorials
--Ads--Function Calling and Tool Use with LLMs
Let an LLM call your Python functions: tool schemas, the request-execute-respond loop, and safety.
Function calling (also called tool use) lets a language model ask your application to run a function, such as searching documents, looking up an order or converting a currency, and then use the result in its answer. It is the foundation of agentic RAG and of any assistant that needs live data. This lesson explains the request-execute-respond loop and implements it with both the Claude API and the OpenAI Responses API.
What you will learn
- How function calling works: tool definitions, tool calls and tool results
- How to write good tool definitions with JSON Schema
- How to run the tool loop with Claude and with OpenAI
- How to keep tool use safe
Prerequisites
- Python setup (Claude key) and optionally OpenAI API setup
How it works
- You send the user's message together with a list of tool definitions: a name, a description and a JSON Schema for the arguments.
- If the model decides a tool would help, it replies with a tool call: the tool name and arguments, instead of (or before) a final answer.
- Your code runs the function with those arguments. The model never executes anything itself.
- You send the tool result back, and the model either calls another tool or writes the final answer.
Defining a tool
The description is what the model reads to decide when to call the tool, so write it like documentation for a colleague: what it does, when to use it, and what each argument means.
ORDER_TOOL_SCHEMA = {
"type": "object",
"properties": {
"order_id": {"type": "string", "description": "Order number, for example 'ORD-1042'"},
},
"required": ["order_id"],
"additionalProperties": False,
}
ORDERS = {"ORD-1042": {"status": "shipped", "carrier": "BlueDart", "eta": "2026-11-29"}}
def get_order_status(order_id: str) -> dict:
return ORDERS.get(order_id.upper(), {"error": f"No order found with id {order_id}"})
Function calling with Claude
With the Claude API, tool calls arrive as tool_use content blocks, and results go back as tool_result blocks in a user message with the matching tool_use_id.
import json
import anthropic
client = anthropic.Anthropic()
TOOLS = [{
"name": "get_order_status",
"description": "Look up the shipping status of a customer order by its order number. "
"Use whenever the user asks where their order is or when it will arrive.",
"input_schema": ORDER_TOOL_SCHEMA,
}]
FUNCTIONS = {"get_order_status": get_order_status}
def run(user_message: str) -> str:
messages = [{"role": "user", "content": user_message}]
for _ in range(5): # cap the number of tool rounds
response = client.messages.create(
model="claude-opus-5-5", max_tokens=2000, output_config={"effort": "low"},
tools=TOOLS, messages=messages)
messages.append({"role": "assistant", "content": response.content})
if response.stop_reason != "tool_use":
return "".join(b.text for b in response.content if b.type == "text")
results = []
for block in response.content:
if block.type == "tool_use":
output = FUNCTIONS[block.name](**block.input)
results.append({"type": "tool_result", "tool_use_id": block.id,
"content": json.dumps(output)})
messages.append({"role": "user", "content": results}) # all results in ONE message
return "Stopped: too many tool calls."
print(run("Where is my order ORD-1042?"))
Your order ORD-1042 has shipped with BlueDart and is expected to arrive on 29 November 2026.
The Anthropic Python SDK also offers a tool runner that runs this loop for you from decorated Python functions; it is used in Agentic RAG with Tool Use.
Function calling with the OpenAI Responses API
With OpenAI's Responses API, tools are defined with "type": "function"; tool calls appear in response.output as items of type function_call whose arguments is a JSON string; results are sent back as function_call_output items with the same call_id.
import json
import os
from openai import OpenAI
client = OpenAI()
MODEL = os.getenv("OPENAI_MODEL", "gpt-6.2-sol")
TOOLS = [{
"type": "function",
"name": "get_order_status",
"description": "Look up the shipping status of a customer order by its order number.",
"parameters": ORDER_TOOL_SCHEMA,
"strict": True,
}]
def run_openai(user_message: str) -> str:
input_list = [{"role": "user", "content": user_message}]
for _ in range(5):
response = client.responses.create(model=MODEL, tools=TOOLS, input=input_list)
input_list += response.output # keep the model's turn, including calls
calls = [item for item in response.output if item.type == "function_call"]
if not calls:
return response.output_text
for call in calls:
output = FUNCTIONS[call.name](**json.loads(call.arguments))
input_list.append({"type": "function_call_output", "call_id": call.call_id,
"output": json.dumps(output)})
return "Stopped: too many tool calls."
print(run_openai("Where is my order ORD-1042?"))
The two APIs differ in shape but follow exactly the same loop.
Function calling in RAG
Retrieval itself can be a tool: search_documents(query). The model then decides whether to search, what to search for, and whether to search again. That is agentic RAG. Other useful tools next to retrieval: database lookups (Text-to-SQL), live data such as order status or leave balances, and calculators for exact arithmetic.
Safety rules for tools
- Validate arguments in your function, even with strict schemas: check IDs, ranges and permissions.
- Enforce permissions in code: pass the authenticated user's identity to the function yourself; never let the model choose whose data to read.
- Read-only by default: require human confirmation for actions that change things (refunds, emails, deletions).
- Return errors as results (as
get_order_statusdoes) so the model can recover, instead of crashing the loop. - Cap the loop and log every call.
Common errors and troubleshooting
- The model never calls the tool: improve the description, or mention the tool in the system prompt ("use get_order_status for order questions").
- API error about missing tool results: every tool call must get a matching result (
tool_use_id/call_id) in the next request. - Invalid arguments: use strict schemas, and parse arguments with
json.loadsrather than string matching.
Key takeaways
- The model requests a function; your code runs it and returns the result; the loop repeats until a final answer.
- Good descriptions and strict JSON Schemas drive correct tool use.
- Claude uses
tool_use/tool_resultblocks; OpenAI usesfunction_call/function_call_outputitems. - Keep permissions and confirmations in your code, and cap the loop.
Frequently asked questions
Can the model call several tools at once?
Yes. Models can request several calls in one turn; run them (in parallel if independent) and return all results together.
Is function calling the same as an agent?
Function calling is the mechanism; an agent is a loop that uses it to decide its own steps (AI Agent Fundamentals).
Practice exercises
- Add a
cancel_ordertool that asks the user for confirmation before doing anything. - Add a
search_policies(query)tool backed by your retriever, and ask a question that needs both tools.