Skip to main content

Monte Carlo OpenTelemetry SDK

This library provides a Python SDK for tracing applications with OpenTelemetry for use with Monte Carlo's AI Observability solution.

To evaluate the effectiveness of AI agents, the first step is capturing the prompts sent to an LLM and the completions returned. The next challenge is categorizing these LLM calls, since different types of LLM calls require different evaluation approaches.

This SDK not only streamlines OpenTelemetry tracing setup, but it also makes it easy to add custom attributes to spans, enabling you to filter and select different subsets of spans for evaluation.

This is alpha software. The API is subject to change.

End-user feedback (SDK 0.6.0)

Feedback is supported for agents whose traces are stored in Agent Observability ClickHouse. Before enabling it, upgrade the Agent Observability chart to 6.0.0 or later and follow the chart README's "Upgrading to 6.0.0" instructions. Complete both the schema job and collector rollout before sending feedback spans. The guide also covers the required settings for custom collector endpoints. Before chart 6.0.0, feedback spans are stored as ordinary traces. Upgrading does not convert those older spans into feedback: the feedback view reads only new inserts, and the stray traces remain until retention expires. Upgrade each installation before enabling feedback in SDK 0.6.0. Warehouse trace tables and individual-message or individual-span ratings are not supported.

Capture the trace ID during the run, then return it with the answer and keep it with that answer. The backend handling the feedback button sends it back:

import montecarlo_opentelemetry as mc

mc.setup(agent_name="support-agent", otlp_endpoint=YOUR_EXISTING_OTLP_ENDPOINT)

def answer(question):
    with mc.get_tracer().start_as_current_span("answer"):
        answer_trace_id = mc.current_trace_id()
        result = run_agent(question)
        return {"answer": result, "trace_id": answer_trace_id}

# In your authenticated backend's feedback-button handler, possibly days later:
queued = mc.record_feedback(
    trace_id=the_answer_trace_id,
    rating="negative",
    categories=["incorrect"],
    comment="The answer used the wrong table",
)

current_trace_id() returns None outside an active span. Do not obtain the ID in the feedback request: that would identify the feedback request itself. LangGraph Server applications can instead use mc.record_feedback(run_id=the_answer_run_id, rating="positive"). Use run IDs only for runs started after the chart's schema job and collector rollout have both finished. For any run started earlier, including runs that span the upgrade, use its saved trace ID: links from its run ID to earlier traces may be missing. Other LangChain applications also require that same run ID in their original trace metadata as montecarlo.association_properties.run_id.

Each call sends the complete current state. Include the current rating and categories when adding or editing a comment. Omit rating for a comment with no rating; use rating="none" to clear feedback. The newest state wins for the whole trace, even if several users rated it. Old records remain until retention expires. A numeric score, including zero, is accepted but is not displayed in v1. A call without a rating, score, nonblank comment, or category returns False. A score-only update still replaces the complete previous state. Its score stays in the raw span, but it does not retain the previous rating, comment, or categories and has no displayed rating in v1.

The helper uses only processors registered on the global provider by Monte Carlo setup() or add_exporter(), including a custom span_processor passed to setup(). It calls those processors' on_end(), not on_start(), the same way an ending span reaches them. To scrub feedback, scrub inside the span_processor passed to setup(...): it receives the feedback span in on_end(). Adding a separate processor with provider.add_span_processor() does not apply it to feedback. The helper skips the global sampler and unrelated exporters, but respects OTEL_SDK_DISABLED: when the provider was created with telemetry disabled, record_feedback() returns False without sending feedback. Changing that environment variable after the provider is created does not change its setting. Customer collector sampling must also preserve user_feedback spans. Feedback does not make a sampled-out agent trace reappear. agent_name= overrides the agent on this feedback only; use it when another service handles the button, one process hosts many agents, or traces are labeled with montecarlo.agent_name baggage. Feedback does not read baggage; pass the same agent name explicitly.

Feedback is handed to those processors directly, with no queue of its own. With the default BatchSpanProcessor it joins the processor's queue, shared with ordinary spans, and the processor's worker exports it; when that queue is full, the SDK drops the oldest queued span, feedback included (size the queue with OTEL_BSP_MAX_QUEUE_SIZE). With SimpleSpanProcessor the feedback is exported before record_feedback() returns, as every ending span is. The call never raises for validation or transport errors. True means every Monte Carlo processor accepted the span, not that it was stored. A processor that raises drops the feedback with a warning and no retry. provider.force_flush(timeout_millis=...) and provider.shutdown() deliver queued feedback the way they deliver ordinary spans, within the processor's own timeouts; once provider.shutdown() starts, record_feedback() returns False. At normal interpreter exit, the provider's own shutdown drains its processors. A provider created with shutdown_on_exit=False needs an explicit flush or shutdown before the process exits. Shutdown follows the installed OpenTelemetry version and processors: BatchSpanProcessor changed to a 30-second default worker wait in OpenTelemetry 1.36, and version 1.45.2 retains that behavior. Versions 1.34 and 1.35 wait without a timeout. This is not a time limit for the whole shutdown: other processors and exporter cleanup can take longer.

