Copy Context To Callable • AI Agent SDK
copy_context_to_callable: Wrap a callable to copy the current context to the new thread/executor.
copy_context_to_callable
Function
</div>
This function is defined in the context_events module.
Wrap a callable to copy the current context to the new thread/executor.
This is needed because contextvars are NOT automatically propagated to thread pool executors. Use this when calling run_in_executor().
The whole context is copied, so the replay state (emitter, run id, branch id and the open-span stack that yields `parent_seq`) reaches the thread.
Signature
def copy_context_to_callable(func: Any) -> AnyParameters
ParamField
AnyThe callable to wrap.
Returns
ResponseField
AnyA wrapped callable that copies the current context.
Usage
# Instead of:
await loop.run_in_executor(None, lambda: agent.chat(prompt))
# Use:
await loop.run_in_executor(None, copy_context_to_callable(lambda: agent.chat(prompt)))Uses
contextvars.copy_contextctx.run
Used By
Source
View on GitHubpraisonaiagents/trace/context_events.py at line 266