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

# Use structured outputs

> Control the format of agent responses using Pydantic models or JSON schemas.

Structured outputs use a Pydantic `BaseModel` or JSON schema to enforce a response format on your agent, giving you typed, integration-ready data without extra parsing or post-processing. Use them when agent responses feed directly into external systems like APIs or databases, or when extracting structured information from unstructured content like documents and emails.

## Define a schema with Pydantic

Define a Pydantic model in the `response_format` parameter:

**Endpoint:** `POST /v1/threads/{thread_id}/runs` [Run agent](/flow/reference/run_agent_v1_threads__thread_id__runs_post)

<CodeGroup>
  ```python Python theme={null}
  from pydantic import BaseModel, Field
  from typing import List
  from seekrai import SeekrFlow

  class ProductReview(BaseModel):
      product_name: str = Field(description="The full product name as listed")
      pros: List[str] = Field(description="List of positive aspects, maximum 3 items")
      cons: List[str] = Field(description="List of negative aspects, maximum 3 items")
      recommended: bool = Field(description="Whether the reviewer recommends this product")

  # Use structured output with your agent
  result = client.agents.runs.run(
      agent_id="your-agent-id",
      thread_id=thread.id,
      response_format=ProductReview
  )
  ```
</CodeGroup>

## Define nested Pydantic objects

You can also define multiple levels of Pydantic classes:

**Endpoint:** `POST /v1/threads/{thread_id}/runs` [Run agent](/flow/reference/run_agent_v1_threads__thread_id__runs_post)

<CodeGroup>
  ```python Python expandable theme={null}
  from pydantic import BaseModel, Field
  from typing import List
  from seekrai import SeekrFlow

  # Define nested objects first
  class ReviewerInfo(BaseModel):
      name: str
      verified_purchase: bool
      review_date: str

  class ProductSpecs(BaseModel):
      brand: str
      model: str
      price: float
      category: str

  # Main object that includes nested objects
  class ProductReview(BaseModel):
      product_name: str = Field(description="The full product name as listed")
      specs: ProductSpecs = Field(description="Technical specifications of the product")
      reviewer: ReviewerInfo = Field(description="Information about the reviewer")
      pros: List[str] = Field(description="List of positive aspects, maximum 3 items")
      cons: List[str] = Field(description="List of negative aspects, maximum 3 items")
      recommended: bool = Field(description="Whether the reviewer recommends this product")

  # Use structured output with your agent
  result = client.agents.runs.run(
      agent_id="your-agent-id",
      thread_id=thread.id,
      response_format=ProductReview
  )

  # Agent will return nested data matching this structure:
  # {
  #   "product_name": "Wireless Headphones",
  #   "specs": {
  #     "brand": "Sony",
  #     "model": "WH-1000XM4",
  #     "price": 299.99,
  #     "category": "Electronics"
  #   },
  #   "reviewer": {
  #     "name": "John Smith",
  #     "verified_purchase": true,
  #     "review_date": "2024-01-15"
  #   },
  #   "pros": ["Great sound quality", "Long battery life"],
  #   "cons": ["Expensive", "Heavy"],
  #   "recommended": true
  # }
  ```
</CodeGroup>

## Handle validation errors

When the agent cannot map its response to the defined schema, a validation error is returned.

**Endpoint:** `POST /v1/threads/{thread_id}/runs` [Run agent](/flow/reference/run_agent_v1_threads__thread_id__runs_post)

<CodeGroup>
  ```python Python theme={null}
  # Validation Error - 422
  {
    "error": "Value Error",
    "feedVersion": "1.0.0",
    "message": "Value error, Response format JSON schema could not be validated: <error>",
    "requestUrl": "https://services-api.seekr.com/v1/agents/runs",
    "status": 422
  }
  ```
</CodeGroup>

If you receive a validation error, handle the error as shown:

<CodeGroup>
  ```python Python expandable theme={null}
  from seekrai import SeekrFlow
  from pydantic import BaseModel, Field
  from typing import List

  class ProductReview(BaseModel):
      product_name: str
      specs: ProductSpecs           # Nested object
      reviewer: ReviewerInfo        # Nested object
      pros: List[str]
      cons: List[str]
      recommended: bool

  try:
      result = client.agents.runs.run(
          agent_id="your-agent-id",
          thread_id=thread.id,
          response_format=ProductReview
      )
      print(result)
  except Exception as e:
      print("Structured output validation failed:", str(e))
  ```
</CodeGroup>

## Improve schema accuracy

When using structured outputs, we recommend the following:

1. **Keep schemas simple and focused.** Complex structures with excessive fields or deep nesting can reduce model accuracy. Limit nesting to one level deep. While multiple levels are supported, single-level nesting produces the most consistent results.
2. **Use clear field names.** Choose descriptive field names that help the model accurately map response content to your schema. For example, `customer_email` is clearer than `email`, and `total_price_usd` is clearer than `price`.
3. **Use few-shot prompting.** Include examples in your agent's instructions to guide accurate field mapping. Sample inputs and expected outputs help the model understand how to structure its response.
4. **Test your schemas thoroughly.** Validate your schemas against real queries and edge cases before deploying. Test with a range of input types to ensure consistent results.
