Basic Agent Events

Stream agent events including run lifecycle, tool calls, and content output.

Basic Agent Events.

1"""
2Basic Agent Events
3=============================
4
5Basic Agent Events.
6"""
7
8import asyncio
9
10from kern.agent import RunEvent
11from kern.agent.agent import Agent
12from kern.models.openai import OpenAIResponses
13from kern.tools.yfinance import YFinanceTools
14
15# ---------------------------------------------------------------------------
16# Create Agent
17# ---------------------------------------------------------------------------
18finance_agent = Agent(
19 id="finance-agent",
20 name="Finance Agent",
21 model=OpenAIResponses(id="gpt-5.2"),
22 tools=[YFinanceTools()],
23)
24
25
26async def run_agent_with_events(prompt: str):
27 content_started = False
28 async for run_output_event in finance_agent.arun(
29 prompt,
30 stream=True,
31 stream_events=True,
32 ):
33 if run_output_event.event in [RunEvent.run_started, RunEvent.run_completed]:
34 print(f"\nEVENT: {run_output_event.event}")
35
36 if run_output_event.event in [RunEvent.tool_call_started]:
37 print(f"\nEVENT: {run_output_event.event}")
38 print(f"TOOL CALL: {run_output_event.tool.tool_name}") # type: ignore
39 print(f"TOOL CALL ARGS: {run_output_event.tool.tool_args}") # type: ignore
40
41 if run_output_event.event in [RunEvent.tool_call_completed]:
42 print(f"\nEVENT: {run_output_event.event}")
43 print(f"TOOL CALL: {run_output_event.tool.tool_name}") # type: ignore
44 print(f"TOOL CALL RESULT: {run_output_event.tool.result}") # type: ignore
45
46 if run_output_event.event in [RunEvent.run_content]:
47 if not content_started:
48 print("\nCONTENT:")
49 content_started = True
50 else:
51 print(run_output_event.content, end="")
52
53
54# ---------------------------------------------------------------------------
55# Run Agent
56# ---------------------------------------------------------------------------
57if __name__ == "__main__":
58 asyncio.run(
59 run_agent_with_events(
60 "What is the price of Apple stock?",
61 )
62 )

Run the Example

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