Skip to content

Performance slowdown when enforcing output_type with a Pydantic BaseModel in an Agent #3342

@MansourKama

Description

@MansourKama

Question

Hi 👋

I’m using PydanticAI and defining an Agent with a Pydantic BaseModel as the output_type to ensure the model always returns a fixed structured output, even when hallucinations occur.

Here’s a simplified snippet of my setup:

module_agent = Agent(
    template_fallback_model,
    name=f"Agent Module {module_code}",
    output_type=list[pydantic_module],
    system_prompt=agent_system_prompt,
    tools=selected_tools,  # direct injection of matching tools
    retries=2,
)

Where pydantic_module is dynamically generated from a JSON template:

pydantic_module = build_pydantic_model_from_module(module_template)

def build_pydantic_model_from_module(module_template: dict) -> type[BaseModel]:
    ...

I noticed that when I enforce this output_type, the agent becomes significantly slower in returning responses.

My question:
👉 Is this slowdown expected because of internal schema validation or regeneration attempts when forcing the model to match a Pydantic schema?
If so, is there a recommended way to optimize structured outputs while keeping schema consistency?

Thanks in advance 🙏

Additional Context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    StalequestionFurther information is requested

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions