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 Agent2from kern.models.anthropic import Claude3from kern.tools import Function4from pydantic import BaseModel56class WeatherInfo(BaseModel):7 """Structured output schema for weather information."""89 location: str10 temperature: float11 unit: str12 condition: str1314def get_weather(location: str, unit: str = "celsius") -> str:15 temp = 72 if unit == "fahrenheit" else 2216 return f"Weather in {location}: {temp}°{unit}, Sunny"1718# Create function with strict mode enabled19weather_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 parameters39 entrypoint=get_weather,40)4142# Agent with both structured outputs and strict tool43agent = 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)4950# The agent will use strict tool validation and return structured output51agent.print_response("What's the weather like in San Francisco?")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 ANTHROPIC_API_KEY=xxxInstall dependencies
1uv pip install -U anthropic kern-aiRun Agent
1python structured_output_strict_tools.py