Accessing the RunContext
The RunContext is accessible from any callable within a Runnable’s execution usingget_run_context(). This includes:
- Main handlers: The main function that does the work (i.e. the function you pass to a Tool).
- Default parameter callables: Functions used to compute default values at runtime (as shown in Runnables).
- Lifecycle hooks: Functions that run before or after the main handler.
RunContext.current_span() method returns the span object for the currently executing Runnable, containing all execution data - input parameters, output, timing, metadata, and any custom data you store on it. You get direct access to the live span object being built during execution.
Here’s a simple example showing context access from a main handler:
Beyond
current_span(), the RunContext provides methods like .parent_span() and .step_span() to access parent or neighbor spans. We’ll explore these methods in future sections when working with multi-step workflows and nested executions.Lifecycle Hooks
Beyond the main handler, Runnables support lifecycle hooks - functions that run at specific points during execution. These provide structured access points for context interaction and enable powerful data transformation patterns. Every Runnable supports two optional hooks:pre_hook: A function that runs before the main handlerpost_hook: A function that runs after the main handler completes
Pre-hooks: Modifying Input and Adding Context
Apre_hook runs before your handler and can both modify input parameters and store additional context data:
- Data Preparation: Process raw webhook payloads, parse JSON, or normalize input formats
- Input Enhancement: Enrich data with additional context from databases or APIs
- Request Preprocessing: Extract headers, validate signatures, or decode authentication tokens
- State Initialization: Set up execution context, timestamps, or tracking metadata
Post-hooks: Processing Output After Completion
Apost_hook runs after your handler and can access both input and output:
- Logging: Record execution details and results
- Metadata Storage: Store processing metrics, timestamps, or analysis data
- Output Modification: Transform or enrich the final result
- Cleanup Tasks: Handle resource cleanup or state management
These simple examples show the basics. In practice, hooks excel at:
- Input manipulation: Processing webhooks where we don’t control the shape of the incoming data.
- Agent adaptation: Converting between modalities (audio ↔ text) for different models.