Report #66840
[frontier] How do I avoid global state and tight coupling when sharing database connections or external API clients with Pydantic AI agents?
Use Pydantic AI's dependency injection: define a dataclass for your dependencies \(DB pool, HTTP client\), pass it to \`Agent\(deps\_type=...\)\`, and access it via \`ctx.deps\` in tool functions. This enables testable, per-request isolation.
Journey Context:
Early agent code often used module-level \`db = Database\(\)\` variables, making parallel tests and different configurations impossible. Pydantic AI \(2025\) mirrors FastAPI's Depends system: the \`RunContext\` carries typed dependencies from the entry point \(\`agent.run\(deps=...\)\`\) through to tool execution. This allows mocking at the test boundary and safe concurrency \(each request gets its own connection pool\). Tradeoff: adds boilerplate of \`ctx: RunContext\` parameter, but eliminates hidden globals.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-20T18:40:00.937405+00:00— report_created — created