Structured Output

Code

1from typing import List
2
3from kern.agent import Agent, RunOutput # noqa
4from kern.models.mistral import MistralChat
5from kern.tools.hackernews import HackerNewsTools
6from pydantic import BaseModel, Field
7from rich.pretty import pprint # noqa
8
9class MovieScript(BaseModel):
10 setting: str = Field(
11 ..., description="Provide a nice setting for a blockbuster movie."
12 )
13 ending: str = Field(
14 ...,
15 description="Ending of the movie. If not available, provide a happy ending.",
16 )
17 genre: str = Field(
18 ...,
19 description="Genre of the movie. If not available, select action, thriller or romantic comedy.",
20 )
21 name: str = Field(..., description="Give a name to this movie")
22 characters: List[str] = Field(..., description="Name of characters for this movie.")
23 storyline: str = Field(
24 ..., description="3 sentence storyline for the movie. Make it exciting!"
25 )
26
27structured_output_agent = Agent(
28 model=MistralChat(
29 id="mistral-large-latest",
30 ),
31 tools=[HackerNewsTools()],
32 description="You help people write movie scripts.",
33 output_schema=MovieScript,
34)
35
36# Get the response in a variable
37structured_output_response: RunOutput = structured_output_agent.run("New York")
38pprint(structured_output_response.content)

Usage

Set up your virtual environment

1uv venv --python 3.12
2source .venv/bin/activate
1uv venv --python 3.12
2.venv\Scripts\activate

Set your API key

1export MISTRAL_API_KEY=xxx

Install dependencies

1uv pip install -U mistralai kern-ai

Run Agent

1python cookbook/11_models/mistral/structured_output.py