-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Closed
Labels
Feature requestNew feature requestNew feature request
Description
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
- Is there a current way to achieve per-request dependency initialization?
- If not, would you be open to adding this functionality?
- What would be the preferred API design for this feature?
Environment
- pydantic-ai version: 0.4.9
- Python version: 3.14
dorukgezici and inking
Metadata
Metadata
Assignees
Labels
Feature requestNew feature requestNew feature request