Back

Pydantic AI Examples on Agentuity

May 9, 2025 by Rick Blalock

Pydantic AI and Agentuity

Pydantic AI takes the nice ergonomics of FastAPI and brings it to agents and LLMs. It's super easy to deploy on Agentuity!

A Simple Pydantic AI Agent

Below is a simple example of a Pydantic AI agent taken from their docs. This shows you how easy it is to take an existing Pydantic AI agent and drop it in Agentuity.

import random
from pydantic_ai import Agent, RunContext
from agentuity import AgentRequest, AgentResponse, AgentContext

# Example taken from: https://ai.pydantic.dev/agents/#introduction

# The pydantic agent
roulette_agent = Agent(
    'openai:gpt-4o',
    deps_type=int,
    output_type=bool,
    system_prompt=(
        'Use the `roulette_wheel` function to see if the '
        'customer has won based on the number they provide.'
    ),
)

# A tool for the pydantic agent
@roulette_agent.tool
async def roulette_wheel(ctx: RunContext[int], square: int) -> str:
    """check if the square is a winner"""
    return 'winner' if square == ctx.deps else 'loser'

# The Agentuity agent handler
async def run(request: AgentRequest, response: AgentResponse, context: AgentContext):
		# Spin that wheel!
    success_number = random.randint(0, 20)

		# Pull out the user query from the request
    user_query = await request.data.text()
    if not user_query:
        user_query = random.randint(0, 20)

    context.logger.info("User query: %s, Winning number: %s", user_query, success_number)

    try:
        context.logger.info("Calling PydanticAI roulette agent with query: '%s' and deps: %s", user_query, success_number)

        pydantic_ai_result = await roulette_agent.run(
            user_query,
            deps=success_number
        )
        context.logger.info("PydanticAI result output: %s", pydantic_ai_result.output)

        return response.json({
            "won": pydantic_ai_result.output,
            "details": "Bet processed by PydanticAI roulette agent.",
            "user_query": user_query,
            "success_number": success_number
        })

    except Exception as e:
        context.logger.error("Error running PydanticAI agent: %s", e)
        return response.json({"error": str(e)}, status_code=500)

Integrating with Agentuity

Notice how little code is needed to make this work?

  1. Define the Pydantic AI agent.
  2. Wrap the agent invocation within an AgentHandler function.
  3. Read the user's input from req.data.text().
  4. Return the structured output using resp.json(). Agentuity handles the JSON serialization automatically.

Deploying to the Cloud

Assuming you have the Agentuity CLI installed and configured, navigate to your project directory and run agentuity deploy.

That's it! Your Pydantic AI agent is now live and accessible via an API endpoint provided by Agentuity.

More examples can be found in the our docs.