Use mc.flush_feedback(timeout_millis=1000) to flush only the Monte Carlo processors. Before calling each processor's force_flush(), it checks one shared deadline and passes the remaining time. Flushing also exports ordinary spans queued ahead of the feedback. True means the processors reported a successful flush, not that the collector accepted or stored the spans. BatchSpanProcessor can return True even when its exporter fails. The helper returns False after the provider is shut down, when the timeout is used up before a processor's turn, or when a processor's force_flush() returns False or raises. A custom processor's force_flush() may return True or None on success. This does not stop a processor that ignores its timeout: the native BatchSpanProcessor in OpenTelemetry 1.36 and 1.45.2 exports everything it holds regardless. With one such processor, a flush can exceed the requested timeout and still return True. Do not record or flush feedback from a signal handler: the handler can land inside the processor's own lock, as it can for any span ending there. Safe failure warnings identify the operation and reason and repeat at most once per operation and reason every 60 seconds; they never include submitted values or exception text.

Server shutdown

Servers must drain tracing during their own shutdown steps. Uvicorn versions including 0.40 and 0.54 re-raise SIGTERM after app cleanup. With the normal signal handler, that ends the process without Python's exit hooks, so the provider's automatic exit shutdown cannot deliver the last buffered feedback.

Call mc.setup() once when the process starts, outside the app's lifespan. Close the provider after requests, background work, and existing app cleanup have finished. For a FastAPI app that already uses event handlers, add the final call to its existing last shutdown handler; keep its startup handlers:

import asyncio

from fastapi import FastAPI
from opentelemetry import trace

import montecarlo_opentelemetry as mc

mc.setup(agent_name="support-agent", otlp_endpoint=YOUR_EXISTING_OTLP_ENDPOINT)
provider = trace.get_tracer_provider()

app = FastAPI()  # Keep your existing app construction and startup handlers.


@app.on_event("shutdown")
async def shutdown():
    try:
        await close_application_resources()  # Your existing app cleanup.
    finally:
        await asyncio.to_thread(provider.shutdown)

For an app already using a lifespan function, put that same final call at the end of its existing cleanup. Do not add lifespan= to an app using @app.on_event handlers: FastAPI would stop calling those handlers. See https://fastapi.tiangolo.com/advanced/events/.

provider.shutdown() permanently closes that provider. Moving setup outside the lifespan does not make a closed provider reusable. If tests enter the same app repeatedly, or several apps share a provider, flush at each app's cleanup instead of closing it:

await asyncio.to_thread(mc.flush_feedback, timeout_millis=1000)

The process must still call provider.shutdown() once when that shared provider is no longer needed. Flushing has the timeout and return-value limits described above. Shutdown also blocks, so asyncio.to_thread keeps it off the event-loop thread. It does not impose a time limit: the server's stop allowance must cover the processor and exporter shutdown. Do not add a separate flush before final shutdown; shutdown already drains the same buffers.

Event identity and limits

For retries, create a UUID event_id and an aware datetime submitted_at in your trusted backend when the user changes the feedback, and reuse both for that same state. Generate event_id there because it becomes the feedback span's trace and span ID. Create new values for the next edit. Reusing only the parent thumb's ID for different states would make distinct changes look like duplicates. Timestamp strings use YYYY-MM-DDTHH:MM:SS[.fraction] followed by Z or ±HH:MM across supported Python versions; fractional digits beyond microseconds are truncated. Timestamps more than 300 seconds in the future are rejected. Keep the submitting service's clock correct: accepted future timestamps can sort ahead of later edits until the clock catches up. Timestamps are preserved on retries, not clamped by arrival time. Identity is optional: pass a customer-computed keyed hash as user_hash=, or explicitly opt in to a raw ID with user_id=. Never pass both. The helper does not invent a hashing key.

Comments are limited to 4096 UTF-8 bytes. There can be at most 20 categories, each at most 128 UTF-8 bytes. Agent names and user identifiers are limited to 256 UTF-8 bytes; run IDs to 128. Invalid data returns False. Comments remain in the raw trace storage and are read only with raw-data permission; the feedback index stores whether a comment exists, not its text.

A service without a tracer

