TracingGuidesInstrumentation

Manual spans

Add spans for the steps that aren't captured on their own: your tools, retrieval, sub-steps, and model calls Trodo can't hook.

Model calls from supported frameworks become spans on their own. Add a span yourself for everything else you want to see in the trace: your tools, a retrieval step, a stage of the agent, or a model client Trodo can't hook. Spans you add nest under the current run, so they have to run inside a wrapAgent (or joinRun).

Wrap a function

Wrap a function once where it's defined, and every call becomes a span. Its arguments become the span's input, its return value the output, and an exception marks the span failed.

const lookupOrder = trodo.tool('lookup_order', async (orderId: string) => db.orders.find(orderId));
const searchDocs  = trodo.retrieval('search_docs', async (q: string) => kb.search(q, { k: 8 }));
const planSteps   = trodo.trace('plan_steps', async (goal: string) => planner.plan(goal));

const order = await lookupOrder('ord_123'); // one tool span per call
@trodo.tool("lookup_order")
def lookup_order(order_id):
    return db.orders.find(order_id)

@trodo.retrieval("search_docs")
def search_docs(q):
    return kb.search(q, k=8)

@trodo.trace("plan_steps")
def plan_steps(goal):
    return planner.plan(goal)

# Or wrap a function you didn't write:
run_query = trodo.tool("run_query", warehouse.run_query)

Wrap a block

When the step isn't one function, wrap the block and set fields on the span you're handed:

const results = await trodo.withSpan('search_docs', async (span) => {
  span.setInput({ query });
  const results = await kb.search(query);
  span.setOutput({ count: results.length, ids: results.map((r) => r.id) });
  return results;
}, { kind: 'retrieval' });
with trodo.span("search_docs", kind="retrieval") as span:
    span.set_input({"query": query})
    results = kb.search(query)
    span.set_output({"count": len(results), "ids": [r.id for r in results]})

kind is one of llm, tool, retrieval, agent or generic (the default). See Concepts.

NodePythonSets
setInput(value)set_input(value)The step's input
setOutput(value)set_output(value)The step's output
setTool(name)set_tool(name)The tool's name, shown on the span and in the Failures view
setLlm({...})set_llm(...)Model, provider, tokens, cost and temperature of a model call
setAttribute(key, value)set_attribute(key, value)A key/value on the span, searchable in Traces
setError({ message, type })set_error(message=, type=)Marks the span failed without throwing
setLevel(level)set_level(level)debug, default, warning or error

Model calls

Use the llm helper for a model call Trodo doesn't capture on its own: a raw provider SDK under Node ESM, a provider without an instrumentor, or your own client. It records the model, provider, input and output, and reads token usage from the response.

const answer = trodo.llm(
  'openai.chat',
  (messages) => client.chat.completions.create({ model: 'gpt-4o-mini', messages }),
  { model: 'gpt-4o-mini', provider: 'openai' },
);

const res = await answer(messages);
@trodo.llm("openai.chat", model="gpt-4o-mini", provider="openai")
def answer(messages):
    return client.chat.completions.create(model="gpt-4o-mini", messages=messages)

Usage is read from the response's usage or usageMetadata field, which covers OpenAI, Anthropic and Google responses, including cached and reasoning tokens. For another shape, return the provider's usage object yourself:

const generate = trodo.llm('cohere.chat', callCohere, {
  model: 'command-r', provider: 'cohere',
  extractUsageMap: (r) => r.meta?.tokens, // { input_tokens, output_tokens }
});
generate = trodo.llm(
    "cohere.chat", call_cohere, model="command-r", provider="cohere",
    extract_usage_map=lambda r: r["meta"]["tokens"],
)

Cost is worked out from the model and tokens. See Cost & model prices.

Record a call you already made

When the response is already in hand, for example from a plain fetch to a self-hosted model, record it with trackLlmCall. Call it inside a run; outside one it records nothing.

const resp = await fetch('http://ollama.internal/api/chat', {
  method: 'POST',
  body: JSON.stringify({ model: 'llama3.1:70b', messages }),
}).then((r) => r.json());

await trodo.trackLlmCall({
  model: 'llama3.1:70b',
  provider: 'ollama',
  inputTokens: resp.prompt_eval_count,
  outputTokens: resp.eval_count,
  prompt: messages,
  completion: resp.message,
});
resp = httpx.post(url, json=body).json()

trodo.track_llm_call(
    model="llama3.1:70b",
    provider="ollama",
    input_tokens=resp["prompt_eval_count"],
    output_tokens=resp["eval_count"],
    prompt=body["messages"],
    completion=resp["message"],
)

Pass cost to set the cost yourself, for a negotiated rate or a self-hosted model that costs nothing.

Give model input as messages

When you set an llm span's input yourself, pass the messages you sent to the model, not one joined string. Evals and search then read the system prompt, the user's words and the retrieved documents separately.

span.setInput([
  { role: 'system', content: systemPrompt },
  { role: 'context', content: retrievedDocs }, // retrieved documents
  { role: 'user', content: 'Where is my order?' },
]);

Roles are system, user, assistant, tool, and context for retrieved documents. Auto-captured model calls already arrive this way.

Errors

An exception inside a wrapped function or block marks the span failed, records its type and message, and is re-thrown. When your code catches the error and carries on, call setError so the span doesn't show as a success. See Status & errors.

The current span

trodo.currentSpanId() (Python: trodo.current_span_id()) returns the ID of the span you're in, for feedback on one span. currentRunId() returns the run's.

Raw OpenTelemetry

Any OpenTelemetry span started inside a run is recorded too. To start one yourself, get a tracer from Trodo:

const tracer = trodo.getTracer('my-module');
tracer.startActiveSpan('rerank', (span) => {
  span.setAttribute('gen_ai.request.model', 'rerank-v3');
  span.end();
});
tracer = trodo.get_tracer("my-module")
with tracer.start_as_current_span("rerank") as span:
    span.set_attribute("gen_ai.request.model", "rerank-v3")

On this page