Set Context
set_context() attaches custom key/value dimensions — customer ID, feature, plan, team, whatever
you already tag internally — to the currently active trace. Two dashboard surfaces read these
values back: Cost’s Segments tab and custom-metric SLOs on
the Reliability screen.
Signature
morse_ai.set_context(**dims: str) -> NoneCall it inside an active trace — typically once per request, e.g. in Django middleware:
morse_ai.set_context(customer_id=request.customer_id, feature="doc-qa")Values are coerced to str() at the SDK boundary; non-string values you pass in are converted
automatically.
Outside an active trace, set_context() is a silent no-op — it does nothing until called from
inside morse_ai.run(...) or @morse_ai.trace_agent.
You can also pass the same dimensions directly when opening a trace, via run()’s
user_metadata kwarg — set_context() is the mid-trace equivalent for values you don’t know yet
at run() time:
with morse_ai.run(
"chat-agent",
thread_id=session_id,
user_id=current_user.id,
user_metadata={"customer_id": tenant_id, "feature": "doc-qa"},
) as r:
...What reads these dimensions
Segments (Cost)
The Cost screen’s Segments tab breaks down cost, coverage, and trace count by any key you’ve set.
It stays empty until your code calls set_context() at least once — the empty state prints the
exact set_context() line to add, rather than hiding the capability.
Custom-metric SLOs (Reliability)
An SLO can target a custom metric instead of a built-in one (success rate, cost, latency). Defining
one asks for a Key field labeled “matches your set_context() key” — the SLO evaluates
whatever value you attach under that key on each trace.
Related
- Overview — the SDK’s tracing primitives (
run(),span(),trace_agent). - Installation — minimal
init()call and API key setup. - Cost — where Segments render the dimensions you set.
- Reliability — where custom-metric SLOs consume the same key.