> ## Documentation Index
> Fetch the complete documentation index at: https://docs.praison.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Structured AI Agents

> Learn how to create AI agents that return structured, type-safe outputs using Pydantic models and JSON.

## Quick Start

<Tabs>
  <Tab title="Code">
    <Steps>
      <Step title="Install Package">
        First, install the PraisonAI Agents package:

        ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
        pip install praisonaiagents
        ```
      </Step>

      <Step title="Set API Key">
        Set your OpenAI API key as an environment variable in your terminal:

        ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
        export OPENAI_API_KEY=your_api_key_here
        ```
      </Step>

      <Step title="Create a file">
        Create a new file `app.py` with the basic setup:

        ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
        from praisonaiagents import Agent, Task, AgentTeam, Tools
        from pydantic import BaseModel

        # Define your data structure
        class AnalysisReport(BaseModel):
            title: str
            findings: str
            summary: str

        # Create agent
        analyst = Agent(
            role="Data Analyst",
            goal="Analyze data and provide structured insights",
            backstory="Expert in data analysis and insights generation",
            tools=[Tools.internet_search],
            
        )

        # Create task with structured output
        task = Task(
            description="Analyze recent AI developments",
            expected_output="Structured analysis report",
            agent=analyst,
            output_pydantic=AnalysisReport
        )

        # Create and start the agents
        agents = AgentTeam(
            agents=[analyst],
            tasks=[task],
            process="sequential",
            verbose=2
        )

        # Start execution
        result = agents.start()
        print(result.pydantic.title)
        print(result.pydantic.findings)
        print(result.pydantic.summary)
        ```
      </Step>

      <Step title="Start Agents">
        Type this in your terminal to run your agents:

        ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
        python app.py
        ```
      </Step>
    </Steps>
  </Tab>

  <Tab title="No Code">
    <Steps>
      <Step title="Install Package">
        Install the PraisonAI package:

        ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
        pip install praisonai
        ```
      </Step>

      <Step title="Set API Key">
        Set your OpenAI API key as an environment variable in your terminal:

        ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
        export OPENAI_API_KEY=your_api_key_here
        ```
      </Step>

      <Step title="Create a file">
        Create a new file `agents.yaml` with the basic setup:

        ```yaml theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
        framework: praisonai
        process: sequential
        topic: analyze AI developments with structured output
        agents:  # Canonical: use 'agents' instead of 'roles'
          analyst:
            instructions:  # Canonical: use 'instructions' instead of 'backstory' Expert in data analysis and insights generation.
            goal: Analyze data and provide structured insights
            role: Data Analyst
            tools:
              - internet_search
            tasks:
              analysis_task:
                description: Analyze recent AI developments.
                expected_output: Structured analysis report.
                output_structure:
                  type: pydantic
                  model:
                    title: str
                    findings: str
                    summary: str
        ```
      </Step>

      <Step title="Start Agents">
        Type this in your terminal to run your agents:

        ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
        praisonai agents.yaml
        ```
      </Step>
    </Steps>
  </Tab>
</Tabs>

<Note>
  **Requirements**

  * Python 3.10 or higher
  * OpenAI API key. Generate OpenAI API key [here](https://platform.openai.com/api-keys). Use Other models using [this guide](/models).
  * Basic understanding of Python and Pydantic
</Note>

## Understanding Structured Outputs

<Card title="What are Structured Outputs?" icon="question">
  Structured outputs allow you to:

  * Define exact shape of data using Pydantic models
  * Get type-safe, validated responses
  * Choose between Pydantic objects or JSON
  * Ensure consistent output format across agent responses
</Card>

## Features

<CardGroup cols={2}>
  <Card title="Pydantic Models" icon="cube">
    Define exact data structures with validation.
  </Card>

  <Card title="JSON Output" icon="brackets-curly">
    Get structured JSON responses.
  </Card>

  <Card title="Type Safety" icon="shield-check">
    Ensure type-safe, validated outputs.
  </Card>

  <Card title="Format Options" icon="code">
    Choose between Pydantic or JSON.
  </Card>
</CardGroup>

## Native Structured Output

PraisonAI automatically uses native `response_format` with JSON schema for models that support it (like GPT-4o, Claude 3.5, Gemini 2.0). This ensures clean JSON outputs without schema echoing.

<Tabs>
  <Tab title="Auto (Default)">
    By default, PraisonAI auto-detects if your model supports native structured output:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonaiagents import Agent
    from pydantic import BaseModel
    from typing import List

    class TopicList(BaseModel):
        topics: List[str]

    # Auto-detects gpt-4o-mini supports native structured output
    agent = Agent(
        name="TopicAgent",
        llm="gpt-4o-mini"
    )

    result = agent.chat("List 3 AI topics", output_pydantic=TopicList)
    ```
  </Tab>

  <Tab title="Force Native">
    Force native mode for models that may not be auto-detected:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    agent = Agent(
        name="TopicAgent",
        llm="custom-model",
        native_structured_output=True  # Force native response_format
    )
    ```
  </Tab>

  <Tab title="Disable Native">
    Disable native mode to use text injection fallback:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    agent = Agent(
        name="TopicAgent",
        llm="gpt-4o-mini",
        native_structured_output=False  # Use text injection
    )
    ```
  </Tab>
</Tabs>

