Skip to content

Add runtime context parameter for callbacks #760

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

anivar
Copy link

@anivar anivar commented Aug 24, 2025

My take on the discussion in #607

The issue raised a good point about callbacks needing access to runtime objects like A2A task updaters. I took a shot at implementing this with what seemed like the most straightforward approach.

What I built

Added a runtime_context parameter to run methods that gets passed through to callbacks:

# When running the agent, pass runtime objects
runtime_context = {"task_updater": updater, "user_session": session}
await agent.run_async("query", runtime_context=runtime_context)

Callbacks can then grab what they need:

def before_agent_invocation(self, context, prompt, **kwargs):
    if context.runtime_context and "task_updater" in context.runtime_context:
        updater = context.runtime_context["task_updater"]
        updater.update_status("started", "Processing query...")
    return context

Implementation approach

  • Added an optional runtime_context field to the existing Context object
  • Made it a keyword-only parameter so it doesn't mess with existing code
  • Keeps it simple - just a dictionary that flows through the callback system
  • Backward compatible since it defaults to None

Why this approach

Seemed like the cleanest way to solve the A2A task updater problem without over-engineering it. The Context object already flows through all callbacks, so extending it felt natural.

Happy to adjust based on feedback!

Addresses #607

Adds the ability to pass runtime-specific objects to callbacks via a new
runtime_context parameter on run() and run_async() methods.

Changes:
- Add runtime_context field to Context dataclass (optional)
- Add runtime_context parameter to run() and run_async() methods
- Pass runtime_context when creating Context objects
- Include comprehensive documentation

This enables callbacks to access objects that only exist at runtime, such as:
- Task updaters in A2A scenarios
- User session data
- Request-specific metadata
- Any other runtime objects callbacks need

Example usage:
  runtime_context = {"task_updater": updater, "session": session}
  await agent.run_async("query", runtime_context=runtime_context)

Callbacks can then access these objects via context.runtime_context.

Fixes mozilla-ai#607
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant