Initialization
Configure and initialize Mantis SDK tracing.
Basic Initialization
The simplest way to initialize tracing:
import mantisdk.tracing as tracing
# Auto-detect Insight credentials from environment variables
tracing.init()This will:
- Create an OpenTelemetry TracerProvider
- Auto-detect Insight credentials from
INSIGHT_*environment variables - Set up a BatchSpanProcessor for efficient export
Configuration Options
tracing.init()
tracing.init(
service_name="my-agent", # Service name in traces
trace_name="my-workflow", # Name for the trace (shown in Insight)
environment="production", # Environment for filtering (production, staging, dev)
version="1.2.3", # App version for regression tracking
# Insight credentials (alternative to env vars)
insight_host="https://insight.withmetis.ai",
insight_public_key="pk-lf-...",
insight_secret_key="sk-lf-...",
insight_endpoint=None, # Custom OTLP endpoint (optional)
instrument_default=True, # Auto-instrument common libraries
trace_config=None, # OpenInference TraceConfig (optional)
integrations=None, # Fine-grained integration control (optional)
force=False, # Replace existing TracerProvider
debug="INFO", # Console logging level (False, True, or level string)
)| Parameter | Type | Default | Description |
|---|---|---|---|
service_name | str | "mantisdk-tracing" | Name of your service |
trace_name | str | None | Name for the trace, shown in Insight UI |
environment | str | None | Environment name (production, staging, dev) for filtering in Insight |
version | str | None | App version (e.g., "1.2.3", git SHA) for regression tracking |
insight_host | str | None | Insight server URL. Overrides INSIGHT_HOST env var |
insight_public_key | str | None | Insight public key. Overrides INSIGHT_PUBLIC_KEY env var |
insight_secret_key | str | None | Insight secret key. Overrides INSIGHT_SECRET_KEY env var |
insight_endpoint | str | None | Optional OTLP endpoint. Overrides INSIGHT_OTLP_ENDPOINT env var |
instrument_default | bool | True | Enable auto-instrumentation |
exporters | list[SpanExporter] | Auto-detect | Custom exporters |
trace_config | TraceConfig | None | OpenInference TraceConfig for controlling capture behavior |
integrations | dict[str, Any] | None | Fine-grained control over individual integrations |
force | bool | False | Replace existing provider |
debug | bool | str | False | Console logging level. See Debug Logging |
Provider Reuse Behavior
- If no TracerProvider exists, creates one
- If a TracerProvider exists and
force=False, reuses it and adds processors - If
force=True, replaces the existing TracerProvider
Debug Logging
The debug parameter controls how much tracing activity the SDK prints to the console. Use it to verify that tracing is working, diagnose export failures, or inspect individual spans.
import mantisdk.tracing as tracing
# Recommended: see init summary and export results
tracing.init(service_name="my-agent", debug="INFO")
# Minimal: only see problems (export failures, missing credentials)
tracing.init(service_name="my-agent", debug="WARNING")
# Full firehose: every span start/end, all internal plumbing
tracing.init(service_name="my-agent", debug=True)
# Silent (default): no console output
tracing.init(service_name="my-agent", debug=False)Log Levels
| Level | What you see |
|---|---|
False (default) | Nothing. Silent operation. |
"ERROR" | Only export failures and exceptions. |
"WARNING" | Export failures and missing exporter warnings. |
"INFO" | Recommended. Init summary, export success/failure with timing, instrumentor activation, shutdown summary. |
"DEBUG" or True | Everything above plus every span start/end, processor setup, and internal plumbing. |
Example Output
debug="INFO" -- what most users want:
[mantisdk.tracing] Created new TracerProvider with service_name=my-agent
[mantisdk.tracing] Auto-configured Insight exporter from environment variables
[mantisdk.tracing] Instrumented: openai
[mantisdk.tracing] MantisDK tracing initialized successfully
[mantisdk.tracing] Export: 4 span(s) -> SUCCESS (https://insight.withmetis.ai, 85ms)
[mantisdk.tracing] Shutdown: exported 47 span(s) totaldebug=True -- full firehose for debugging:
[mantisdk.tracing] Created new TracerProvider with service_name=my-agent
[mantisdk.tracing] Added TracingContextSpanProcessor
[mantisdk.tracing] Added LoggingSpanProcessor
[mantisdk.tracing] Auto-configured Insight exporter from environment variables
[mantisdk.tracing] Instrumented: openai
[mantisdk.tracing] MantisDK tracing initialized successfully
[mantisdk.tracing] Span started: "my-workflow"
[mantisdk.tracing] Span started: "ChatCompletion" (auto: openai)
[mantisdk.tracing] Span ended: "ChatCompletion" (0.61s) trace_id=abc123...
[mantisdk.tracing] Span ended: "my-workflow" (1.32s) trace_id=abc123...
[mantisdk.tracing] Export: 2 span(s) -> SUCCESS (https://insight.withmetis.ai, 85ms)
[mantisdk.tracing] Flush completed successfully
[mantisdk.tracing] Shutdown: exported 2 span(s) totaldebug=True is a shortcut for debug="DEBUG". The parameter is backward compatible -- existing code using debug=True or debug=False works unchanged.
If no exporter is configured (missing Insight credentials and no custom exporters), the SDK logs a warning: "No exporter configured -- spans will not be persisted". Set debug="WARNING" or higher to see it.
Pass Insight Credentials Directly
Instead of relying on environment variables, you can pass Insight credentials straight to init(). This is useful in notebooks, one-off scripts, or when you pull secrets from a vault at runtime.
import os
import mantisdk.tracing as tracing
tracing.init(
service_name="my-agent",
insight_host=os.environ.get("INSIGHT_HOST"),
insight_public_key=os.environ.get("INSIGHT_PUBLIC_KEY"),
insight_secret_key=os.environ.get("INSIGHT_SECRET_KEY"),
)You must pass all three credential parameters (insight_host, insight_public_key, insight_secret_key) together. If any are missing, the SDK falls back to environment variables entirely.
Control Capture Behavior with trace_config
Pass an OpenInference TraceConfig to control what the SDK captures. This is helpful when you need to hide sensitive inputs or outputs.
from openinference.instrumentation import TraceConfig
import mantisdk.tracing as tracing
config = TraceConfig(hide_inputs=True, hide_outputs=False)
tracing.init(
service_name="my-agent",
trace_config=config,
instrument_default=True,
)Fine-Grained Integration Control with integrations
The integrations parameter lets you pass configuration to individual auto-instrumentors. Keys are instrumentor names (e.g., "openai", "anthropic"), values are dictionaries of options forwarded to that instrumentor.
import mantisdk.tracing as tracing
tracing.init(
service_name="my-agent",
instrument_default=True,
integrations={
"openai": {"record_content": False},
"anthropic": {"record_content": True},
},
)Environment Variables
Insight Configuration
# Required for Insight export
INSIGHT_HOST=https://insight.withmetis.ai
INSIGHT_PUBLIC_KEY=pk-lf-your-public-key
INSIGHT_SECRET_KEY=sk-lf-your-secret-key
# Optional: Override OTLP endpoint
INSIGHT_OTLP_ENDPOINT=https://custom.endpoint/v1/tracesChecking Configuration
from mantisdk.tracing.exporters.insight import is_insight_configured
if is_insight_configured():
print("Insight credentials found")
else:
print("Set INSIGHT_HOST, INSIGHT_PUBLIC_KEY, INSIGHT_SECRET_KEY")Custom Exporters
Using Insight Exporter Explicitly
import mantisdk.tracing as tracing
tracing.init(
service_name="my-agent",
exporters=[
tracing.insight_exporter(
host="https://insight.withmetis.ai",
public_key="pk-lf-...",
secret_key="sk-lf-...",
)
]
)Custom OTLP Exporter
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
import mantisdk.tracing as tracing
tracing.init(
service_name="my-agent",
exporters=[
OTLPSpanExporter(endpoint="http://localhost:4317"),
]
)Lifecycle Management
Shutdown
Always call shutdown() before your program exits to ensure all spans are exported:
import atexit
import mantisdk.tracing as tracing
tracing.init()
# Option 1: Register with atexit
atexit.register(tracing.shutdown)
# Option 2: Manual try/finally
try:
main()
finally:
tracing.shutdown()Flush
Force flush pending spans without shutting down:
# Process a batch
for item in batch:
process(item)
# Ensure spans are exported before continuing
tracing.flush()
# Continue with more work...Shutdown vs Flush
| Function | Behavior |
|---|---|
shutdown() | Flushes spans, closes processors, releases resources. Logs total export count. |
flush() | Flushes spans, keeps provider running |
Complete Example
#!/usr/bin/env python3
"""Complete initialization example."""
import atexit
from dotenv import load_dotenv
load_dotenv()
import mantisdk.tracing as tracing
tracing.init(
service_name="my-agent",
environment="production",
version="1.0.0",
instrument_default=True,
debug="INFO",
)
atexit.register(tracing.shutdown)
with tracing.trace("test_trace", input="hello"):
print("Tracing is working!")Next Steps
- Traces & Spans - Create spans in your code
- Auto-Instrumentation - Enable framework support
- Insight Export - Configure Insight backend