Agentic AI Notebook
Phase 14

Dependencies

~2 min read

Concept & How It Works

  • Key points are in the visual diagram above.

Learn these elsewhere (not covered in depth here)

  • Build a PydanticAI Agent

Why Does It Exist?

Putting secrets or request-scoped handles in the prompt is how keys leak and tests become impossible.

Real-World Analogy

FastAPI Depends(). The handler receives a db session; the model never sees the connection string.
Loading diagram...

Visual Workflows

What is Dependencies?

Loading diagram...

Example

Scenario

Deps = {db, user_id}. Tool get_order uses ctx.deps.db. Tests inject InMemoryDB.

Solution

In PydanticAI, apply Dependencies to this scenario: Deps = {db, user_id}. Identify the inputs, run the technique, validate the output, and note one thing you would monitor in production.

Practice Task

Do this before moving to the next module — reading alone is not enough.

Open the Code Walkthrough below and run it locally. Change one parameter related to Dependencies (e.g. model, temperature, top_k, or tool name), observe the difference in output, and write 2–3 sentences explaining what changed.

Code Walkthrough

Highlighted lines show where Dependencies happens in the code.

Dependencies
1from dataclasses import dataclass  # import dependencies2from pydantic_ai import Agent, RunContext  # import dependencies3
4@dataclass5class Deps:  # define a data structure or component6    db: object7    user_id: str8
9agent: Agent[Deps, str] = Agent("openai:gpt-4o-mini", deps_type=Deps)  # key line for Dependencies10
11@agent.tool12async def my_orders(ctx: RunContext[Deps]) -> list[str]:  # key line for Dependencies13    return ctx.deps.db.list(ctx.deps.user_id)  # return the result14
15await agent.run("what did I buy?", deps=Deps(db=db, user_id="u1"))  # key line for Dependencies

Commands to Remember

Commands to Remember

  • deps_type on the Agent
  • RunContext[Deps] in tools
  • Inject fakes in tests
  • No secrets in tool args

Common Mistakes

  • Global db in the tool module
  • Passing user_id from the model

Cheat Sheet

Quick recap — the most important points from this module.

Cheat Sheet

quick ref
  • Deps ≠ prompt
  • Test with fakes
  • user_id from auth
  • Clock is a dep