Set up the feedback service with the same collector endpoint and credentials used for the agent's traces:

mc.setup(agent_name="support-agent", otlp_endpoint=YOUR_EXISTING_OTLP_ENDPOINT)

If the service already has an OpenTelemetry SDK provider, use mc.add_exporter(YOUR_EXISTING_OTLP_ENDPOINT) instead, and pass agent_name="support-agent" to record_feedback(). This sends feedback to the installation holding the agent's traces. Without a Monte Carlo pipeline registered by setup() or add_exporter(), the helper returns False and logs a warning at most once every 60 seconds. It makes no separate HTTP request. Services using plain OpenTelemetry can emit a user_feedback span as shown below. Services using Monte Carlo's hosted ingestion can also call the hosted REST endpoint directly.

Google ADK or plain OpenTelemetry

Read the active span inside the agent run. With ADK, an after_agent_callback can save the ID under the current invocation so later requests cannot replace another answer's ID:

from opentelemetry import trace

def after_agent_callback(callback_context):
    context = trace.get_current_span().get_span_context()
    if context.is_valid:
        callback_context.state[f"feedback_trace:{callback_context.invocation_id}"] = (
            format(context.trace_id, "032x")
        )
    return None

# Set after_agent_callback=after_agent_callback when constructing your ADK agent.

async def response_for_answer(runner, user_id, session_id, final_event, answer_text):
    # Call after fully consuming runner.run_async(), so the callback's state is saved.
    session = await runner.session_service.get_session(
        app_name=runner.app_name, user_id=user_id, session_id=session_id
    )
    answer_trace_id = (
        session.state.get(f"feedback_trace:{final_event.invocation_id}")
        if session is not None else None
    )
    return {"answer": answer_text, "trace_id": answer_trace_id}

The answer route returns response_for_answer()'s result. The browser keeps that response with its displayed answer. Enable its feedback button only when trace_id is present, and send that ID back when the user clicks it:

const answer = await answerResponse.json();
// Keep `answer` with this answer's feedback button.
await fetch("/feedback", {
  method: "POST",
  headers: {"Content-Type": "application/json"},
  body: JSON.stringify({trace_id: answer.trace_id, rating: "negative"}),
});

ADK exposes the invocation ID on its callback context and returned events, and stores callback state in the session; see https://github.com/google/adk-python/blob/main/src/google/adk/agents/readonly_context.py, https://github.com/google/adk-python/blob/main/src/google/adk/events/event.py and https://github.com/google/adk-python/blob/main/src/google/adk/sessions/base_session_service.py.

From that backend, use the hosted endpoint below, or emit a span named user_feedback through the agent's existing OTel exporter with these attributes:

def record_button_feedback(feedback_request):
    # feedback_request is the JSON body sent by this answer's feedback button.
    attributes = {
        "gen_ai.evaluation.name": "user_feedback",
        "gen_ai.evaluation.evaluator.type": "human",
        "montecarlo.agent_name": "support-agent",
        "montecarlo.feedback.trace_id": feedback_request["trace_id"],
        "gen_ai.evaluation.score.label": feedback_request["rating"],
    }
    with agent_tracer.start_as_current_span("user_feedback", attributes=attributes):
        pass

Use the rated agent's service name and preserve these spans in every sampler. Set montecarlo.agent_name to that same agent when another service sends feedback; copy its exact name and run ID without adding or removing whitespace. This manual example follows the normal tracer's exporters; filter feedback out of other destinations if necessary. The Python SDK helper handles exporter isolation and application sampling for you. Each manual call creates a new span. For retry deduplication, use the SDK helper or REST endpoint with the same event_id and submitted_at for every retry.

Hosted REST example

This direct-call option is for services using Monte Carlo's hosted ingestion. Customer-hosted collectors do not implement this endpoint; use the agent's collector through the SDK or plain OpenTelemetry instead. Run this on your backend. The browser must never receive the OTel key. Replace the host and target trace ID with your configured host and a stored answer ID:

curl --fail-with-body "https://YOUR_INGESTION_HOST/otel/v1/feedback" \
  -H "Content-Type: application/json" \
  -H "x-mcd-id: $MCD_DEFAULT_API_ID" \
  -H "x-mcd-token: $MCD_DEFAULT_API_TOKEN" \
  --data '{"agent":"support-agent","trace_id":"1234567890abcdef1234567890abcdef","rating":"negative","categories":["incorrect"],"comment":"The answer used the wrong table"}'

