Documentation

@trace decorator

Mark functions for automatic tracing.

Overview

The @trace decorator is the primary instrumentation API in TraceLLM. Wrapping any function with @trace automatically captures the full execution context — prompt, response, latency, token usage, errors, and nested tool calls — and persists it as a trace document in MongoDB.

Syntax

@trace decoratorCopy
python
from tracellm import trace

@trace(
    prompt="optional prompt or defaults to function name",
    model_name="gpt-4.1-mini",
    project="my-project",
    environment="production",
    api_key="tlm_sk_...",
)
def my_function():
    ...

Parameters

ParameterTypeDefaultDescription
promptstr"" (falls back to func.__name__)The prompt or operation label recorded on the trace
model_namestr"unknown"Model identifier stored on the trace for filtering and analytics
projectstr or NoneNoneProject name for grouping traces in the dashboard
environmentstr"development"Environment label: development, staging, or production
api_keystr or NoneNoneTraceLLM API key for project context resolution

Note

When api_keyis provided, the project ID, project name, and environment are resolved from the database record. Otherwise the decorator's parameter values are used directly.

Trace Lifecycle

Every decorated function triggers the same six-stage lifecycle:

1

Start Time Captured

datetime.now(timezone.utc) records the human-readable timestamp. time.perf_counter() starts the high-precision latency timer.
2

Project Context Resolved

If an API key was provided, the project ID, name, and environment are looked up from MongoDB. Otherwise the decorator arguments or defaults are used.
3

Context Variable Set

A contextvars.ContextVar is initialized with empty step and retry counters. Any @trace_tool or SDK integration calls that execute inside this function will append their steps to this context.
4

Function Executes

The wrapped function runs. If it raises, the exception is captured and re-raised after finalization.
5

Trace Finalized

The latency delta is computed. A trace payload is built with all metadata, steps, token estimates, and status. The payload is persisted to MongoDB and broadcast via WebSocket. A summary report is rendered to the console.
6

Context Reset

The ContextVar is reset so sibling or subsequent calls start with a clean state.

Metadata Capture

Every trace stores these fields, automatically populated by the decorator:

FieldSourceExample
trace_idAuto-generated UUID4tr_2kf9q3m1
promptDecorator argument or function name"classify_document"
model_nameDecorator argument"gpt-4.1-mini"
latencytime.perf_counter() delta3420.00
token_countestimate_tokens() heuristic1247
statusCoerced from result or retry count"success"
project_idResolved from API key or argument"default"
environmentResolved or argument"production"
slow_requesttrue if latency >= 1500msfalse
retry_countCollected from nested tools1
failure_reasonException or result fieldnull
created_atFunction start time2026-05-31T14:22:10Z

Examples

Usage patternsCopy
python
from tracellm import trace

# Basic usage — prompt defaults to function name
@trace()
def classify_document(text: str) -> str:
    return "classified as important"

# With explicit prompt and model
@trace(prompt="classify_document", model_name="gpt-4o")
def classify(text: str) -> str:
    return process(text)

# Production environment with project grouping
@trace(
    prompt="process_payment",
    model_name="gpt-4o",
    project="payment-service",
    environment="production",
    api_key="tlm_sk_abc123def456",
)
def process_payment(transaction: dict) -> str:
    return execute(transaction)

Common Errors

ErrorCauseFix
trace() missing required positional argumentDecorator called without parenthesesUse @trace(), not @trace
Trace persistence skippedMongoDB is unavailableThe trace still completes — check MONGO_URL and start MongoDB
API key not foundInvalid or expired API keyGenerate a new key with tracellm create-project

Warning

Always use @trace() with parentheses, not @trace. The decorator factory requires invocation to return the actual wrapper.

Troubleshooting

Tip

If traces are not appearing in the dashboard, verify that MongoDB is running and MONGO_URLis set. The decorator logs a yellow "Trace persistence skipped" warning when persistence fails, but the function itself still executes normally.