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:
...thread_id without any code change
When an adapter opens the trace for you, it fills thread_id in from whatever conversation
identity the framework already carries — an openai-agents session= / conversation_id= or a
thread/thread_id on the run context, a LangGraph configurable.thread_id, the Claude Agent
SDK’s session id. A thread_id you pass to run() always wins; the adapter only fills a gap.
Both SDKs do this. In TypeScript the field is threadId on run() / runTraced(), and the
adapters read the same places (session / conversationId / the run context for openai-agents,
configurable.thread_id for LangChain and LangGraph, the message session_id for the Claude
Agent SDK).
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.