Skip to content

Pydantic AI

Here's an example showing how to use batchling with Pydantic AI:

pydantic_ai_example.py
import asyncio

from dotenv import load_dotenv
from pydantic_ai import Agent

from batchling import batchify

load_dotenv()


async def build_tasks() -> list:
    """Build pydantic-ai requests."""
    agent = Agent(
        model="openai:gpt-5-nano",
        tools=[],
    )
    questions = [
        "Who is the best French painter? Answer in one short sentence.",
        "What is the capital of France?",
    ]
    return [agent.run(user_prompt=question) for question in questions]


async def main() -> None:
    """Run the pydantic-ai example."""
    tasks = await build_tasks()
    responses = await asyncio.gather(*tasks)
    for response in responses:
        print(f"{response._state.message_history[-1].model_name} answer:\n{response.output}\n")


async def run_with_batchify() -> None:
    """Run `main` inside `batchify` for direct script execution."""
    async with batchify():
        await main()


if __name__ == "__main__":
    asyncio.run(run_with_batchify())

Output:

gpt-5-nano-2025-08-07 answer:
There isn’t a single best French painter, but Claude Monet is often regarded as one of the greatest.

gpt-5-nano-2025-08-07 answer:
Paris.

Would you like a few fun facts about Paris or its sights?