Python SDK API Reference

Both

Complete API reference for the Traccia Python SDK.

This page documents all public functions, classes, and decorators in the Traccia Python SDK.

Initialization

traccia.init()

Simplified initialization for Traccia SDK with config file support and automatic trace management.

python
def init(
api_key: Optional[str] = None,
*,
auto_start_trace: bool = True,
auto_trace_name: str = "root",
config_file: Optional[str] = None,
**kwargs
) -> TracerProvider

Parameters:

api_key — API key for Traccia Platform (optional)
auto_start_trace — Auto-start a root trace (default: True)
auto_trace_name — Name for auto-started trace (default: "root")
config_file — Path to config file (optional)
**kwargs — All parameters from start_tracing() can be passed here
compliance — Optional dict with frameworks and risk_tier (see Governance)
redact_pii — Mask email/phone/SSN on sensitive span attrs before export (default: false)
prompt_cache_ttl_s — Client cache TTL for load_prompt (default: 60)

Returns:

TracerProvider instance

Example:

python
from traccia import init
# Minimal initialization
init()
# With API key
init(api_key="tr_live_xxxxxxxxxxxx")
# With custom config
init(
endpoint="http://localhost:4318/v1/traces",
agent_id="my-agent",
sample_rate=0.1
)
# With governance overlay
init(
api_key="tr_live_…",
compliance={"frameworks": ["eu_ai_act"], "risk_tier": "high"},
redact_pii=True,
)

traccia.start_tracing()

Advanced initialization with full control over all configuration options. Use this when you need more control than init() provides.

python
def start_tracing(
*,
api_key: Optional[str] = None,
endpoint: Optional[str] = None,
sample_rate: float = 1.0,
max_queue_size: int = 5000,
max_export_batch_size: int = 512,
schedule_delay_millis: int = 5000,
exporter: Optional[Any] = None,
use_otlp: bool = True,
enable_patching: bool = True,
enable_token_counting: bool = True,
enable_costs: bool = True,
pricing_override: Optional[dict] = None,
pricing_refresh_seconds: Optional[int] = None,
enable_console_exporter: bool = False,
enable_file_exporter: bool = False,
file_exporter_path: str = "traces.jsonl",
reset_trace_file: bool = False,
enable_span_logging: bool = False,
auto_instrument_tools: bool = False,
max_tool_spans: int = 100,
max_span_depth: int = 10,
session_id: Optional[str] = None,
user_id: Optional[str] = None,
tenant_id: Optional[str] = None,
project_id: Optional[str] = None,
agent_id: Optional[str] = None,
debug: bool = False,
attr_truncation_limit: Optional[int] = None,
service_name: Optional[str] = None,
max_spans_per_second: Optional[float] = None,
max_block_ms: int = 100,
openai_agents: Optional[bool] = None,
crewai: Optional[bool] = None,
enable_metrics: bool = True,
metrics_endpoint: Optional[str] = None,
metrics_sample_rate: float = 1.0,
compliance: Optional[dict] = None,
redact_pii: Optional[bool] = None,
) -> TracerProvider

See Configuration Reference for detailed parameter descriptions, and Metrics for how enable_metrics and metrics_endpoint work.

traccia.stop_tracing()

Gracefully shutdown tracing, flush pending spans, and clean up resources.

python
def stop_tracing(flush_timeout: Optional[float] = None) -> None
python
from traccia import stop_tracing
# Flush and shutdown
stop_tracing()
# With timeout (seconds)
stop_tracing(flush_timeout=10.0)

Tracing API

@observe()

Decorator to automatically create spans around function execution.

python
def observe(
name: Optional[str] = None,
*,
attributes: Optional[Dict[str, Any]] = None,
tags: Optional[Iterable[str]] = None,
as_type: str = "span",
skip_args: Optional[Iterable[str]] = None,
skip_result: bool = False,
) -> Callable

See @observe() Documentation for detailed usage and examples.

traccia.span()

Context manager for creating manual spans.

python
def span(name: str, attributes: dict = None) -> ContextManager
python
from traccia import span
with span("database_query", {"table": "users"}) as s:
result = db.query("SELECT * FROM users")
s.set_attribute("row_count", len(result))

traccia.span_scope()

Start a span with explicit lifecycle control. Unlike span(), the span is not ended automatically — call scope.end() when the operation completes. Use for long-lived operations such as streaming chat turns.

