Compression Events
Test script to verify compression events are working correctly.
1"""2Compression Events3=============================45Test script to verify compression events are working correctly.6"""78import asyncio910from kern.agent import Agent11from kern.models.openai import OpenAIResponses12from kern.run.agent import RunEvent13from kern.tools.duckduckgo import DuckDuckGoTools1415# ---------------------------------------------------------------------------16# Create Agent17# ---------------------------------------------------------------------------18agent = Agent(19 model=OpenAIResponses(id="gpt-5-mini"),20 tools=[DuckDuckGoTools()],21 description="Specialized in tracking competitor activities",22 instructions="Use the search tools and always use the latest information and data.",23 compress_tool_results=True,24)252627async def main():28 print("--- Running agent with compression events ---")2930 stream = agent.arun(31 """32 Research recent activities for these AI companies:33 1. OpenAI - latest news34 2. Anthropic - latest news35 3. Google DeepMind - latest news36 """,37 stream=True,38 stream_events=True,39 )4041 async for chunk in stream:42 if chunk.event == RunEvent.run_started.value:43 print(f"[RunStarted] model={chunk.model}")4445 elif chunk.event == RunEvent.model_request_started.value:46 print(f"[ModelRequestStarted] model={chunk.model}")4748 elif chunk.event == RunEvent.model_request_completed.value:49 print(50 f"[ModelRequestCompleted] tokens: in={chunk.input_tokens}, out={chunk.output_tokens}"51 )5253 elif chunk.event == RunEvent.tool_call_started.value:54 print(f"[ToolCallStarted] {chunk.tool.tool_name}")5556 elif chunk.event == RunEvent.tool_call_completed.value:57 print(f"[ToolCallCompleted] {chunk.tool.tool_name}")5859 elif chunk.event == RunEvent.compression_started.value:60 print("[CompressionStarted]")6162 elif chunk.event == RunEvent.compression_completed.value:63 print(64 f"[CompressionCompleted] compressed={chunk.tool_results_compressed} results"65 )66 print(67 f" Original: {chunk.original_size} chars -> Compressed: {chunk.compressed_size} chars"68 )69 if chunk.original_size and chunk.compressed_size:70 ratio = (1 - chunk.compressed_size / chunk.original_size) * 10071 print(f" Compression ratio: {ratio:.1f}% reduction")7273 elif chunk.event == RunEvent.run_completed.value:74 print("[RunCompleted]")757677# ---------------------------------------------------------------------------78# Run Agent79# ---------------------------------------------------------------------------80if __name__ == "__main__":81 asyncio.run(main())Run the Example
1# Clone and setup repo2git clone https://github.com/kern-ai/kern.git3cd kern/cookbook/02_agents/14_advanced45# Create and activate virtual environment6./scripts/demo_setup.sh7source .venvs/demo/bin/activate89python compression_events.py