Skip to main content
Python context managers and TypeScript callback scopes give you full control over trace and span lifecycle. Use them when you need to set metadata, token usage, or model information imperatively.
Prefer scoped instrumentation over decorators when inputs and outputs are not simple function arguments/returns, or when you must attach token counts and costs after the fact.

Python context managers

Starting a trace

Python
pandaprobe.start_trace() parameters: Returns a TraceContext with:
  • trace_id property — the auto-generated trace UUID (read-only)
  • span() method — creates child spans
  • set_input(data) — update trace input
  • set_output(data) — set trace output
  • set_metadata(dict) — merge metadata
  • set_status(status) — set TraceStatus (PENDING, RUNNING, COMPLETED, ERROR)

Creating spans

Python
t.span() parameters:

SpanContext methods

span_id property — read-only UUID of the span.
set_token_usage and set_cost accept additional keyword arguments so you can record provider-specific breakdowns without losing structured data in the UI.

Nested spans

Spans can be nested to form a tree. Parent-child relationships are tracked automatically via a context-var span stack:
Python
The llm-call and tool-call spans are automatically parented to the agent span.

Error handling

On exception within a span, the status is automatically set to ERROR and the error message is captured. The exception is re-raised.
Python
Because exceptions propagate, you can rely on normal try / except boundaries around your instrumentation while still recording span-level failures.

Sync and async support

Both TraceContext and SpanContext work as sync or async context managers.
Python

TypeScript callback scopes

JavaScript has no direct equivalent to Python’s with statement. PandaProbe provides withTrace() and withSpan() callback wrappers that preserve the active trace and span across asynchronous work with AsyncLocalStorage.
TypeScript

Callback options

Both functions also accept the callback as the second argument when no options are needed.

Context methods

TraceContext provides traceId, span(), setInput(), setOutput(), setMetadata(), and setStatus(). SpanContext provides spanId, setInput(), setOutput(), setModel(), setTokenUsage(), setModelParameters(), setCost(), setCompletionStartTime(), setError(), and setMetadata(). TypeScript uses objects for structured token and cost data:
TypeScript

Imperative lifecycle

Use startTrace() only when a callback scope is impractical. Always pair it with end() and pass any error so the final trace status is correct.
TypeScript
Exceptions thrown by withTrace() or withSpan() are recorded as errors and re-thrown. Nested callback scopes automatically preserve parent-child relationships.