python
def span_scope(
name: str,
*,
attributes: Optional[Dict[str, Any]] = None,
parent: Optional[Any] = None,
parent_context: Optional[Any] = None,
tracer_name: str = "traccia",
) -> SpanScope
python
from traccia import span_scope
async def handle_stream():
turn = span_scope("chat.turn", attributes={"span.type": "llm"})
try:
await turn.run_async(lambda: stream_tokens())
except Exception as e:
turn.end(error=e)
raise
else:
turn.end()

traccia.run_with_span() / run_with_span_async()

Run a function with a specific span set as the active parent. Used internally by SpanScope.run() and SpanScope.run_async().

python
from traccia import get_tracer, run_with_span, run_with_span_async
tracer = get_tracer()
span = tracer.start_span("background_job")
# Sync
run_with_span(span, lambda: process_batch())
# Async
await run_with_span_async(span, lambda: process_batch_async())
span.end()

traccia.get_current_span()

Return the currently active span in the call context, or None.

python
from traccia import get_current_span
span = get_current_span()
if span:
span.set_attribute("step", "validation")

traccia.trace()

Context manager for creating explicit root traces. Ends auto-trace if active.

python
class trace:
def __init__(self, name: str = "trace", **kwargs)
python
from traccia import init, trace
init() # Auto-starts "root" trace
# End auto-trace and start custom trace
with trace("my-workflow", project="ml-pipeline"):
# All spans here are children of "my-workflow"
do_work()

traccia.end_auto_trace()

Explicitly end the auto-started trace without starting a new one.

python
def end_auto_trace() -> None
python
from traccia import init, end_auto_trace
init() # Auto-starts trace
# Do some work...
# End auto-trace before creating custom traces
end_auto_trace()

traccia.get_tracer()

Get a tracer instance by instrumentation scope name.

python
def get_tracer(name: str = "default") -> Tracer
python
from traccia import get_tracer
tracer = get_tracer("my-service")
with tracer.start_as_current_span("operation") as span:
span.set_attribute("custom", "value")
do_work()

traccia.get_tracer_provider()

Access the global tracer provider instance.

python
def get_tracer_provider() -> TracerProvider

traccia.set_tracer_provider()

Override the global tracer provider (primarily for testing or advanced customization).

python
def set_tracer_provider(provider: TracerProvider) -> None

Runtime Configuration

The runtime_config module provides functions to set and get runtime metadata at any point during execution.

Session ID

python
from traccia import runtime_config
runtime_config.set_session_id(value: Optional[str]) -> None
runtime_config.get_session_id() -> Optional[str]

User ID

python
runtime_config.set_user_id(value: Optional[str]) -> None
runtime_config.get_user_id() -> Optional[str]

Tenant ID

python
runtime_config.set_tenant_id(value: Optional[str]) -> None
runtime_config.get_tenant_id() -> Optional[str]

Project ID

python
runtime_config.set_project_id(value: Optional[str]) -> None
runtime_config.get_project_id() -> Optional[str]

Agent ID

python
runtime_config.set_agent_id(value: Optional[str]) -> None
runtime_config.get_agent_id() -> Optional[str]

Debug Mode

python
runtime_config.set_debug(value: bool) -> None
runtime_config.get_debug() -> bool

Attribute Truncation Limit

python
runtime_config.set_attr_truncation_limit(value: int) -> None
runtime_config.get_attr_truncation_limit() -> int

Runtime config example

python
from traccia import runtime_config
# Set metadata for current context
runtime_config.set_agent_id("billing-agent")
runtime_config.set_session_id("session-123")
runtime_config.set_user_id("user-456")
# Enable debug logging
runtime_config.set_debug(True)

Instrumentation

traccia.instrumentation.patch_openai()

Manually patch OpenAI client (called automatically if enable_patching=True).

python
from traccia.instrumentation import patch_openai
patch_openai()

traccia.instrumentation.patch_anthropic()

Manually patch Anthropic client.

python
from traccia.instrumentation import patch_anthropic
patch_anthropic()

traccia.instrumentation.patch_requests()

Manually patch requests library for HTTP client tracing.

python
from traccia.instrumentation import patch_requests
patch_requests()

traccia.instrumentation.install_http_middleware()

Install FastAPI middleware for automatic HTTP server span creation and context extraction.

