Output Guardrail

Validate and constrain agent output with guardrails.

Output Guardrail.

1"""
2Output Guardrail
3=============================
4
5Output Guardrail.
6"""
7
8from kern.agent import Agent
9from kern.exceptions import CheckTrigger, OutputCheckError
10from kern.models.openai import OpenAIResponses
11from kern.run.agent import RunOutput
12
13
14def enforce_non_empty_output(run_output: RunOutput) -> None:
15 """Reject empty or very short responses."""
16 content = (run_output.content or "").strip()
17 if len(content) < 20:
18 raise OutputCheckError(
19 "Output is too short to be useful.",
20 check_trigger=CheckTrigger.OUTPUT_NOT_ALLOWED,
21 )
22
23
24# ---------------------------------------------------------------------------
25# Create Agent
26# ---------------------------------------------------------------------------
27agent = Agent(
28 name="Output-Checked Agent",
29 model=OpenAIResponses(id="gpt-5.2"),
30 post_hooks=[enforce_non_empty_output],
31)
32
33# ---------------------------------------------------------------------------
34# Run Agent
35# ---------------------------------------------------------------------------
36if __name__ == "__main__":
37 agent.print_response("Summarize the key ideas in clean architecture.", stream=True)

Run the Example

1# Clone and setup repo
2git clone https://github.com/kern-ai/kern.git
3cd kern/cookbook/02_agents/08_guardrails
4
5# Create and activate virtual environment
6./scripts/demo_setup.sh
7source .venvs/demo/bin/activate
8
9python output_guardrail.py