Skip to content

AG-UI dependencies per request #2377

@kadosh1000

Description

@kadosh1000

How to Initialize Dependencies Per Request in ag_ui?

Summary

I need to initialize different dependencies for each user/request when using to_ag_ui(), but the current implementation appears to share dependencies across all users.

Use Case

I'm building a multi-tenant application where each user should have their own isolated dependencies (e.g., database connections, user-specific context, API clients with different credentials). Currently, it seems like dependencies are initialized once and shared across all ag_ui sessions.

What I've Tried

from pydantic_ai import Agent
from pydantic_ai.dependencies import RunContext

# Current approach - but this creates shared dependencies
def get_user_db_connection(user_id: str):
    # This should be called per user, not shared
    return DatabaseConnection(user_id=user_id)

agent = Agent(
    'openai:gpt-4',
    deps_type=DatabaseConnection,
)

@agent.tool
def query_data(ctx: RunContext[DatabaseConnection], query: str) -> str:
    # ctx.deps is shared across users - not what we want
    return ctx.deps.execute(query)

# This creates a shared instance
app = agent.to_ag_ui()

Expected Behavior

Each user session should be able to initialize its own dependencies, possibly through:

  • A dependency factory function that receives request context
  • Per-session dependency initialization hooks
  • Request-scoped dependency injection

Something like:

def dependency_factory(request_context):
    user_id = extract_user_from_request(request_context)
    return DatabaseConnection(user_id=user_id)

app = agent.to_ag_ui(deps_factory=dependency_factory)

Actual Behavior

Dependencies appear to be initialized once and shared across all users, making it impossible to have user-specific context.

Questions

  1. Is there a current way to achieve per-request dependency initialization?
  2. If not, would you be open to adding this functionality?
  3. What would be the preferred API design for this feature?

Environment

  • pydantic-ai version: 0.4.9
  • Python version: 3.14

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions