Overview
The Python SDK provides async- and thread-safe session context using Python contextvars, analogous to the TypeScript SDK’s AsyncLocalStorage. This ensures spans from concurrent requests are attributed to the correct session. Use the context helpers below to manage session lifecycle and binding in a reliable, ergonomic way.When to use
- Use
with lai.session(...)
for self-contained workflows that should start and end within a single function or request handler. - Use
with lai.bind_session(session_id)
when you need to attach an existing session to a block of work without ending it. - Prefer these context helpers over relying on a global session in concurrent environments.
Full lifecycle: session
Creates a new session, binds it to the current context, and automatically ends it on context exit.- Inside
session(...)
,auto_end
is ignored; the session always ends on context exit. - Telemetry stamps
lucidic.session_id
on spans at start to ensure correct attribution.
Bind only: bind_session
Bind an existing session to a block of code. The session is not ended on exit.Async variants
Use these in async code paths.Function wrappers
Wrap a function to run within a session context.Manual control
You can manually bind and clear the active session when needed.Important behaviors
init(...)
binds the created or resumed session id to the current context automatically.- Exporter and span processor use the context-stamped
lucidic.session_id
so events are created for the correct session even under concurrency. - Use provider instrumentation via
providers=[...]
insideinit/session
to capture LLM calls automatically.