Define a schema
from pydantic import BaseModel, Field
class MovieReview(BaseModel):
title: str = Field(description="The title of the movie")
rating: int = Field(ge=1, le=10, description="Rating from 1-10")
genre: str = Field(description="The movie's genre(s)")
summary: str = Field(description="A brief summary of the movie")
pros: list[str] = Field(description="List of positive aspects")
cons: list[str] = Field(description="List of negative aspects")
recommendation: str = Field(description="Who should watch this movie")
import { z } from 'zod';
const movieReviewSchema = z.object({
title: z.string().describe('The title of the movie'),
rating: z.number().int().min(1).max(10).describe('Rating from 1-10'),
genre: z.string().describe("The movie's genre(s)"),
summary: z.string().describe('A brief summary of the movie'),
pros: z.array(z.string()).describe('List of positive aspects'),
cons: z.array(z.string()).describe('List of negative aspects'),
recommendation: z.string().describe('Who should watch this movie'),
});
type MovieReview = z.infer<typeof movieReviewSchema>;
Create an agent with the schema
from polos import Agent
movie_reviewer = Agent(
id="movie_reviewer",
provider="openai",
model="gpt-4o-mini",
system_prompt="You are a professional movie critic. Provide comprehensive reviews.",
output_schema=MovieReview, # Pydantic model for structured output
)
import { defineAgent, maxSteps } from '@polos/sdk';
import { openai } from '@ai-sdk/openai';
const movieReviewer = defineAgent({
id: 'movie_reviewer',
model: openai('gpt-4o-mini'),
systemPrompt: 'You are a professional movie critic. Provide comprehensive reviews.',
outputSchema: movieReviewSchema,
stopConditions: [maxSteps({ count: 5 })],
});
Get typed responses
result = await movie_reviewer.run(polos, "Review the movie 'The Matrix'")
# result.result is a validated MovieReview instance
print(result.result.title) # "The Matrix"
print(result.result.rating) # 9
print(result.result.pros) # ["Innovative visual effects", ...]
const result = await movieReviewer.run(polos, {
input: "Review the movie 'The Matrix'",
});
// result.result is a validated MovieReview object
console.log(result.result);
Run it
git clone https://github.com/polos-dev/polos.git
cd polos/python-examples/02-structured-output
cp .env.example .env # Add your POLOS_PROJECT_ID and OPENAI_API_KEY
uv sync
python main.py
git clone https://github.com/polos-dev/polos.git
cd polos/typescript-examples/02-structured-output
cp .env.example .env # Add your POLOS_PROJECT_ID and OPENAI_API_KEY
npm install
npx tsx main.ts