Tracing (TypeScript)
Use observe, withSpan and withLlmSpan to turn your TypeScript code into spans.
Wrapper rules
Section titled “Wrapper rules”observe(fn, options?) wraps a function so that each call is one span.
- Input: no arguments record none; one argument records that value; more record the JSON array of them. Destructuring defaults are invisible to
observe: pass the fields you want recorded explicitly. - Output: the return value, or the resolved value of a returned promise.
undefinedrecords no output; returnnullto record a JSONnull. - Generators: a generator or async generator function (detected at wrap time) is traced as a generator: the span starts at the first
next(), the output is the yielded items, their concatenation when every item is a string, else the JSON array. An earlyreturn()ends the span with status ok, not an error. - Errors: a throw records one
exceptionevent and sets the status to error, then re-throws unchanged. Any other function shape, including one returning a generator, is traced as a call, and a returned generator object is passed through untouched, never consumed. captureInput/captureOutput(defaulttrue) turn each side off.- An invalid
kindthrows aTypeErrorat wrap time, before the function runs.
Manual spans and withLlmSpan
Section titled “Manual spans and withLlmSpan”withSpan(name, options?, fn) runs fn inside a span; the body’s return value is never recorded. Only span.setInput, span.setOutput and span.setMetadata write attributes.
withLlmSpan( "chat", { provider: "openai", model: "gpt-4o-mini", inputMessages: [{ role: "user", content: "hi" }], params: { temperature: 0.2 }, }, (span) => { span.setOutputMessages([{ role: "assistant", content: "hello" }]); span.setUsage({ inputTokens: 12, outputTokens: 3 }); },);withLlmSpan writes the GenAI attributes (gen_ai.*), cetra.span.kind = "llm" and, through the handle, the response model, usage, cost (setCost(totalUsd)) and time-to-first-token (recordFirstToken()). Messages may be the canonical { role, parts } format or the short { role, content: "<text>" } form, which becomes one text part.