Sub topic 11
Tracing tool calls
This chapter assumes you can create spans with start_as_current_span, that you have configured a tracer provider, and that you know the GenAI attribute names from the earlier chapters. It covers how to represent each tool an agent runs as its own span.
Why tool calls need their own spans
An agent loop alternates between asking the model what to do and running what it asked for. The model call span shows that the model requested search_orders. It does not show whether the function ran, how long it took, or what it returned. Those facts belong to a separate span.
Tool spans answer the questions you ask when an agent misbehaves:
- Which tool was slow?
- Which tool failed, and did the agent recover?
- How many times was the same tool called in one run?
- Did the model request a tool that does not exist?
What the conventions specify
The GenAI semantic conventions define a span for tool execution. The span is named execute_tool {tool name} and carries these attributes:
| Attribute | Meaning | Example |
|---|---|---|
| `gen_ai.operation.name` | Operation type, always `execute_tool` here | `execute_tool` |
| `gen_ai.tool.name` | Name of the tool | `search_orders` |
| `gen_ai.tool.call.id` | The ID the model assigned to this call | `call_abc123` |
| `gen_ai.tool.type` | Where the tool runs: `function`, `extension` or `datastore` | `function` |
| `gen_ai.tool.description` | Human-readable description of the tool | `Look up orders` |
| `error.type` | Error class, set only on failure | `TimeoutError` |
The call ID links the tool span to the model response that requested it. When a model returns several tool calls in one turn, the ID tells you which result belongs to which request.
The GenAI conventions are still marked as in development. Attribute names can change between releases, so check the version you pin. Tool arguments and results can be recorded too. Treat them as content that is off by default, for the reasons covered in the chapter on capturing prompts and responses safely.
Span kind needs a decision. A function running inside your process is INTERNAL, which is the default. A tool that calls a remote service is better modeled as CLIENT, or as an INTERNAL tool span with an HTTP client span beneath it. The second option gives you both the agent's view of the tool and the network view.
Where tool spans sit in the tree
The tool span's parent is the agent span, not the model call. The model call finishes before the tool runs. Tools are siblings of the model calls, in the order they happened.
Because start_as_current_span makes the agent span the current parent, any tool span started inside the agent's with block attaches to it automatically.
A tool dispatcher you can run
The script below wraps tool dispatch in one function. It looks up the tool inside the span, so a call to an unknown tool still produces an error span. It also catches tool failures and returns them to the agent as text, which is how most agents let the model react to a failed tool.
import json
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor
from opentelemetry.trace import Status, StatusCode
provider = TracerProvider(resource=Resource.create({"service.name": "support-agent"}))
provider.add_span_processor(SimpleSpanProcessor(ConsoleSpanExporter()))
trace.set_tracer_provider(provider)
tracer = trace.get_tracer("support_agent")
def search_orders(customer_id):
return [{"id": "A-1001", "customer": customer_id}]
def refund_order(order_id):
raise TimeoutError("payments service did not answer in 5s")
TOOLS = {"search_orders": search_orders, "refund_order": refund_order}
def run_tool(tool_call):
name = tool_call["name"]
with tracer.start_as_current_span(
f"execute_tool {name}",
record_exception=False,
set_status_on_exception=False,
) as span:
span.set_attribute("gen_ai.operation.name", "execute_tool")
span.set_attribute("gen_ai.tool.name", name)
span.set_attribute("gen_ai.tool.call.id", tool_call["id"])
span.set_attribute("gen_ai.tool.type", "function")
try:
result = TOOLS[name](**tool_call["arguments"])
return json.dumps(result)
except Exception as exc:
span.record_exception(exc)
span.set_attribute("error.type", type(exc).__qualname__)
span.set_status(Status(StatusCode.ERROR, str(exc)))
return f"tool error: {exc!r}"
def run_agent():
with tracer.start_as_current_span("invoke_agent support-agent") as span:
span.set_attribute("gen_ai.operation.name", "invoke_agent")
span.set_attribute("gen_ai.agent.name", "support-agent")
calls = [
{"id": "call_1", "name": "search_orders", "arguments": {"customer_id": "c-42"}},
{"id": "call_2", "name": "refund_order", "arguments": {"order_id": "A-1001"}},
{"id": "call_3", "name": "delete_account", "arguments": {}},
]
for call in calls:
print(run_tool(call))
run_agent()Running it prints three execute_tool spans under one invoke_agent span. The second has status ERROR with error.type set to TimeoutError. The third has error.type set to KeyError, because delete_account is not registered.
The record_exception=False and set_status_on_exception=False arguments matter. By default, start_as_current_span records an exception and sets error status when one escapes the with block. Here the code catches the exception inside the block, so the defaults would not run. Disabling them also guards against a duplicate exception event if you later re-raise.
Errors, retries and timeouts
Keep these rules when a tool misbehaves:
- Put the error on the span that failed. Record it on the tool span, not on its parent.
- Use a short, stable
error.typesuch asTimeoutErrororHTTPStatusError. Do not put the message there, because high-cardinality values make grouping and alerting hard. - Create one span per retry attempt. Add an attribute such as
retry.attempt(a custom name, not part of the conventions) so you can see three tries instead of one slow call. - Record timeouts as errors. A timed-out tool whose span ends as
OKhides the real problem.
Parallel tool calls
Models often request several tools in one turn. If you run them concurrently, each should still be a child of the agent span. Threads do not inherit the current OpenTelemetry context automatically. A ThreadPoolExecutor task starts with an empty context, so its tool span becomes a new root trace. Fix this by running each task through contextvars.copy_context().run(...). With asyncio, tasks copy the context when they are created, so spans attach correctly.
Reading tool spans in a trace
In a trace viewer, check these patterns:
- Repeated sibling spans with the same tool name and arguments. The agent is probably stuck in a loop.
- A tool span that dominates the run's duration. Optimize the tool, not the prompt.
- An error span followed by a successful call to a different tool. The agent recovered. Check whether the tool description misled the model.
- A tool span with an unknown
gen_ai.tool.name. The model invented a tool, so your tool schema or prompt needs work.
Exercise
A model returns two tool calls in one turn, and your code runs them in a thread pool. In the trace, both execute_tool spans appear as separate root traces instead of children of invoke_agent. What is the cause, and how do you fix it?
Show answer
Worker threads do not inherit the OpenTelemetry context, so the agent span is not the current parent inside them and each tool span starts a new trace. Fix it by running each task with contextvars.copy_context().run(...), or by capturing the context with opentelemetry.context.get_current() and attaching it inside the worker.
Exercise
Which attributes would you set on the span for a tool call that raised TimeoutError, and which span should carry the error status if the agent then recovered by calling another tool?
Show answer
On the tool span set gen_ai.operation.name=execute_tool, gen_ai.tool.name, gen_ai.tool.call.id, error.type=TimeoutError, record the exception and set status ERROR. The invoke_agent span should not be marked as an error, because the run as a whole succeeded.