Cache Model Response
Example showing how to cache model responses to avoid redundant API calls.
1"""2Cache Model Response3=============================45Example showing how to cache model responses to avoid redundant API calls.6"""78import time910from kern.agent import Agent11from kern.models.openai import OpenAIResponses1213# ---------------------------------------------------------------------------14# Create Agent15# ---------------------------------------------------------------------------16agent = Agent(model=OpenAIResponses(id="gpt-4o", cache_response=True))1718# ---------------------------------------------------------------------------19# Run Agent20# ---------------------------------------------------------------------------21if __name__ == "__main__":22 # Run the same query twice to demonstrate caching23 for i in range(1, 3):24 print(f"\n{'=' * 60}")25 print(26 f"Run {i}: {'Cache Miss (First Request)' if i == 1 else 'Cache Hit (Cached Response)'}"27 )28 print(f"{'=' * 60}\n")2930 response = agent.run(31 "Write me a short story about a cat that can talk and solve problems."32 )33 print(response.content)34 print(f"\n Elapsed time: {response.metrics.duration:.3f}s")3536 # Small delay between iterations for clarity37 if i == 1:38 time.sleep(0.5)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 cache_model_response.py