python
from fastapi import FastAPI
from traccia.instrumentation import install_http_middleware
app = FastAPI()
install_http_middleware(app)

traccia.instrumentation.inject_http_headers()

Inject trace context into HTTP headers for manual propagation.

python
from traccia.instrumentation import inject_http_headers
headers = {}
inject_http_headers(headers)
# headers now contains 'traceparent' and 'tracestate'

traccia.instrumentation.extract_parent_context()

Extract parent trace context from HTTP headers.

python
from traccia.instrumentation import extract_parent_context
parent_context = extract_parent_context(request_headers)

Span Methods

When you have a span object (from span(), get_tracer().start_as_current_span(), or as parameter in @observe()), you can use these methods:

span.set_attribute(key: str, value: Any)

Add or update a span attribute

span.add_event(name: str, attributes: dict = None)

Add a timestamped event to the span

span.record_exception(exception: Exception)

Record an exception as a span event

span.set_status(status: SpanStatus, description: str = "")

Set span status (OK, ERROR, UNSET)

span.end()

End the span (called automatically by context managers)

Example Usage:

python
from traccia import span
from traccia.tracer.span import SpanStatus
with span("process_order", {"order_id": "12345"}) as s:
s.add_event("Validating order")
try:
validate_order(order)
s.add_event("Order validated")
process_payment(order)
s.add_event("Payment processed")
s.set_attribute("payment_status", "success")
s.set_status(SpanStatus.OK)
except PaymentError as e:
s.record_exception(e)
s.set_status(SpanStatus.ERROR, str(e))
raise

Prompts

Fetch versioned prompts from the Traccia library at runtime, compile {{variables}}, and stamp the active span with prompt identity. Narrative guide: Prompts in the SDK. Platform workflow: Platform Prompts.

Requires Traccia platform

Runtime fetch uses your workspace API key against the prompt-runtime API. Tracing-only / self-hosted OTLP backends can still call compile on an explicit fallback body.

traccia.load_prompt()

python
def load_prompt(
name: str,
*,
label: str = "production",
version: Optional[int] = None,
fallback: Optional[Mapping[str, Any]] = None,
force_refresh: bool = False,
) -> LoadedPrompt

Parameters

name — Prompt name in the workspace library
label — Deploy label (default production). Ignored when version is set
version — Exact integer version (mutually exclusive with label)
fallback — Body used when fetch fails and nothing is cached (chat or text shape with optional messages/text)
force_refresh — Bypass the client cache and fetch synchronously

Returns: LoadedPrompt

.name, .type, .version, .version_id, .label
.text / .messages — uncompiled body by type
.config — model hint / config from the version
.is_fallback, .is_stale
.compile(**vars) or .compile(variables=dict) — substitutes {{var}}; missing required → CompileError; unknown extras → warning
.span_attributes() / .apply_span_attributes()traccia.prompt.* keys (also applied automatically on successful compile)
python
from traccia import init, load_prompt, observe
init(
api_key="tr_…",
endpoint="https://api.traccia.ai/v2/traces",
prompt_cache_ttl_s=60,
)
@observe(as_type="llm")
def reply(question: str) -> str:
prompt = load_prompt(
"support-reply",
label="production",
fallback={
"type": "chat",
"messages": [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "{{question}}"},
],
},
)
messages = prompt.compile(question=question)
return call_llm(messages)

traccia.prefetch_prompts()

Warm the client cache at process start. Optional jitter spreads multi-replica startup stampedes.

python
def prefetch_prompts(
names: Sequence[str],
*,
label: str = "production",
jitter_s: float = 1.0,
) -> List[LoadedPrompt]
prefetch_prompts(["support-reply", "billing-triage"], jitter_s=0.5)

Cache, SWR, and init options

  • Default TTL ~60s; key is name + label or version
  • After expiry: return last good immediately and refresh in the background (stale-while-revalidate). is_stale=True
  • Fetch failure with cache → last good. Fetch failure without cache → fallback if provided, else error
prompt_cache_ttl_s / TRACCIA_PROMPT_CACHE_TTL_S

Compile errors and span attributes

traccia.prompts.CompileError (also exported as traccia.CompileError) is raised when a required {{var}} is missing. Successful compile sets:

traccia.prompt.name
traccia.prompt.version
traccia.prompt.version_id
traccia.prompt.label
traccia.prompt.is_fallback # only when fallback used

Redaction allowlists traccia.prompt.* so the sensitive key fragment "prompt" does not wipe identity. See Span Events & Attributes.

Governance

Optional audit attributes and PII masking. Human review (approve/reject) is not in the SDK — use Governance Hub.

@govern requires Traccia platform

@observe works with any OTLP backend. @govern calls the Traccia agent-status API before each run and requires a Traccia account (API key + endpoint). Tracing-only users should use @observe.

traccia.govern() / @govern

Observability plus runtime policy enforcement. Policy URLs are derived from your tracing endpoint — no [governance] TOML section required unless you use custom endpoints.

python
from traccia import init, govern
from traccia.governance import AgentBlockedError
init(api_key="...", endpoint="https://api.traccia.ai/v2/traces")
@govern(agent_id="my-agent", fail_open=False, name="run_agent")
def run_agent(prompt: str) -> str:
return call_llm(prompt)

Raises AgentBlockedError on hard block. Set TRACCIA_AGENT_ID instead of passing agent_id on each decorator.

init() parameters

compliance and redact_pii are passed to init() / start_tracing(). Env: TRACCIA_REDACT_PII, TRACCIA_COMPLIANCE_FRAMEWORKS.

traccia.governance.disclosure()

Record Art. 50 transparency evidence on the current span after your UI already informed the user they interact with AI. Does not render UI.

python
def disclosure(
*,
channel: str = "ui",
disclosed_to_user: bool = True,
synthetic_content: bool = False,
generator: Optional[str] = None,
) -> None

Sets governance.event_type=transparency, governance.transparency.disclosed, and related attrs.

traccia.governance.hooks.enrich_governance_attributes()

Build a dict of governance span attributes (input/output hashes, model id, integrity hash).

python
def enrich_governance_attributes(
attributes: Dict[str, Any],
*,
event_type: str = "inference",
model_id: Optional[str] = None,
model_version: Optional[str] = None,
input_text: Optional[str] = None,
output_text: Optional[str] = None,
session_id: Optional[str] = None,
eu_risk_tier: Optional[str] = None,
) -> Dict[str, Any]

traccia.governance.guardrail_span()

Context manager to track a guardrail evaluation and link it to the current trace.

python
def guardrail_span(
name: str,
*,
policy_id: Optional[str] = None,
action: str = "block",
) -> ContextManager

Automatically adds governance.guardrail.action and governance.guardrail.policy_id attributes to the span.

traccia.processors.redaction_processor

redact_string(text: str) -> strMask email, US phone, SSN-like patterns in a string.
redact_attributes(attrs) -> dictRedact sensitive keys in an attribute dict.
apply_redaction_to_span(span) -> intRedact mutable span attributes in-place; returns keys updated.

With init(redact_pii=True), RedactionSpanProcessor runs automatically at span end. Regex-based only — not ML PII detection.

traccia.governance.GOVERNANCE_PREFIX

Constant "governance." — prefix for attribute keys. EU keys use eu_ai_act.* when init(compliance={"frameworks": ["eu_ai_act"], "risk_tier": "high"}) is set. Full attribute list: Span attributes — Governance.

governance_example.py
python
from opentelemetry import trace
from traccia import init, observe
from traccia.governance import disclosure
from traccia.governance.hooks import enrich_governance_attributes
from traccia.processors.redaction_processor import redact_string, apply_redaction_to_span
init(compliance={"frameworks": ["eu_ai_act"], "risk_tier": "high"}, redact_pii=True)
@observe()
def chat(user_msg: str) -> str:
disclosure(channel="ui", disclosed_to_user=True)
safe = redact_string(user_msg)
out = run_llm(safe)
span = trace.get_current_span()
for k, v in enrich_governance_attributes({}, input_text=safe, output_text=out).items():
span.set_attribute(k, v)
apply_redaction_to_span(span)
return out

Configuration

traccia.config.load_config()

Load and validate configuration from file.

python
from traccia.config import load_config
config = load_config(config_file="traccia.toml")

traccia.config.validate_config()

Validate configuration without loading.

python
from traccia.config import validate_config
is_valid, message, config = validate_config(config_file="traccia.toml")
if not is_valid:
print(f"Config error: {message}")

Next Steps

© 2026 Traccia.