The JSON body has agent and exactly one of trace_id or run_id. Optional fields are rating, categories, comment, score, user_hash, user_id, event_id (UUID), and submitted_at (ISO 8601 with timezone). The body limit is 16 KiB. Successful delivery returns {"accepted": true}. Malformed data gets 400, invalid credentials 401, and a key without a data store 403. Temporary delivery errors return 429 or 5xx. A valid-looking but unknown trace ID cannot be rejected immediately: feedback may arrive first. The agent's mismatch warning identifies feedback still unmatched after 24 hours. Stored feedback and raw spans follow the installation's retention, 30 days by default.

Installation

Install the SDK

Requires Python 3.10 or later.

$ pip install montecarlo-opentelemetry

Install the instrumentation package(s) for the AI libraries you want to trace.

The Monte Carlo SDK can work with existing instrumentation for AI libraries to capture traces automatically. Choose the instrumentation library that matches the library you are using.

# For Langchain/LangGraph
$ pip install "opentelemetry-instrumentation-langchain<=0.53.4"

# For OpenAI
$ pip install "opentelemetry-instrumentation-openai<=0.53.4"

See a selection of available instrumentation libraries below.

Quick Start

Set up Tracing in Your Application

# Import the Monte Carlo SDK.
import montecarlo_opentelemetry as mc

# Import the AI client library (Anthropic in this example.)
from anthropic import Anthropic

# Import the corresponding instrumentation library.
from opentelemetry.instrumentation.anthropic import AnthropicInstrumentor

# Create an Instrumentor object
anthropic_instrumentor = AnthropicInstrumentor()

# Set up tracing.
mc.setup(
    agent_name="my-agent",
    otlp_endpoint="http://localhost:4318/v1/traces",
    instrumentors=[anthropic_instrumentor],
)

# Use decorator to add a Monte Carlo workflow attribute.
@mc.trace_with_workflow("parent-function", "my-workflow")
def parent():
    child()

# Use decorator to add a Monte Carlo task attribute.
@mc.trace_with_task("child-function", "my-task")
def child():
    message = Anthropic().messages.create(
        max_tokens=1024,
        messages=[
            {
                "role": "user",
                "content": "Hello world!",
            }
        ],
        model="claude-sonnet-4-20250514",
    )

Add MonteCarlo API credentials as environment variables

If you are sending OpenTelemetry traces to a Monte Carlo OTLP Ingestion endpoint, you will need to add your Monte Carlo API credentials as environment variables when running your application. See our docs on generating API keys.

There are two different ways to add your Monte Carlo API credentials as environment variables. Choose the option that best fits your needs.

  1. Use Monte Carlo environment variables. Similar to how environment variables are used for the Pycarlo SDK, you can set separate environment variables for your Monte Carlo API ID and API token.

    $ export MCD_DEFAULT_API_ID=<your-api-id>
    $ export MCD_DEFAULT_API_TOKEN=<your-api-token>
    
  2. Use the standard OpenTelemetry environment variable for headers. You can add both your Monte Carlo API ID and API token to the OTEL_EXPORTER_OTLP_HEADERS environment variable. The value of this environment variable should be a comma-separated list of key=value pairs, where the keys are: x-mcd-id and x-mcd-token.

    $ export OTEL_EXPORTER_OTLP_HEADERS="x-mcd-id=<your-api-id>,x-mcd-token=<your-api-token>"
    

Configuring the span processor

By default, mc.setup() configures a BatchSpanProcessor that buffers spans and flushes them on a timer. This is the right choice for long-running services because batching reduces export overhead.

