Stream Hook
Example demonstrating sending a notification to the user after an agent generates a response.
1"""2Stream Hook3=============================45Example demonstrating sending a notification to the user after an agent generates a response.6"""78import asyncio910from kern.agent import Agent11from kern.models.openai import OpenAIResponses12from kern.run import RunContext13from kern.run.agent import RunOutput14from kern.tools.yfinance import YFinanceTools151617def send_notification(run_output: RunOutput, run_context: RunContext) -> None:18 """19 Post-hook: Send a notification to the user.20 """21 if run_context.metadata is None:22 return23 email = run_context.metadata.get("email")24 if email:25 send_email(email, run_output.content)262728def send_email(email: str, content: str) -> None:29 """30 Send an email to the user. Mock, just for the example.31 """32 print(f"Sending email to {email}: {content}")333435# ---------------------------------------------------------------------------36# Create Agent37# ---------------------------------------------------------------------------38async def main():39 # Agent with comprehensive output validation4041 # ---------------------------------------------------------------------------42 # Create Agent43 # ---------------------------------------------------------------------------4445 agent = Agent(46 name="Financial Report Agent",47 model=OpenAIResponses(id="gpt-5-mini"),48 post_hooks=[send_notification],49 tools=[YFinanceTools()],50 instructions=[51 "You are a helpful financial report agent.",52 "Generate a financial report for the given company.",53 "Keep it short and concise.",54 ],55 )5657 # Run the agent58 await agent.aprint_response(59 "Generate a financial report for Apple (AAPL).",60 user_id="user_123",61 metadata={"email": "test@example.com"},62 stream=True,63 )646566# ---------------------------------------------------------------------------67# Run Agent68# ---------------------------------------------------------------------------69if __name__ == "__main__":70 asyncio.run(main())Run the Example
1# Clone and setup repo2git clone https://github.com/kern-ai/kern.git3cd kern/cookbook/02_agents/09_hooks45# Create and activate virtual environment6./scripts/demo_setup.sh7source .venvs/demo/bin/activate89python stream_hook.py