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
| Parameter | Type | Default | Description |
|---|---|---|---|
| prompt | str | "" (falls back to func.__name__) | The prompt or operation label recorded on the trace |
| model_name | str | "unknown" | Model identifier stored on the trace for filtering and analytics |
| project | str or None | None | Project name for grouping traces in the dashboard |
| environment | str | "development" | Environment label: development, staging, or production |
| api_key | str or None | None | TraceLLM 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:
| Field | Source | Example |
|---|---|---|
| trace_id | Auto-generated UUID4 | tr_2kf9q3m1 |
| prompt | Decorator argument or function name | "classify_document" |
| model_name | Decorator argument | "gpt-4.1-mini" |
| latency | time.perf_counter() delta | 3420.00 |
| token_count | estimate_tokens() heuristic | 1247 |
| status | Coerced from result or retry count | "success" |
| project_id | Resolved from API key or argument | "default" |
| environment | Resolved or argument | "production" |
| slow_request | true if latency >= 1500ms | false |
| retry_count | Collected from nested tools | 1 |
| failure_reason | Exception or result field | null |
| created_at | Function start time | 2026-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
| Error | Cause | Fix |
|---|---|---|
| trace() missing required positional argument | Decorator called without parentheses | Use @trace(), not @trace |
| Trace persistence skipped | MongoDB is unavailable | The trace still completes — check MONGO_URL and start MongoDB |
| API key not found | Invalid or expired API key | Generate 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.