<Note>
  **Supported Models**: GPT-4o, GPT-4o-mini, Claude 3.5 Sonnet, Gemini 2.0 Flash, and other models that support OpenAI's `response_format` with `json_schema`.

  **Flow**:

  1. Agent checks if model supports native structured output
  2. If supported → uses `response_format` with JSON schema (clean output)
  3. If not supported → falls back to prompt injection (schema in prompt)
</Note>

## Multi-Agent Structured Analysis

<Tabs>
  <Tab title="Code">
    <Steps>
      <Step title="Install Package">
        First, install the PraisonAI Agents package:

        ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
        pip install praisonaiagents
        ```
      </Step>

      <Step title="Set API Key">
        Set your OpenAI API key as an environment variable in your terminal:

        ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
        export OPENAI_API_KEY=your_api_key_here
        ```
      </Step>

      <Step title="Create a file">
        Create a new file `app.py` with the basic setup:

        ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
        from praisonaiagents import Agent, Task, AgentTeam, Tools
        from pydantic import BaseModel

        # Define output structures
        class ResearchReport(BaseModel):
            topic: str
            findings: str
            sources: list[str]

        class Analysis(BaseModel):
            key_points: list[str]
            implications: str
            recommendations: str

        # Create first agent for research
        researcher = Agent(
            role="Research Analyst",
            goal="Gather and structure research data",
            backstory="Expert in research and data collection",
            tools=[Tools.internet_search],
            
        )

        # Create second agent for analysis
        analyst = Agent(
            role="Data Analyst",
            goal="Analyze research and provide structured insights",
            backstory="Expert in data analysis and insights generation",
            
        )

        # Create first task
        research_task = Task(
            description="Research quantum computing developments",
            expected_output="Structured research findings",
            agent=researcher,
            output_pydantic=ResearchReport
        )

        # Create second task
        analysis_task = Task(
            description="Analyze research implications",
            expected_output="Structured analysis report",
            agent=analyst,
            output_pydantic=Analysis
        )

        # Create and start the agents
        agents = AgentTeam(
            agents=[researcher, analyst],
            tasks=[research_task, analysis_task],
            process="sequential"
        )

        # Start execution
        result = agents.start()
        ```
      </Step>

      <Step title="Start Agents">
        Type this in your terminal to run your agents:

        ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
        python app.py
        ```
      </Step>
    </Steps>
  </Tab>

  <Tab title="No Code">
    <Steps>
      <Step title="Install Package">
        Install the PraisonAI package:

        ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
        pip install praisonai
        ```
      </Step>

      <Step title="Set API Key">
        Set your OpenAI API key as an environment variable in your terminal:

        ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
        export OPENAI_API_KEY=your_api_key_here
        ```
      </Step>

      <Step title="Create a file">
        Create a new file `agents.yaml` with the basic setup:

        ```yaml theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
        framework: praisonai
        process: sequential
        topic: research and analyze quantum computing
        agents:  # Canonical: use 'agents' instead of 'roles'
          researcher:
            instructions:  # Canonical: use 'instructions' instead of 'backstory' Expert in research and data collection.
            goal: Gather and structure research data
            role: Research Analyst
            tools:
              - internet_search
            tasks:
              research_task:
                description: Research quantum computing developments.
                expected_output: Structured research findings.
                output_structure:
                  type: pydantic
                  model:
                    topic: str
                    findings: str
                    sources: list[str]

          analyst:
            instructions:  # Canonical: use 'instructions' instead of 'backstory' Expert in data analysis and insights generation.
            goal: Analyze research and provide structured insights
            role: Data Analyst
            tasks:
              analysis_task:
                description: Analyze research implications.
                expected_output: Structured analysis report.
                output_structure:
                  type: pydantic
                  model:
                    key_points: list[str]
                    implications: str
                    recommendations: str
        ```
      </Step>

      <Step title="Start Agents">
        Type this in your terminal to run your agents:

        ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
        praisonai agents.yaml
        ```
      </Step>
    </Steps>
  </Tab>
</Tabs>

### Configuration Options

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# Create an agent with structured output configuration
agent = Agent(
    role="Data Analyst",
    goal="Provide structured analysis",
    backstory="Expert in data analysis",
    tools=[Tools.internet_search],
      # Enable detailed logging
    llm="gpt-4o"  # Language model to use
)

# Task with Pydantic output
task = Task(
    description="Analyze data",
    expected_output="Structured report",
    agent=agent,
    output_pydantic=AnalysisReport  # Use Pydantic model
    # or output_json=AnalysisReport  # Use JSON output
)
```

## Troubleshooting

<CardGroup cols={2}>
  <Card title="Validation Errors" icon="triangle-exclamation">
    If model validation fails:

    * Check data types match model
    * Verify required fields
    * Enable verbose mode for debugging
  </Card>

  <Card title="Output Format" icon="code">
    If output format is incorrect:

    * Verify model definition
    * Check output\_pydantic vs output\_json
    * Review field specifications
  </Card>
</CardGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="AutoAgents" icon="robot" href="./autoagents">
    Learn about automatically created and managed AI agents
  </Card>

  <Card title="Mini Agents" icon="microchip" href="./mini">
    Explore lightweight, focused AI agents
  </Card>
</CardGroup>

<Note>
  For optimal results, ensure your Pydantic models accurately represent your desired output structure.
</Note>
