Your AI agent understands the user's request, identifies a tool that should help, and then fails to complete the task. Maybe it selects the wrong function, generates invalid arguments, calls the same tool repeatedly, or receives a result that never makes it into the final answer.
These problems are easy to misdiagnose as model failures. In reality, tool calling is a multi-step application workflow. The model proposes an action, your application executes it, and the result must be returned to the model correctly.
To debug tool calling, inspect the entire cycle—not just the model's final response. This tutorial uses Python and the OpenAI Responses API to demonstrate common failure points and build a safer debugging workflow.
Table of Contents
Understand the Tool Calling Lifecycle
Identify the Four Common Failure Points
Build a Traceable Tool Execution Layer
Validate Arguments Before Execution
Return Tool Results Correctly
Prevent Loops and Unsafe Actions
Understand the Tool Calling Lifecycle
A tool call is not the same as a normal text response. The model returns a structured request that your application must recognize and execute.
A typical Responses API workflow has five stages:
Send the user request and available tool definitions to the model.
Inspect the response for function calls.
Validate the requested function and its arguments.
Execute the application function and collect its result.
Send the result back to the model so it can continue.

Each stage can fail independently. For example, the model may select the correct tool but provide an invalid order ID. The external service may return an error, or your application may send the result using the wrong call ID.
Debugging becomes easier when you record the stages separately.
Identify the Four Common Failure Points
1. The model chooses the wrong tool
Tool descriptions that are too vague or overlap with one another can make selection difficult. A function named search does not explain whether it searches products, documents, or customer records.
Use specific names and descriptions that explain when a tool should be used and what it returns.
2. The arguments are invalid
A model may return an empty string, an unexpected identifier format, or a value that your backend cannot process. Structured schemas help constrain arguments, but application-level validation is still necessary.
3. The function executes but fails
The model may request a valid operation while the external service is unavailable, the database query times out, or the user lacks permission to access the requested resource.
4. The tool result never reaches the model correctly
The application may forget to return the tool output, associate it with the wrong call ID, or stop processing before the model produces its final response.

Build a Traceable Tool Execution Layer
Start with one narrow tool. The following example looks up an order using an application function. The sample data is local so the tool workflow can be understood without depending on a real order service.
ORDERS = {
"ORD-1001": {
"status": "shipped",
"estimated_delivery": "2026-11-12"
},
"ORD-1002": {
"status": "processing",
"estimated_delivery": None
}
}
def get_order_status(order_id: str) -> dict:
order = ORDERS.get(order_id)
if order is None:
return {
"ok": False,
"error": "Order not found"
}
return {
"ok": True,
"order_id": order_id,
**order
}Define the function tool:
order_tool = {
"type": "function",
"name": "get_order_status",
"description": (
"Look up the status of an order using its exact order ID. "
"Use this when a user asks about an existing order."
),
"parameters": {
"type": "object",
"properties": {
"order_id": {
"type": "string",
"description": "An order ID such as ORD-1001"
}
},
"required": ["order_id"],
"additionalProperties": False
},
"strict": True
}The tool description makes its purpose clear, and the schema defines the required input. Keep the initial tool list small. Adding many overlapping tools can make selection harder and increase the amount of context the model must process.
Validate Arguments Before Execution
Even when a tool uses a strict schema, the application should verify the arguments before executing the operation. Never treat model-generated arguments as trusted application input.
Use a small dispatcher that only permits known functions:
import json
def execute_tool(name: str, raw_arguments: str) -> dict:
if name != "get_order_status":
return {
"ok": False,
"error": "Unsupported tool"
}
try:
arguments = json.loads(raw_arguments)
except json.JSONDecodeError:
return {
"ok": False,
"error": "Invalid JSON arguments"
}
if not isinstance(arguments, dict):
return {
"ok": False,
"error": "Arguments must be an object"
}
order_id = arguments.get("order_id")
if not isinstance(order_id, str):
return {
"ok": False,
"error": "Order ID must be a string"
}
order_id = order_id.strip()
if not order_id.startswith("ORD-"):
return {
"ok": False,
"error": "Invalid order ID format"
}
return get_order_status(order_id)This example checks the function name, JSON structure, input type, and basic identifier format. A real application must also verify that the authenticated user is allowed to access the requested order. A valid ID does not automatically mean the current user owns that order.
Return Tool Results Correctly
Now connect the dispatcher to the Responses API. The important detail is that each function output must reference the original function call through its call_id.
import os
from openai import OpenAI
client = OpenAI()
MODEL = os.environ["OPENAI_MODEL"]
def run_agent(user_message: str) -> str:
response = client.responses.create(
model=MODEL,
input=user_message,
tools=[order_tool]
)
max_rounds = 5
for _ in range(max_rounds):
if response.status != "completed":
raise RuntimeError(
f"Response status: {response.status}"
)
calls = [
item for item in response.output
if item.type == "function_call"
]
if not calls:
return response.output_text
outputs = []
for call in calls:
result = execute_tool(
call.name,
call.arguments
)
outputs.append({
"type": "function_call_output",
"call_id": call.call_id,
"output": json.dumps(result)
})
response = client.responses.create(
model=MODEL,
previous_response_id=response.id,
input=outputs,
tools=[order_tool]
)
raise RuntimeError("Maximum tool rounds exceeded")
The loop allows the model to request another tool after receiving the first result. The round limit prevents an application from continuing indefinitely if the model repeatedly requests tools.
Try asking: "Can you check the status of order ORD-1001?" The model should request the order tool, the application should return the order data, and the model should produce a readable answer.
If the result is missing, inspect the response output for a function call, confirm that the dispatcher ran, and verify that the returned output uses the matching call_id.
Debug Tool Failures With Structured Logs
Do not rely only on the final assistant message. Record enough information to reconstruct the tool lifecycle.
Useful diagnostic fields include:
Request or conversation ID
Tool name and call ID
Argument validation outcome
Tool execution duration
External service status
Tool result status
Number of tool rounds
For example, a log entry might record that get_order_status was called, argument validation succeeded, and the order service returned a not-found result. This is much more useful than a generic message saying the agent failed.
Do not log API keys, passwords, private customer information, or full tool payloads unless there is a clear, approved reason to retain them.
Prevent Loops and Unsafe Actions
Tool calling introduces application-level risks. A model can request a function, but the application must decide whether that operation is allowed.
Apply these controls:
Use an allowlist: Execute only explicitly registered tools.
Enforce user permissions: Check access using the authenticated user's identity, not an ID supplied by the model alone.
Set timeouts: Prevent a slow external service from blocking the entire agent workflow.
Limit tool rounds: Stop repeated calls and surface a controlled failure.
Handle retries carefully: Retry temporary failures only when the operation is safe to repeat.
Require approval for sensitive actions: Sending money, deleting data, and issuing refunds should have explicit authorization and confirmation.
Also remember that external tool results are untrusted data. A document or API response may contain instructions that should not override the application's trusted instructions or permission checks.
Use a Failure-First Debugging Checklist
When a tool call fails, work through the workflow in order:
Did the model return a function call?
Was the intended tool selected?
Are the arguments valid and complete?
Did the dispatcher recognize the function?
Did the application execute it successfully?
Was the result returned with the correct call ID?
Did the model receive the result and produce a final answer?
This checklist separates model selection problems from application bugs and external service failures. It also makes logs and test cases more useful because each failure can be assigned to a specific stage.
Make Tool Calling Predictable
A reliable agent is not one that can call the largest number of tools. It is one that uses a small, clearly defined set of capabilities and handles failures without losing control of the application.
Keep tool definitions specific, validate every argument, check permissions outside the model, and trace every execution from the original request to the final answer. Once these boundaries are clear, tool-calling failures become much easier to reproduce and fix.
Build it. Break it. Understand it. Fix it.
