Interaction Context

Context management for interaction patterns providing access to state, request, and custom data

InteractionContext Class

The InteractionContext class provides a unified interface for accessing state, request data, and custom data within interaction patterns. This allows render functions and handlers to access everything they need without passing many individual parameters.


source

InteractionContext


def InteractionContext(
    state:Dict=<factory>, request:Optional=None, session:Optional=None, data:Dict=<factory>, metadata:Dict=<factory>
)->None:

Context for interaction patterns providing access to state, request, and custom data.

Usage Examples

The InteractionContext is typically created and managed by interaction pattern classes (like StepFlow), but here are examples showing how it’s used:

# Create a context
ctx = InteractionContext()
ctx
InteractionContext(state={}, request=None, session=None, data={}, metadata={})
# Store and retrieve state
ctx.set("plugin_id", "transcription_voxtral")
ctx.set("step", 1)

print(f"Plugin ID: {ctx.get('plugin_id')}")
print(f"Has file_path: {ctx.has('file_path')}")
Plugin ID: transcription_voxtral
Has file_path: False
# Context with custom data (typically from data loaders)
ctx_with_data = InteractionContext(
    state={"user_id": "123"},
    data={
        "plugins": [
            {"name": "voxtral", "title": "Voxtral HF"},
            {"name": "whisper", "title": "Whisper"}
        ],
        "plugin_count": 5
    }
)

plugins = ctx_with_data.get_data("plugins", [])
print(f"Plugins available: {ctx_with_data.get_data('plugin_count')}")
print(f"First plugin: {plugins[0]}")
Plugins available: 5
First plugin: {'name': 'voxtral', 'title': 'Voxtral HF'}
# Batch updates
ctx.update_state({
    "file_path": "/path/to/file.mp3",
    "confirmed": True
})

print(f"All state: {ctx.get_all_state()}")
All state: {'plugin_id': 'transcription_voxtral', 'step': 1, 'file_path': '/path/to/file.mp3', 'confirmed': True}

Using Context in Render Functions

Here’s how the context is typically used within step render functions:

# Example render function signature
def render_plugin_selector(ctx: InteractionContext):
    """Render plugin selection step."""
    # Access loaded data
    plugins = ctx.get_data("plugins", [])
    
    # Access current state
    selected = ctx.get("plugin_id")
    
    # Could access request if needed
    # app_state = ctx.request.app.state
    
    # Return rendered UI
    return f"Render {len(plugins)} plugins, selected: {selected}"
# Simulate using the render function
test_ctx = InteractionContext(
    state={"plugin_id": "plugin_1"},
    data={"plugins": [{}, {}]}  # 2 plugins
)

render_plugin_selector(test_ctx)
'Render 2 plugins, selected: plugin_1'