Documentation
Agent Example
Trace a multi-tool agent with retries.
Overview
This example demonstrates a multi-tool agent where each tool is instrumented with @trace_tool and the orchestrator is decorated with @trace. The trace captures every tool call including retries, durations, inputs, outputs, and exceptions — all as steps within a single trace.
Code
agent_example.pyCopy
python
import os
import random
import sys
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
from openai import OpenAI
from tracellm import trace, trace_tool
from tracellm.integrations.openai import wrap_openai
client = OpenAI()
client = wrap_openai(client)
@trace_tool(name="search_web", max_retries=2)
def search_web(query: str) -> str:
"""Simulated web search that fails 30% of the time."""
if random.random() < 0.3:
raise ConnectionError("Search API temporarily unavailable")
return f"Top result for '{query}': LLM agents are transforming enterprise workflows."
@trace_tool(name="calculate", max_retries=1)
def calculate(expression: str) -> str:
"""Evaluate a math expression safely."""
allowed = {"+", "-", "*", "/", "(", ")", " ", ".", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}
if not all(c in allowed for c in expression):
return "Error: Invalid characters in expression"
try:
result = eval(expression, {"__builtins__": {}}, {})
return f"Result: {result}"
except Exception as e:
return f"Calculation error: {e}"
@trace_tool(name="summarize")
def summarize(text: str, max_words: int = 30) -> str:
"""Truncate text to a summary."""
words = text.split()
if len(words) <= max_words:
return text
return " ".join(words[:max_words]) + "..."
@trace(project="agent-demo", environment="development")
def run_agent(task: str) -> dict:
search_result = search_web(task)
calc_result = calculate("145 * 32")
summary = summarize(f"{search_result}\nToken count: {calc_result}")
return {"task": task, "summary": summary, "calc": calc_result}
if __name__ == "__main__":
result = run_agent("impact of AI agents on enterprise software")
print(f"\nAgent Response:")
for key, value in result.items():
print(f" {key}: {value}")Info
No API key needed for this example — tools are simulated. The
@trace_tool decorator records each call as a step in the parent trace via contextvars.ContextVar.Expected Output
Console outputCopy
text
╭── TraceLLM Trace ───────────────────────────── SUCCESS ──╮
│ │
│ Trace ID tr_c5d8e2f1 │
│ Prompt impact of AI agents on enterprise software │
│ Model unknown │
│ Project agent-demo │
│ Environment development │
│ Latency 284.15 ms │
│ Token Count 42 │
│ Retries 0 │
│ Steps 3 │
│ Status SUCCESS │
│ │
╰──────────────────────────────────────────────────────────────╯
# Tool Duration Status Detail
1 search_web 120ms OK
2 calculate 35ms OK
3 summarize 12ms OK
Agent Response:
task: impact of AI agents on enterprise software
summary: Top result for 'impact of AI agents on enterprise
software': LLM agents are transforming enterprise...
calc: Result: 4640
If search_web fails (30% chance), the trace shows retry attempts:
# Tool Duration Status Detail
1 search_web 120ms RETRY
2 search_web 115ms RETRY
3 search_web 130ms OK
4 calculate 35ms OK
5 summarize 12ms OKDashboard Result
The trace appears in the dashboard with all 3 tool steps visible:
Dashboard UICopy
text
TraceLLM Dashboard > Traces
Status Trace ID Prompt Model Latency Tokens Time
─────── ─────────────── ─────────────────────────────────────────────────── ─────── ───────── ──────── ─────────────────────
● Success tr_c5d8e2f1 impact of AI agents on enterprise software unknown 284 ms 42 2026-05-31 14:25:12
> Detail view shows all 3 steps in the timeline:
┌─ Step Timeline ────────────────────────────────────────────────────────────┐
│ │
│ search_web ───────────────────────────── 120ms OK │
│ calculate ────────── 35ms OK │
│ summarize ──── 12ms OK │
│ │
└─────────────────────────────────────────────────────────────────────────────┘
> Clicking a step opens the TraceInspector panel showing input/output:
┌─ TraceInspector ───────────────────────────────────────────────┐
│ Step: search_web │
│ Input: {'query': 'impact of AI agents on enterprise software'}│
│ Output: {'result': "Top result for 'impact...'} │
│ Duration: 120.45 ms │
│ Success: True │
└─────────────────────────────────────────────────────────────────┘Replay Result
Replay animates each tool call in sequence with live step details:
terminalCopy
bash
tracellm replay tr_c5d8e2f1 --show-response
Replay outputCopy
text
╭────────────────── Replaying execution timeline... ──────────────────╮
│ │
│ ╭─ Replay ───────────────────────────────────────────────────────╮ │
│ │ │ │
│ │ trace_id tr_c5d8e2f1 │ │
│ │ status SUCCESS │ │
│ │ latency 284.15 ms │ │
│ │ retries 0 │ │
│ │ steps 3 │ │
│ │ │ │
│ ╰─────────────────────────────────────────────────────────────────╯ │
│ │
│ ╭─ Step 1/3 ───────────────────────────────────────╮ │
│ │ step 1/3 │ │
│ │ tool search_web │ │
│ │ duration 120 ms │ │
│ │ status OK │ │
│ │ input {'query': 'impact of AI agents...'} │ │
│ │ output {'result': "Top result for 'impact... │ │
│ ╰────────────────────────────────────────────────────╯ │
│ │
│ ╭─ Step 2/3 ───────────────────────────────────────╮ │
│ │ step 2/3 │ │
│ │ tool calculate │ │
│ │ duration 35 ms │ │
│ │ status OK │ │
│ ╰────────────────────────────────────────────────────╯ │
│ │
│ ╭─ Step 3/3 ───────────────────────────────────────╮ │
│ │ step 3/3 │ │
│ │ tool summarize │ │
│ │ duration 12 ms │ │
│ │ status OK │ │
│ ╰────────────────────────────────────────────────────╯ │
╰──────────────────────────────────────────────────────────────────────╯
╭── TraceLLM Trace ───────────────────────────── SUCCESS ──╮
│ │
│ Trace ID tr_c5d8e2f1 │
│ Prompt impact of AI agents on enterprise... │
│ ... │
╰──────────────────────────────────────────────────────────╯
Replay complete