Agent with Structured Output
Code
1from typing import List23from kern.agent import Agent, RunOutput # noqa4from kern.models.ibm import WatsonX5from pydantic import BaseModel, Field6from rich.pretty import pprint # noqa78class MovieScript(BaseModel):9 setting: str = Field(10 ..., description="Provide a nice setting for a blockbuster movie."11 )12 ending: str = Field(13 ...,14 description="Ending of the movie. If not available, provide a happy ending.",15 )16 genre: str = Field(17 ...,18 description="Genre of the movie. If not available, select action, thriller or romantic comedy.",19 )20 name: str = Field(..., description="Give a name to this movie")21 characters: List[str] = Field(..., description="Name of characters for this movie.")22 storyline: str = Field(23 ..., description="3 sentence storyline for the movie. Make it exciting!"24 )2526movie_agent = Agent(27 model=WatsonX(id="mistralai/mistral-small-3-1-24b-instruct-2503"),28 description="You help people write movie scripts.",29 output_schema=MovieScript,30)3132# Get the response in a variable33# movie_agent: RunOutput = movie_agent.run("New York")34# pprint(movie_agent.content)3536movie_agent.print_response("New York")Usage
Set up your virtual environment
1uv venv --python 3.122source .venv/bin/activate1uv venv --python 3.122.venv\Scripts\activateSet your API key
1export IBM_WATSONX_API_KEY=xxx2export IBM_WATSONX_PROJECT_ID=xxxInstall dependencies
1uv pip install -U ibm-watsonx-ai pydantic rich kern-aiRun Agent
1python cookbook/11_models/ibm/watsonx/structured_output.pyThis example shows how to use structured output with IBM WatsonX. It defines a Pydantic model MovieScript with various fields and their descriptions, then creates an agent using this model as the output_schema. The model's output will be parsed into this structured format.