⚡ TL;DR — Ready-to-Deploy Automation Blueprints:
If your company is scaling an AI product, you are intimately familiar with the moment the OpenAI or Anthropic invoice drops. You look at the usage metrics and realize something agonizing: you are paying maximum token costs for the exact same answers.
Users ask "How do I reset my password?", "I forgot my password", and "Password reset help". A traditional Redis cache misses this completely because the strings aren't identical. Your backend happily forwards all three requests to the LLM, burning tokens and introducing 1-3 seconds of latency each time.
In this guide, I'll show you how to build a Semantic AI Caching Proxy using Python 3.10+, FastAPI, and local embeddings. It acts as a drop-in replacement for your LLM endpoints, intercepts similar queries, and serves cached responses in under 50ms—slashing your token waste by up to 40%.
1. The Bottleneck: Why Traditional Caching Fails
Standard caching relies on exact key-value matching. In the context of LLMs, prompts are naturally highly variable.
Commercial solutions exist for this, but they usually require heavy vendor lock-in, external network hops to a third-party vector database, or massive refactoring of your codebase to integrate their SDKs.
We need an architectural pattern that meets these criteria:
- Zero Client Refactoring: It must perfectly mimic the OpenAI API schema. You just change the
base_url in your existing app to point to localhost:8000.
- Zero Network Hop Embeddings: Embeddings must be generated locally and kept in memory to guarantee sub-50ms cache hits.
- Configurable Confidence: A tunable cosine similarity threshold (e.g.,
0.92) to decide whether to serve a cache hit or fall back to the real LLM API.
2. The Architecture
Our microservice is composed of three lightweight layers:
- The Ingress Layer (FastAPI): Exposes a
/v1/chat/completions endpoint that validates incoming requests via Pydantic.
- The Embedding Engine: Uses a lightweight, local embedding model (like
all-MiniLM-L6-v2 via the sentence-transformers library) to convert the user's prompt into a high-dimensional vector in milliseconds.
- The In-Memory Vector Cache: A Numpy-backed memory store that computes cosine similarity against historical prompts. If a match exceeds our threshold, it returns the cached completion string.
3. The Code & Logic
Let's build the core engine. First, we define our Pydantic models to mimic the OpenAI schema, ensuring a true drop-in replacement.
import asyncio
import time
import numpy as np
from fastapi import FastAPI, HTTPException, Request
from pydantic import BaseModel, Field
from sentence_transformers import SentenceTransformer
from typing import Optional, Any
import httpx
# --- Models ---
class ChatMessage(BaseModel):
role: str
content: str
class ChatCompletionRequest(BaseModel):
model: str
messages: list[ChatMessage]
temperature: Optional[float] = 1.0
# Include other standard OpenAI kwargs as needed
Next, we build the SemanticCache. To keep dependencies extremely low and performance high, we use pure Numpy for vectorized cosine similarity calculations across our cached memory.
class SemanticCache:
def __init__(self, threshold: float = 0.92):
self.threshold = threshold
self.encoder = SentenceTransformer('all-MiniLM-L6-v2')
self._vectors: list[np.ndarray] = []
self._responses: list[dict] = []
def encode(self, text: str) -> np.ndarray:
# Local, fast embedding generation
return self.encoder.encode(text, normalize_embeddings=True)
async def search(self, query_vector: np.ndarray) -> Optional[dict]:
if not self._vectors:
return None
# Stack vectors for fast matrix multiplication (cosine similarity)
matrix = np.vstack(self._vectors)
similarities = np.dot(matrix, query_vector)
best_idx = np.argmax(similarities)
if similarities[best_idx] >= self.threshold:
return self._responses[best_idx]
return None
async def store(self, query_vector: np.ndarray, response: dict):
self._vectors.append(query_vector)
self._responses.append(response)
Finally, we wire up the FastAPI routing. The proxy intercepts the request, checks the cache, and routes to OpenAI only if necessary.
app = FastAPI(title="Semantic Caching Proxy")
cache = SemanticCache(threshold=0.95)
OPENAI_API_KEY = "sk-..." # Load from env in production
@app.post("/v1/chat/completions")
async def proxy_chat_completions(req: ChatCompletionRequest):
# Extract the last user message for semantic matching
user_messages = [m.content for m in req.messages if m.role == "user"]
if not user_messages:
raise HTTPException(status_code=400, detail="No user message found.")
latest_prompt = user_messages[-1]
# 1. Encode locally
query_vector = cache.encode(latest_prompt)
# 2. Check Semantic Cache
start_time = time.time()
cached_response = await cache.search(query_vector)
if cached_response:
# Add a custom header or flag to indicate a cache hit
cached_response["system_fingerprint"] = "semantic-cache-hit"
print(f"Cache Hit! Latency: {(time.time() - start_time)*1000:.2f}ms")
return cached_response
# 3. Cache Miss: Forward to real LLM provider
async with httpx.AsyncClient() as client:
response = await client.post(
"https://api.openai.com/v1/chat/completions",
headers={"Authorization": f"Bearer {OPENAI_API_KEY}"},
json=req.model_dump(exclude_none=True),
timeout=60.0
)
if response.status_code != 200:
raise HTTPException(status_code=response.status_code, detail=response.text)
llm_data = response.json()
# 4. Store the successful response in cache
await cache.store(query_vector, llm_data)
return llm_data
To run this in production, you'll want to wrap it in a Docker container and serve it via Uvicorn:
uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4
Production Considerations:
- Memory Management: The simple list-based cache above will grow indefinitely. In a production environment, you must implement an LRU (Least Recently Used) eviction policy or cap the vector matrix size (e.g., max 10,000 vectors) to prevent OOM errors.
- Concurrency: Because
SentenceTransformer encoding is CPU-bound, running multiple Uvicorn workers ensures that embedding generation doesn't block the async event loop for other incoming requests.
- Timeouts & Retries: The
httpx client is configured with a 60-second timeout. In a robust microservice, you should wrap the external API call in a tenacity retry block to handle OpenAI rate limits (HTTP 429).
5. Conclusion & Turnkey Package
By placing this lightweight Python microservice between your application and your LLM provider, you instantly gain semantic caching. Your client code requires zero refactoring—just point your OpenAI SDK's base_url to http://localhost:8000/v1.
You can take the code above, add your own eviction logic, write the test suite, and deploy it to your infrastructure.
However, if you want to skip the boilerplate and instantly deploy a battle-tested, production-ready version of this architecture, I've packaged the complete Semantic AI Caching Proxy.
The turnkey package includes the full Python 3.10+ CLI tool, advanced LRU memory management, automated test suites, Dockerfiles, and configuration templates for immediate deployment.
Grab the production-ready engine here:
Stop paying for the same tokens twice. Optimize your API layer today.
🛠️ D'autres outils MR Studio qui pourraient vous intéresser :