The default exporter pipeline is tuned for the large spans that AI/LLM instrumentation produces (prompt and completion content can make a single span several MB):

  • gzip compression is on by default, shrinking OTLP request bodies over the wire.
  • max_export_batch_size defaults to 128 (smaller than OpenTelemetry's default of 512), keeping each OTLP request small enough to stay under the collector's body-size limit.

Both are lossless. If you supply your own span_processor (below), these defaults do not apply — configure compression and batch size on your processor as needed.

If you need different export behavior, pass your own processor with the span_processor kwarg:

mc.setup(
    agent_name="my-agent",
    otlp_endpoint="http://localhost:4318/v1/traces",  # required by signature; ignored when span_processor is set
    instrumentors=[LangchainInstrumentor()],          # Match the instrumentor to the AI library/framework you are using.
    span_processor=my_custom_processor,
)

The processor you pass replaces only the default exporter pipeline. mc.MonteCarloSpanProcessor — which propagates montecarlo.* attributes through the trace — is always installed on the tracer provider mc.setup() creates. If another library has already set the global tracer provider, that provider is used instead, and neither Monte Carlo's processor nor the one you pass is installed on it; see When another library already set the TracerProvider.

Serverless and other suspendable runtimes

In runtimes that can freeze the Python process between invocations — AWS Lambda, Google Cloud Run services, and similar — BatchSpanProcessor's timer-driven flush will not run reliably. Spans queued in the buffer are lost when the process is suspended and the runtime moves on without resuming it.

In these environments, use SimpleSpanProcessor, which exports ordinary spans synchronously when they end. record_feedback() then exports the feedback span synchronously as well, so feedback needs no extra flush. With BatchSpanProcessor, call the provider's force_flush() (or mc.flush_feedback()) before the handler returns; OpenTelemetry's AWS Lambda instrumentation calls the provider's force_flush() after each invocation, and that call includes Monte Carlo feedback.

import os

import montecarlo_opentelemetry as mc
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.instrumentation.langchain import LangchainInstrumentor
from opentelemetry.sdk.trace.export import SimpleSpanProcessor

mcd_headers = {
    "x-mcd-id": os.environ["MCD_DEFAULT_API_ID"],
    "x-mcd-token": os.environ["MCD_DEFAULT_API_TOKEN"],
}

# SimpleSpanProcessor exports ordinary spans and feedback as soon as they end,
# so nothing waits in a queue when the runtime suspends the process.
exporter = OTLPSpanExporter(endpoint="http://localhost:4318/v1/traces", headers=mcd_headers)
span_processor = SimpleSpanProcessor(exporter)

mc.setup(
    agent_name="my-agent",
    otlp_endpoint="http://localhost:4318/v1/traces",  # required by signature; ignored when span_processor is set
    instrumentors=[LangchainInstrumentor()],          # Match the instrumentor to the AI library/framework you are using.
    span_processor=span_processor,
)

Auth headers note: When you supply a custom span_processor, mc.setup() does not inject the MCD_DEFAULT_API_ID / MCD_DEFAULT_API_TOKEN headers — that injection only happens when mc.setup() builds the default exporter. The example above passes those headers explicitly. If you use OTEL_EXPORTER_OTLP_HEADERS instead, OTLPSpanExporter reads it automatically and you can omit the headers= argument.

The trade-off is per-span latency: each span ending blocks on an OTLP round-trip. That cost is acceptable when the alternative is losing spans entirely.

When another library already set the TracerProvider

OpenTelemetry lets a process set its global tracer provider only once, and the first one set wins. Some frameworks install their own while they start up, before your agent code runs — Google ADK's adk web does this. When that happens, mc.setup() cannot install Monte Carlo's provider: the existing provider stays in place, mc.setup() logs a warning, and spans are handled by the provider that is already there.

Add Monte Carlo to that provider with the two functions:

import montecarlo_opentelemetry as mc

mc.add_processor()                                  # montecarlo.* attributes on spans
mc.add_exporter("http://localhost:4318/v1/traces")  # Monte Carlo's OTLP pipeline

Both default to the global provider, both accept an explicit provider= instead, and both are idempotent: adding the same processor, or the same endpoint, twice does nothing. That matters because a framework can import your module more than once in a single process (Google ADK's --reload_agents does exactly that). Call them before the spans you care about, since attributes are added when a span starts. If you build a provider yourself, you can also add the processor directly with provider.add_span_processor(mc.MonteCarloSpanProcessor()); add_processor() does the same, once per provider.

add_exporter() adds Monte Carlo's tuned pipeline — gzip, max_export_batch_size=128, and credentials from MCD_DEFAULT_API_ID / MCD_DEFAULT_API_TOKEN, or from OTEL_EXPORTER_OTLP_TRACES_HEADERS or OTEL_EXPORTER_OTLP_HEADERS when those are not set. When added to the global provider, this pipeline also receives record_feedback() spans independently of the global sampler. A different endpoint is added as well, so Monte Carlo can be one of several destinations. Nothing is added automatically: if you don't call it and the provider in place doesn't export to Monte Carlo, no traces arrive.

Two things belong to the provider itself and cannot be changed once it exists: service.name and the span attribute limit (mc.setup() uses 1024). The OpenTelemetry SDK reads OTEL_SERVICE_NAME and OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT when the provider is created, so set them in the environment that launches the process. A .env file loaded after startup is too late — add_processor() warns when OTEL_SERVICE_NAME arrived after the provider was created.

To keep a custom pipeline — SimpleSpanProcessor in a suspendable runtime, for example — add your own exporter instead, with the same settings mc.setup() uses:

import os

import montecarlo_opentelemetry as mc
from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.http import Compression
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.trace.export import BatchSpanProcessor

mc.add_processor()

exporter = OTLPSpanExporter(
    endpoint="http://localhost:4318/v1/traces",  # Your endpoint, including the /v1/traces path.
    headers={
        "x-mcd-id": os.environ["MCD_DEFAULT_API_ID"],
        "x-mcd-token": os.environ["MCD_DEFAULT_API_TOKEN"],
    },
    compression=Compression.Gzip,
)
trace.get_tracer_provider().add_span_processor(
    BatchSpanProcessor(exporter, max_export_batch_size=128)
)

Don't add this exporter when the provider already exports to Monte Carlo — every span would be sent twice. And you own the processor you create, including its flush behavior; see Serverless and other suspendable runtimes.

This manual recipe exports ordinary spans, but does not register a processor for record_feedback(). To use the helper with a custom processor, call setup(span_processor=...) before another library installs the global provider. Once that provider is installed, a later setup() cannot add your custom processor or enable its feedback delivery. Keep your existing processor and emit the plain OpenTelemetry feedback span shown above, or use add_exporter() if Monte Carlo's default exporter meets your needs. Adding that exporter also sends ordinary spans to its endpoint, so avoid sending them there twice.

One provider, one service name, many agents

A framework that hosts several agents in one process has one tracer provider, and therefore one service.name. Label each agent per trace instead, with montecarlo.agent_name baggage, which Monte Carlo's span processor copies onto every span that starts while it is set:

from opentelemetry import baggage, context

token = context.attach(baggage.set_baggage("montecarlo.agent_name", "business-analyst-agent"))
try:
    run_the_agent()
finally:
    context.detach(token)

Set it per run, from whatever hook the framework gives you — an ADK plugin's before-run callback, for instance — rather than from a process-wide default, so concurrent agents don't label each other's spans.

Troubleshooting

  • The agent shows up as unknown_service. The provider was created before OTEL_SERVICE_NAME was available, which is what a configuration file loaded after startup produces. Set the variable in the environment that launches the process, or label per trace with montecarlo.agent_name baggage as above. When using baggage, also pass the same name to record_feedback(agent_name=...): feedback does not read baggage, and setting OTEL_SERVICE_NAME after the provider was created does not replace its existing unknown_service name.
  • The ingestion endpoint rejects an export as an invalid key id. A credential is wrapped in quotes — x-mcd-id='abc123' — which shells and .env files often keep as part of the value. When mc.setup() or mc.add_exporter() builds the exporter, Monte Carlo logs a warning naming the header (never the value).
  • Traces stop being labeled after editing agent code. Google ADK's --reload_agents re-imports agent modules in the same process, so module-level code runs again. Use add_processor() and add_exporter(), which are idempotent, rather than adding processors and exporters by hand.

Example

Example Application

To see how the Monte Carlo SDK can be used to add identifying attributes to spans, let's look at an example application that's slighly larger than the Quick Start one.

This is a simplified "Travel Assistant" agent that can make hotel and flight reservations.

# Fake LLM library that can make a call to an LLM.
from example.LLMLibrary import call_llm

def travel_assistant():
    flight_assistant()
    hotel_assistant()

def flight_assistant():
    plan_flight()
    book_flight()

def plan_flight():
    pass

def book_flight():
    call_llm()

def hotel_assistant():
    search_for_hotel()
    book_hotel()

def search_for_hotel():
    call_llm()

def book_hotel():
    call_llm()

If we traced each function in this application, the structure of the trace would look like this:

travel_assistant
├── flight_assistant
│   ├── plan_flight
│   └── book_flight
│       └── call_llm
└── hotel_assistant
    ├── search_for_hotel
    │   └── call_llm
    └── book_hotel
        └── call_llm

In order to differentiate between different types of LLM calls, it would be helpful to add identifying attributes to spans. That way we could tell if an LLM call was part of a workflow managed by the flight assistant, or if it was part of the hotel booking task in the workflow managed by the hotel assistant.

Adding Attributes with the Monte Carlo SDK

Let's see how we can use the Monte Carlo SDK to enhance the tracing data with identifying attributes.

import montecarlo_opentelemetry as mc

# Fake LLM library that can make a call to an LLM.
from example.LLMLibrary import call_llm

# Fake LLM library instrumentation that will automatically create spans
# each time call_llm() is called.
from example.LLMLibrary.instrumentation import LLMInstrumentor

mc.setup(
    agent_name="travel-assistant",
    otlp_endpoint="http://localhost:4318/v1/traces",
    instrumentors=[LLMInstrumentor()],
)

@mc.trace_with_tags(span_name="travel_assistant", tags=["travel", "v1"])
def travel_assistant():
    flight_assistant()
    hotel_assistant()

@mc.trace_with_workflow(span_name="flight_assistant", workflow_name="flight")
def flight_assistant():
    plan_flight()
    book_flight()

@mc.trace_with_task(span_name="plan_flight", task_name="plan")
def plan_flight():
    pass

@mc.trace_with_task(span_name="book_flight", task_name="book")
def book_flight():
    call_llm()

@mc.trace_with_workflow(span_name="hotel_assistant", workflow_name="hotel")
def hotel_assistant():
    search_for_hotel()
    book_hotel()

@mc.trace_with_task(span_name="search_for_hotel", task_name="search")
def search_for_hotel():
    call_llm()

# Arguments can also be passed positionally.
@mc.trace_with_task("book_hotel", "book")
def book_hotel():
    call_llm()

Because montecarlo.* attributes propagate from parent to child spans, the call_llm spans will contain all of the montecarlo.* attributes were added to spans that occur above it in the trace hierarchy.

For example, the call_llm span for book_flight will not only have the montecarlo.task = "book" attribute that we added directly, but also the montecarlo.workflow = "flight" added on the flight_assistant span, and the montecarlo.tags = "travel,v1" attributes added on the travel_assistant span.

That results in the following trace structure:

travel_assistant            <-- montecarlo.tags = "travel,v1"
│
├── flight_assistant        <-- montecarlo.workflow = "flight"
|   |                       <-- montecarlo.tags = "travel,v1"
|   |
│   ├── plan_flight         <-- montecarlo.task = "plan"
|   |                       <-- montecarlo.workflow = "flight"
|   |                       <-- montecarlo.tags = "travel,v1"
|   |
│   └── book_flight         <-- montecarlo.task = "book"
│       |                   <-- montecarlo.workflow = "flight"
│       |                   <-- montecarlo.tags = "travel,v1"
│       |
│       └── call_llm        <-- montecarlo.task = "book"
│                           <-- montecarlo.workflow = "flight"
│                           <-- montecarlo.tags = "travel,v1"
│
└── hotel_assistant         <-- montecarlo.workflow = "hotel"
    |                       <-- montecarlo.tags = "travel,v1"
    |
    ├── search_for_hotel    <-- montecarlo.task = "search"
    │   |                   <-- montecarlo.workflow = "hotel"
    │   |                   <-- montecarlo.tags = "travel,v1"
    │   |
    │   └── call_llm        <-- montecarlo.task = "search"
    │                       <-- montecarlo.workflow = "hotel"
    │                       <-- montecarlo.tags = "travel,v1"
    │
    └── book_hotel          <-- montecarlo.task = "book"
        |                   <-- montecarlo.workflow = "hotel"
        |                   <-- montecarlo.tags = "travel,v1"
        |
        └── call_llm        <-- montecarlo.task = "book"
                            <-- montecarlo.workflow = "hotel"
                            <-- montecarlo.tags = "travel,v1"

Capturing Span I/O

The trace_with_attributes, trace_with_task, and trace_with_workflow decorators accept an optional capture_io=True parameter (default False) that records the decorated function's inputs and return value directly into span attributes. This data is used by offline replay and evaluation tooling.

@mc.trace_with_task("analyze-monitor", "analyze", capture_io=True)
def analyze(monitor_uuid: str, threshold: int = 10):
    ...

What gets recorded

When capture_io=True is set, the decorator serializes the call's arguments — including positional arguments mapped to their parameter names — and writes them to the span attribute montecarlo.span_input. The return value is written to montecarlo.span_output.

The attributes use a structured envelope:

  • montecarlo.span_input — {"inputs": {"monitor_uuid": "abc-123", "threshold": 10}, "tags": [], "metadata": {}, "kwargs": {}}
  • montecarlo.span_output — {"outputs": <return value>, "kwargs": {}}

Values that aren't JSON-serializable are recorded as a <unserializable …> placeholder rather than their repr. Note that nested dataclass and Pydantic model fields are expanded — a config object with a nested credential field would be captured in full.

Why it's off by default

capture_io is opt-in per decoration so you control both data volume and which calls expose their arguments. Large inputs or outputs (long documents, big lists) can increase span size significantly, and not every call is appropriate to record — see the warning below.

Warning: With capture_io=True, call inputs and return values are serialized verbatim into span attributes and exported to your configured telemetry backend, where they are searchable, retained for the backend's retention window, often under broader access than your secret store, and not rotated when a secret rotates. Do not enable capture_io on calls that carry secrets, credentials, tokens, or PII. Values that aren't JSON-serializable are recorded as a <unserializable …> placeholder (not their repr), but nested dataclass/Pydantic fields are expanded — so a config object with a nested credential field would be captured verbatim.

For LLM prompt content specifically, see the Tracing LLM Calls Manually section below, which covers how to pass a redacted prompt list to create_llm_span while sending the un-redacted prompts to the model.

Tracing LLM Calls Manually

Typically, an instrumentation library will be used to automatically trace LLM calls. When that's not possible, the create_llm_span context manager can be used to create a span for the LLM call manually.

The create_llm_span context manager will set request-related attributes. Since provider, model, operation, and prompts are known before the LLM call is made, they should be passed to the context manager so that the appropriate span attributes can be added automatically. Response-related attributes need to be added with the helper functions after the LLM call.

It is possible to record a list of prompts as attributes that is different than the prompts sent to the LLM. If you have sensitive data that should not be recorded as span attributes, you can pass a modified list of prompts to create_llm_span, and then pass the un-redacted prompts to the LLM.

import montecarlo_opentelemetry as mc

# Fake LLM library that can make a call to an LLM.
from example.LLMLibrary import call_llm

prompts_to_record = [
    {"role": "system", "content": "You are a world-class greeter."},
    {"role": "user", "content": "Say hello to Bob."},
    {"role": "assistant", "content": "Hello Bob!"},
]

prompts_to_send = [
    {"role": "system", "content": "You are a world-class greeter."},
    {"role": "user", "content": "Say hello to Bob. Use SENSITIVE DATA."},
    {"role": "assistant", "content": "Hello Bob!"},
]

with mc.create_llm_span(
    span_name="example-span",
    provider="llm-provider",
    model="llm-model",
    operation="chat",
    prompts_to_record=prompts_to_record,
) as span:
    # Make LLM call.
    #
    # We are sending un-redacted prompts to the LLM. The LLM will see
    # "SENSITIVE DATA", but it won't be recorded as a span attribute.
    resp = call_llm(prompts_to_send)

    # Add response attributes to span.
    #
    # Assume that the response object has attributes like model, completions, etc.
    mc.add_llm_response_model(span, resp.model)
    mc.add_llm_completions(span, resp.completions)
    mc.add_llm_tokens(
        span,
        resp.prompt_tokens,
        resp.completion_tokens,
        resp.total_tokens,
        resp.cache_creation_input_tokens,
        resp.cache_read_input_tokens,
    )

License

Apache 2.0 - See the LICENSE for more information.

Security

See SECURITY.md for more information.

Available Instrumentation Packages

Note: Some packages have version constraints. See Version Compatibility below.

Version Compatibility

Newer versions of some instrumentation packages have adopted a different attribute format that will be supported in a future release.

Known incompatible versions:

Package Last compatible version First incompatible version
opentelemetry-instrumentation-anthropic 0.53.4 0.54.0
opentelemetry-instrumentation-openai 0.53.4 0.55.0
opentelemetry-instrumentation-langchain 0.53.4 0.55.0
opentelemetry-instrumentation-crewai 0.55.4 0.56.0
opentelemetry-instrumentation-bedrock 0.56.1 0.57.0

For other instrumentation packages, version 0.57.0 or earlier is recommended as they may adopt the new format in future releases.

Metadata

Release files for montecarlo-opentelemetry 0.6.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for montecarlo-opentelemetry 0.6.0
File Size Uploaded Provenance Actions
montecarlo_opentelemetry-0.6.0.tar.gz 45.7 kB Without provenance Details for montecarlo_opentelemetry-0.6.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for montecarlo-opentelemetry 0.6.0
File Interpreter ABI Platform Actions
montecarlo_opentelemetry-0.6.0-py3-none-any.whl Python 3 none any Details for montecarlo_opentelemetry-0.6.0-py3-none-any.whl

Total release size: 81.6 kB

Release files / montecarlo_opentelemetry-0.6.0.tar.gz

Download URL montecarlo_opentelemetry-0.6.0.tar.gz
Size 45.7 kB
Tags Source
SHA-256 checksum
How to use checksums
e5f6efb80c42579ecede59ec4b9dbac5ba3b885bed9802562d991013361e0074
BLAKE2b-256 checksum
How to use checksums
553e636635b7bc25abaf7d27803ee0a68870d3fdf93922da0111a80bec5c3c04
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.6.14

Release files / montecarlo_opentelemetry-0.6.0-py3-none-any.whl

Download URL montecarlo_opentelemetry-0.6.0-py3-none-any.whl
Size 35.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
25656a8afd5293aca49c6651f6549d9c8a71b53044a5231ab5e65cfb38c9e2bd
BLAKE2b-256 checksum
How to use checksums
8f5baf64f737c287fec5f6308b0cc32aab38d243887e3fb29c4d12ff7333d25e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.6.14

Security for montecarlo-opentelemetry 0.6.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page