Agent with Structured Outputs

Code

1import asyncio
2from typing import List
3
4from kern.agent import Agent
5from kern.models.lmstudio import LMStudio
6from pydantic import BaseModel, Field
7
8class MovieScript(BaseModel):
9 name: str = Field(..., description="Give a name to this movie")
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 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 )
25
26# Agent that returns a structured output
27structured_output_agent = Agent(
28 model=LMStudio(id="qwen2.5-7b-instruct-1m"),
29 description="You write movie scripts.",
30 output_schema=MovieScript,
31)
32
33# Run the agent synchronously
34structured_output_agent.print_response("New York")

Usage

Set up your virtual environment

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

Install LM Studio

Install LM Studio from here and download the model you want to use.

Install dependencies

1uv pip install -U kern-ai

Run Agent

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