Agent with Structured Outputs and Strict Tools

This example demonstrates how to use strict tool validation with structured outputs. Strict tool use ensures that tool parameters strictly follow the input schema, providing additional validation when using tools alongside structured outputs.

Code

1from kern.agent import Agent
2from kern.models.anthropic import Claude
3from kern.tools import Function
4from pydantic import BaseModel
5
6class WeatherInfo(BaseModel):
7 """Structured output schema for weather information."""
8
9 location: str
10 temperature: float
11 unit: str
12 condition: str
13
14def get_weather(location: str, unit: str = "celsius") -> str:
15 temp = 72 if unit == "fahrenheit" else 22
16 return f"Weather in {location}: {temp}°{unit}, Sunny"
17
18# Create function with strict mode enabled
19weather_tool = Function(
20 name="get_weather",
21 description="Get current weather information for a location",
22 parameters={
23 "type": "object",
24 "properties": {
25 "location": {
26 "type": "string",
27 "description": "The city and state, e.g. San Francisco, CA",
28 },
29 "unit": {
30 "type": "string",
31 "enum": ["celsius", "fahrenheit"],
32 "description": "Temperature unit",
33 },
34 },
35 "required": ["location"],
36 "additionalProperties": False,
37 },
38 strict=True, # Enable strict mode for validated tool parameters
39 entrypoint=get_weather,
40)
41
42# Agent with both structured outputs and strict tool
43agent = Agent(
44 model=Claude(id="claude-sonnet-4-5-20250929"),
45 tools=[weather_tool],
46 output_schema=WeatherInfo,
47 description="You help users get weather information.",
48)
49
50# The agent will use strict tool validation and return structured output
51agent.print_response("What's the weather like in San Francisco?")

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 ANTHROPIC_API_KEY=xxx

Install dependencies

1uv pip install -U anthropic kern-ai

Run Agent

1python structured_output_strict_tools.py