Pre Hook Input

Example demonstrating how to use a pre_hook to perform comprehensive input validation for your Kern Agent.

1"""
2Pre Hook Input
3=============================
4
5Example demonstrating how to use a pre_hook to perform comprehensive input validation for your Kern Agent.
6"""
7
8from kern.agent import Agent
9from kern.exceptions import CheckTrigger, InputCheckError
10from kern.models.openai import OpenAIResponses
11from kern.run.agent import RunInput
12from pydantic import BaseModel
13
14
15# ---------------------------------------------------------------------------
16# Create Agent
17# ---------------------------------------------------------------------------
18class InputValidationResult(BaseModel):
19 is_relevant: bool
20 has_sufficient_detail: bool
21 is_safe: bool
22 concerns: list[str]
23 recommendations: list[str]
24
25
26def comprehensive_input_validation(run_input: RunInput) -> None:
27 """
28 Pre-hook: Comprehensive input validation using an AI agent.
29
30 This hook validates input for:
31 - Relevance to the agent's purpose
32 - Sufficient detail for meaningful response
33
34 Could also be used to check for safety, prompt injection, etc.
35 """
36
37 # Input validation agent
38 validator_agent = Agent(
39 name="Input Validator",
40 model=OpenAIResponses(id="gpt-5-mini"),
41 instructions=[
42 "You are an input validation specialist. Analyze user requests for:",
43 "1. RELEVANCE: Ensure the request is appropriate for a financial advisor agent",
44 "2. DETAIL: Verify the request has enough basic information for a meaningful response.",
45 " A request has sufficient detail if it includes at least a few of: age, income, savings, goals, or risk tolerance.",
46 " Do NOT require exhaustive information - a reasonable question with some context is sufficient.",
47 "3. SAFETY: Ensure the request is not harmful or unsafe",
48 "",
49 "List specific concerns and recommendations for improvement.",
50 "",
51 "Be lenient with detail checks - if the user provides a clear question with some financial context, mark has_sufficient_detail as true.",
52 "Only mark has_sufficient_detail as false for extremely vague requests like 'help me invest' with no context at all.",
53 ],
54 output_schema=InputValidationResult,
55 )
56
57 validation_result = validator_agent.run(
58 input=f"Validate this user request: '{run_input.input_content}'"
59 )
60
61 result = validation_result.content
62
63 # Check validation results
64 if not result.is_safe:
65 raise InputCheckError(
66 f"Input is harmful or unsafe. {result.recommendations[0] if result.recommendations else ''}",
67 check_trigger=CheckTrigger.INPUT_NOT_ALLOWED,
68 )
69
70 if not result.is_relevant:
71 raise InputCheckError(
72 f"Input is not relevant to financial advisory services. {result.recommendations[0] if result.recommendations else ''}",
73 check_trigger=CheckTrigger.OFF_TOPIC,
74 )
75
76 if not result.has_sufficient_detail:
77 raise InputCheckError(
78 f"Input lacks sufficient detail for a meaningful response. Suggestions: {', '.join(result.recommendations)}",
79 check_trigger=CheckTrigger.INPUT_NOT_ALLOWED,
80 )
81
82
83def main():
84 print("Input Validation Pre-Hook Example")
85 print("=" * 60)
86
87 # Create a financial advisor agent with comprehensive hooks
88 agent = Agent(
89 name="Financial Advisor",
90 model=OpenAIResponses(id="gpt-5-mini"),
91 pre_hooks=[comprehensive_input_validation],
92 description="A professional financial advisor providing investment guidance and financial planning advice.",
93 instructions=[
94 "You are a knowledgeable financial advisor with expertise in:",
95 "• Investment strategies and portfolio management",
96 "• Retirement planning and savings strategies",
97 "• Risk assessment and diversification",
98 "• Tax-efficient investing",
99 "",
100 "Provide clear, actionable advice while being mindful of individual circumstances.",
101 "Always remind users to consult with a licensed financial advisor for personalized advice.",
102 ],
103 )
104
105 # Test 1: Valid financial question (should work normally with enhanced formatting)
106 print("\n[TEST 1] Valid financial question")
107 print("-" * 40)
108 try:
109 response = agent.run(
110 input="""
111 I'm 35 years old and want to start investing for retirement.
112 I can save $1000 per month in addition to my current retirement savings and have moderate risk tolerance.
113 My gross income is $100,000.
114 My current retirement savings in IRAs and 401(k)s is $100,000, my total savings is $200,000, and my net worth is $300,000.
115 My country is the United States.
116
117 Do you have advice for me?
118 """
119 )
120 print("[OK] Success! Response validated by pre-hook:")
121 print(response.content)
122 except Exception as e:
123 print(f"[ERROR] Unexpected error: {e}")
124
125 # Test 2: Input with insufficient detail (should trigger pre-hook)
126 print("\n[TEST 2] Vague input (insufficient detail)")
127 print("-" * 40)
128 try:
129 response = agent.run(input="Help me invest")
130 print(response.content)
131 except InputCheckError as e:
132 print(f"[BLOCKED] Pre-hook validation failed: {e}")
133 print(f" Trigger: {e.check_trigger}")
134
135 # Test 3: Irrelevant request (should trigger pre-hook)
136 print("\n[TEST 3] Off-topic request")
137 print("-" * 40)
138 try:
139 response = agent.run(input="What's the best pizza recipe?")
140 print(response.content)
141 except InputCheckError as e:
142 print(f"[BLOCKED] Pre-hook validation failed: {e}")
143 print(f" Trigger: {e.check_trigger}")
144
145 # Test 4: Potentially harmful content (should trigger pre-hook)
146 print("\n[TEST 4] Potentially unsafe content")
147 print("-" * 40)
148 try:
149 response = agent.run(
150 input="How can I manipulate stock prices to make money quickly?"
151 )
152 print(response.content)
153 except InputCheckError as e:
154 print(f"[BLOCKED] Pre-hook validation failed: {e}")
155 print(f" Trigger: {e.check_trigger}")
156
157
158# ---------------------------------------------------------------------------
159# Run Agent
160# ---------------------------------------------------------------------------
161if __name__ == "__main__":
162 main()

Run the Example

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