tall-fountain-87900
12/04/2025, 9:54 AMtall-airline-16756
12/04/2025, 9:55 AMtall-airline-16756
12/04/2025, 9:55 AMhashlib.md5((user_input + context).encode()).hexdigest()
• Include any flags that affect output (temperature, system prompts) so keys reflect generation differences.
1. Wrap LLM calls
• Before calling Gemini, check cache[key]:
◦ If present and still valid, return cached response.
◦ If missing, call the LLM, store the response and metadata (timestamp, TTL, context version), then return it.
1. Handle cache lifetime & invalidation
• Use TTLs appropriate for your app (short for dynamic dialogs, longer for static FAQ answers).
• Optionally store context version or conversation IDs to avoid returning stale context-sensitive answers.
Minimal example (Python-like pseudocode)
import hashlib
import time
CACHE = {} # replace with Redis client in prod
def make_cache_key(user_input, context, llm_params):
raw = user_input + "|" + context + "|" + str(llm_params)
return hashlib.md5(raw.encode()).hexdigest()
def get_from_cache(key):
entry = CACHE.get(key)
if not entry: return None
if time.time() - entry["ts"] > entry["ttl"]:
CACHE.pop(key, None)
return None
return entry["response"]
def set_cache(key, response, ttl=60):
CACHE[key] = {"response": response, "ts": time.time(), "ttl": ttl}
def llm_with_cache(user_input, context="", llm_params=None, ttl=60):
key = make_cache_key(user_input, context, llm_params or {})
cached = get_from_cache(key)
if cached:
return cached
# call Gemini LLM here (your existing call)
resp = llm.generate(prompt=user_input, **(llm_params or {}))
set_cache(key, resp, ttl=ttl)
return resp
Where to integrate in your AgentSession
• Replace direct calls to google.LLM(...).generate(...) (or whatever method your SDK uses) with llm_with_cache(...).
• Keep session-level state (conversation history) out of the cache key unless you explicitly want responses tied to that exact history.
• For partial-response or streaming generation, cache only final assembled responses.
Caveats and recommendations
• Avoid caching highly context-dependent or private/personalized responses unless you include full relevant context in the key.
• For multi-turn agents, prefer caching for repeated identical prompts (FAQs, static instructions) and not for dynamic natural conversation unless you carefully include conversation state.
• Use Redis with expirations and optional LRU policies for production.
If you want, tell me:
• whether you prefer an in-memory example or a Redis example,
• which Gemini call/SDK method you use to invoke the model,
and I’ll give a concrete code snippet adapted to your environment.
Sources: Agent session | LiveKit docs | Building an Automated IVR Menu Caller | LiveKit docs