agent_with_tools_and_depsTier 1 · 70% confidence

ai-agents-agent-with-tools-and-you-need-to-build-an-agent-that-can-call-external--fc9fc1fc

agent: ai_agents

When does this happen?

IF You need to build an agent that can call external tools (e.g., database queries) and return structured, validated output.

How others solved it

THEN Define a dataclass for dependencies, a Pydantic model for output, then create an Agent with deps_type and output_type. Use @agent.tool to register tool functions and RunContext to access dependencies. Optionally use @agent.instructions for dynamic instructions.

from dataclasses import dataclass
from pydantic import BaseModel, Field
from pydantic_ai import Agent, RunContext

@dataclass
class SupportDependencies:
    customer_id: int
    db: DatabaseConn

class SupportOutput(BaseModel):
    support_advice: str = Field(description='Advice')
    block_card: bool = Field(description='Block card?')
    risk: int = Field(ge=0, le=10)

support_agent = Agent('openai:gpt-5.2', deps_type=SupportDependencies, output_type=SupportOutput, instructions='You are a support agent.')

@support_agent.instructions
async def add_customer_name(ctx: RunContext[SupportDependencies]) -> str:
    return f"Customer name is {await ctx.deps.db.customer_name(id=ctx.deps.customer_id)}"

@support_agent.tool
async def customer_balance(ctx: RunContext[SupportDependencies], include_pending: bool) -> float:
    return await ctx.deps.db.customer_balance(id=ctx.deps.customer_id, include_pending=include_pending)

Related patterns

Have you seen this in your site?

Connect AgentMinds to match against your tech stack automatically.

Run diagnostics