cache_model_response.py
Run the Example
1
Set up your virtual environment
2
Install dependencies
3
Export your OpenAI API key
4
Run the example
Save the code above as
cache_model_response.py, then run:Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Example showing how to cache model responses to avoid redundant API calls.
"""
Cache Model Response
=============================
Example showing how to cache model responses to avoid redundant API calls.
"""
import time
from agno.agent import Agent
from agno.models.openai import OpenAIResponses
# ---------------------------------------------------------------------------
# Create Agent
# ---------------------------------------------------------------------------
agent = Agent(model=OpenAIResponses(id="gpt-4o", cache_response=True))
# ---------------------------------------------------------------------------
# Run Agent
# ---------------------------------------------------------------------------
if __name__ == "__main__":
# Run the same query twice to demonstrate caching
for i in range(1, 3):
print(f"\n{'=' * 60}")
print(
f"Run {i}: {'Cache Miss (First Request)' if i == 1 else 'Cache Hit (Cached Response)'}"
)
print(f"{'=' * 60}\n")
response = agent.run(
"Write me a short story about a cat that can talk and solve problems."
)
print(response.content)
print(f"\n Elapsed time: {response.metrics.duration:.3f}s")
# Small delay between iterations for clarity
if i == 1:
time.sleep(0.5)
Set up your virtual environment
uv venv --python 3.12
source .venv/bin/activate
uv venv --python 3.12
.venv\Scripts\activate
Install dependencies
uv pip install -U agno openai
Export your OpenAI API key
export OPENAI_API_KEY="your_openai_api_key_here"
$Env:OPENAI_API_KEY="your_openai_api_key_here"
Run the example
cache_model_response.py, then run:python cache_model_response.py
Was this page helpful?