Python SDK API Reference
BothComplete 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.
def init( api_key: Optional[str] = None, *, auto_start_trace: bool = True, auto_trace_name: str = "root", config_file: Optional[str] = None, **kwargs) -> TracerProviderParameters:
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 herecompliance — 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:
from traccia import init
# Minimal initializationinit()
# With API keyinit(api_key="tr_live_xxxxxxxxxxxx")
# With custom configinit( endpoint="http://localhost:4318/v1/traces", agent_id="my-agent", sample_rate=0.1)
# With governance overlayinit( 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.
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,) -> TracerProviderSee 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.
def stop_tracing(flush_timeout: Optional[float] = None) -> Nonefrom traccia import stop_tracing
# Flush and shutdownstop_tracing()
# With timeout (seconds)stop_tracing(flush_timeout=10.0)Tracing API
@observe()
Decorator to automatically create spans around function execution.
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,) -> CallableSee @observe() Documentation for detailed usage and examples.
traccia.span()
Context manager for creating manual spans.
def span(name: str, attributes: dict = None) -> ContextManagerfrom 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.
def span_scope( name: str, *, attributes: Optional[Dict[str, Any]] = None, parent: Optional[Any] = None, parent_context: Optional[Any] = None, tracer_name: str = "traccia",) -> SpanScopefrom 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().
from traccia import get_tracer, run_with_span, run_with_span_async
tracer = get_tracer()span = tracer.start_span("background_job")
# Syncrun_with_span(span, lambda: process_batch())
# Asyncawait 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.
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.
class trace: def __init__(self, name: str = "trace", **kwargs)from traccia import init, trace
init() # Auto-starts "root" trace
# End auto-trace and start custom tracewith 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.
def end_auto_trace() -> Nonefrom traccia import init, end_auto_trace
init() # Auto-starts trace
# Do some work...
# End auto-trace before creating custom tracesend_auto_trace()traccia.get_tracer()
Get a tracer instance by instrumentation scope name.
def get_tracer(name: str = "default") -> Tracerfrom 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.
def get_tracer_provider() -> TracerProvidertraccia.set_tracer_provider()
Override the global tracer provider (primarily for testing or advanced customization).
def set_tracer_provider(provider: TracerProvider) -> NoneRuntime Configuration
The runtime_config module provides functions to set and get runtime metadata at any point during execution.
Session ID
from traccia import runtime_config
runtime_config.set_session_id(value: Optional[str]) -> Noneruntime_config.get_session_id() -> Optional[str]User ID
runtime_config.set_user_id(value: Optional[str]) -> Noneruntime_config.get_user_id() -> Optional[str]Tenant ID
runtime_config.set_tenant_id(value: Optional[str]) -> Noneruntime_config.get_tenant_id() -> Optional[str]Project ID
runtime_config.set_project_id(value: Optional[str]) -> Noneruntime_config.get_project_id() -> Optional[str]Agent ID
runtime_config.set_agent_id(value: Optional[str]) -> Noneruntime_config.get_agent_id() -> Optional[str]Debug Mode
runtime_config.set_debug(value: bool) -> Noneruntime_config.get_debug() -> boolAttribute Truncation Limit
runtime_config.set_attr_truncation_limit(value: int) -> Noneruntime_config.get_attr_truncation_limit() -> intRuntime config example
from traccia import runtime_config
# Set metadata for current contextruntime_config.set_agent_id("billing-agent")runtime_config.set_session_id("session-123")runtime_config.set_user_id("user-456")
# Enable debug loggingruntime_config.set_debug(True)Instrumentation
traccia.instrumentation.patch_openai()
Manually patch OpenAI client (called automatically if enable_patching=True).
from traccia.instrumentation import patch_openai
patch_openai()traccia.instrumentation.patch_anthropic()
Manually patch Anthropic client.
from traccia.instrumentation import patch_anthropic
patch_anthropic()traccia.instrumentation.patch_requests()
Manually patch requests library for HTTP client tracing.
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.
from fastapi import FastAPIfrom 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.
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.
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:
from traccia import spanfrom 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)) raisePrompts
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
compile on an explicit fallback body.traccia.load_prompt()
def load_prompt( name: str, *, label: str = "production", version: Optional[int] = None, fallback: Optional[Mapping[str, Any]] = None, force_refresh: bool = False,) -> LoadedPromptParameters
name — Prompt name in the workspace librarylabel — Deploy label (default production). Ignored when version is setversion — 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 synchronouslyReturns: 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)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.
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 →
fallbackif provided, else error
prompt_cache_ttl_s / TRACCIA_PROMPT_CACHE_TTL_SCompile errors and span attributes
traccia.prompts.CompileError (also exported as traccia.CompileError) is raised when a required {{var}} is missing. Successful compile sets:
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.
from traccia import init, governfrom 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.
def disclosure( *, channel: str = "ui", disclosed_to_user: bool = True, synthetic_content: bool = False, generator: Optional[str] = None,) -> NoneSets 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).
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.
def guardrail_span( name: str, *, policy_id: Optional[str] = None, action: str = "block",) -> ContextManagerAutomatically 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.
from opentelemetry import tracefrom traccia import init, observefrom traccia.governance import disclosurefrom traccia.governance.hooks import enrich_governance_attributesfrom 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 outConfiguration
traccia.config.load_config()
Load and validate configuration from file.
from traccia.config import load_config
config = load_config(config_file="traccia.toml")traccia.config.validate_config()
Validate configuration without loading.
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.