Manual Tracing

Auto-instrumentation sees calls into libraries. It cannot see your logic — your agent loop, your retrieval step, your business rules. Manual tracing fills those gaps and turns a flat list of LLM calls into a readable execution tree.

Manual tracing span tree


Two APIs

API Use for
@trail.trace(role=...) Whole functions — the common case
trail.start_trace(name, role=...) Blocks of code inside a function, or when you need to set attributes as you go

@trail.trace — the decorator

import trail

@trail.trace(role="tool")
def search_web(query: str) -> str:
    return requests.get(f"https://api.example.com/search?q={query}").text

Captured automatically: span name (the function's name), duration, arguments, return value, success/failure, and the exception with traceback if it raises.

Works bare too:

@trail.trace                # role defaults to "function"
def preprocess(text): ...

The role is a classification, not a name. The span keeps the function's name, so five tools show up as five distinct spans rather than five spans called "tool". Name your functions well — search_knowledge_base, not run.

Roles

role= Span kind Emits gen_ai.operation.name Feeds
"agent" agent agent Agent Analytics — an agent run
"agent step" / anything with step or task agent execute_task Agent Analytics — a step
"tool" tool execute_tool Agent Analytics — a tool call
"llm" llm — LLM span rendering
"memory" memory — Trace tree
"api" / "external" external — Trace tree
unset function — Trace tree

Roles are matched by substring, case-insensitively — "agent reasoning step" classifies as an agent step because it contains step.

Both @trail.trace and start_trace also accept an optional goal= string — what this agent run is trying to accomplish. It only applies when role classifies as "agent" (sets gen_ai.agent.goal); on any other role it's silently ignored.

Agent context propagation

A span with role="agent" becomes the current agent for everything nested inside it. Steps and tools inherit gen_ai.agent.name automatically:

@trail.trace(role="agent")
def research_agent(topic):        # ← becomes the current agent
    plan = plan_research(topic)   #   inherits gen_ai.agent.name = "research_agent"
    return search_web(plan)       #   inherits it too

@trail.trace(role="agent step")
def plan_research(topic): ...

@trail.trace(role="tool")
def search_web(query): ...

This is what lets Agent Analytics attribute every tool call to the agent that made it. Propagation uses contextvars, so it's async-safe and correct across concurrent agent runs.


trail.start_trace — the context manager

For a block rather than a function, or when you want to enrich the span as you go:

import trail

with trail.start_trace("retrieve_and_rank", role="agent step") as span:
    docs = vector_db.query(embedding, top_k=20)
    ranked = rerank(docs)

    span.set_result(f"{len(ranked)} documents")
    span.set_metadata({
        "candidates": len(docs),
        "returned": len(ranked),
        "index": "product-docs-v3",
    })

Span methods

Method Purpose
set_result(value) Record the span's output
set_metadata(dict) Add custom attributes. Non-primitive values are stringified
set_llm_usage(model=, prompt_tokens=, completion_tokens=) Record model and token usage; total is derived
set_agent_step(index) Record which step in a sequence this is

Metadata values are coerced to str unless they're int, float, bool, or str — safe to pass anything, but keep values small.


Instrumenting a custom LLM client

For a model provider TrailAI doesn't auto-instrument:

with trail.start_trace("custom_llm_call", role="llm") as span:
    result = my_client.generate(prompt, model="internal-model-v2")

    span.set_result(result.text)
    span.set_llm_usage(
        model="internal-model-v2",
        prompt_tokens=result.usage.input_tokens,
        completion_tokens=result.usage.output_tokens,
    )

For cost to be computed, add the model to a custom pricing table — Configuration.


A complete agent

import trail
from openai import OpenAI

client = OpenAI()

@trail.trace(role="tool")
def search_docs(query: str) -> str:
    return "…retrieved passages…"

@trail.trace(role="tool")
def lookup_order(order_id: str) -> dict:
    return {"id": order_id, "status": "shipped"}

@trail.trace(role="agent step")
def decide_next_action(state: dict) -> str:
    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[{"role": "user", "content": f"Given {state}, what next?"}],
    )
    return response.choices[0].message.content

@trail.trace(role="agent")
def support_agent(question: str) -> str:
    state = {"question": question, "steps": []}

    for i in range(5):
        with trail.start_trace(f"iteration_{i}", role="agent step") as span:
            action = decide_next_action(state)
            span.set_agent_step(i)
            span.set_metadata({"action": action})

            if "search" in action:
                state["steps"].append(search_docs(question))
            elif "order" in action:
                state["steps"].append(lookup_order("12345"))
            else:
                span.set_result("done")
                break

    return synthesize(state)

@trail.trace(role="agent step")
def synthesize(state: dict) -> str:
    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[{"role": "user", "content": f"Answer from: {state['steps']}"}],
    )
    return response.choices[0].message.content

Which produces:

support_agent                       (agent)      2.4 s
├── iteration_0                     (agent step) 0.8 s
│   ├── decide_next_action          (agent step) 0.6 s
│   │   └── openai.chat.completion  (llm)        0.5 s   ← automatic
│   └── search_docs                 (tool)       0.2 s
├── iteration_1                     (agent step) 0.9 s
│   ├── decide_next_action          (agent step) 0.6 s
│   │   └── openai.chat.completion  (llm)        0.5 s
│   └── lookup_order                (tool)       0.3 s
└── synthesize                      (agent step) 0.7 s
    └── openai.chat.completion      (llm)        0.6 s

Every span in that tree is attributed to support_agent, so Agent Analytics reports its run count, step count, tool usage, and cost correctly.


What to trace, and what not to

Trace:

  • Agent runs and their reasoning steps.
  • Tool calls — especially anything crossing the network.
  • Retrieval and reranking.
  • Prompt construction, when it's non-trivial.
  • External API calls your AI logic depends on.
  • Any function you'd want a duration for when debugging latency.

Don't trace:

  • Tight loops or functions called thousands of times per request. You'll drown the trace tree and pay for the volume.
  • Trivial getters and formatters.
  • Anything already auto-instrumented — you'd get duplicate spans.

The heuristic: if it could plausibly take more than ~10 ms, or if you'd want to know it happened while reading a trace, trace it. Otherwise leave it.


Errors

Exceptions are recorded automatically and re-raised — your control flow is unaffected:

@trail.trace(role="tool")
def flaky_api_call():
    raise ConnectionError("upstream unavailable")   # recorded, then re-raised

The span is marked failed, the exception and traceback are attached, and it appears in Exceptions.

For start_trace, exceptions inside the block are recorded the same way.


Async

The decorator wraps synchronous callables. For async work, use start_trace inside the coroutine:

async def fetch_all(queries):
    with trail.start_trace("fetch_all", role="agent step") as span:
        results = await asyncio.gather(*[fetch(q) for q in queries])
        span.set_metadata({"count": len(results)})
        return results

Agent context propagation is contextvars-based and therefore async-safe — concurrent agent runs don't cross-contaminate each other's attribution.


Naming spans well

Span names are how you read a trace at a glance. Since the span takes the function's name:

Poor Better
run support_agent
process rerank_documents
handler classify_intent
tool1, tool2 search_web, lookup_order

For start_trace, name the operation, not the code: "retrieve_and_rank", not "step 2".


Related