Spaces:
Build error

WordGame / CACHE_STRATEGY.md
0Mart00
Verbumix rebrand: emojis removed, multi-jurisdictional legal docs, cookie consent, footer links
9d4e305
|
Raw History Blame Contribute Delete
16.7 kB
# Prompt-alapu szo-generator cache strategia
## Problema
Ha a felhasznalok tematikus promptokat adnak meg (pl. "Star Wars") es az AI general hozza 5-betus szavakat, akkor ugyanarra a promptra tobbszor is kikuldhetjuk az AI hivast, ami:
- Penzbe kerul (AI API token koltseg)
- Lassu (API latencia: 200-2000ms)
- Rate limit aldozata lehet
A haverok tipikusan egymas utan irjak be ugyanazt a promptot. Ezt ki kell vedeni.
## Megoldas: 3 szintu cache
```
User prompt ("Star Wars")
β”‚
hash("Star Wars") "a1b2c3d4..."
β”‚
[1. szint] In-memory dict cache (TTL: 10 perc)
β”œβ”€ hit return cached word
β”‚
miss
[2. szint] Supabase `szavak` tabla (prompt_hash oszlop)
β”œβ”€ hit update memory cache + return word
β”‚
miss
[3. szint] AI API call
β”œβ”€ general szo
β”œβ”€ save to Supabase (szo + prompt_hash + kategoria)
β”œβ”€ update memory cache
└─ return word
```
---
## 1. szint: In-memory Python dict cache
A legegyszerubb, nulla fuggoseg. A FastAPI event loop alatt el, ujrainditaskor urul.
```python
# core/ai_cache.py
import time
import hashlib
from typing import Optional
# prompt_hash {"word": "VADER", "expires_at": 1717000000}
_cache: dict[str, dict] = {}
CACHE_TTL = 600 # 10 perc
def _hash_prompt(prompt: str) -> str:
"""SHA256 hash a promptbol, roviditve."""
return hashlib.sha256(prompt.lower().strip().encode()).hexdigest()[:16]
def cache_get(prompt: str) -> Optional[str]:
"""Visszaadja a cache-elt szot, ha meg nem jart le."""
key = _hash_prompt(prompt)
entry = _cache.get(key)
if entry and entry["expires_at"] > time.time():
return entry["word"]
# Lejart vagy nem letezik toroljuk
if entry:
del _cache[key]
return None
def cache_set(prompt: str, word: str) -> None:
"""Elmenti a szot a cache-be 10 percre."""
key = _hash_prompt(prompt)
_cache[key] = {
"word": word,
"expires_at": time.time() + CACHE_TTL,
}
def cache_clear() -> int:
"""Torli az osszes lejart bejegyzest. Visszaadja a torolt szamot."""
now = time.time()
expired = [k for k, v in _cache.items() if v["expires_at"] <= now]
for k in expired:
del _cache[k]
return len(expired)
```
**Elozonyok:**
- Nincs extra fuggoseg (nincs Redis, nincs `cachetools`)
- Azonnali valasz (memoriabol olvasas)
- Automatikus TTL takaritas
**Hatrany:**
- Tobb worker process (gunicorn -w 4) eseten minden workernek sajat cache-e van ugyanaz a prompt maximum 4x mehet AI-ra
- Szerver ujrainditaskor elveszik
**Megjegyzes:** A wordGame Hugging Face Space-en fut, ahol jellemzoen 1 worker van (`uvicorn` egyetlen process), igy ez a hatrany nem relevans.
---
## 2. szint: Supabase adatbazis cache
A `szavak` tablaban minden AI altal generalt szot elmentunk, hogy kesobb ujra felhasznalhato legyen.
### Adatbazis schema kiegeszites
```sql
-- A letezo `szavak` tabla bovitese AI prompt-hoz
ALTER TABLE szavak ADD COLUMN prompt_hash VARCHAR(16);
ALTER TABLE szavak ADD COLUMN ai_generated BOOLEAN DEFAULT false;
ALTER TABLE szavak ADD COLUMN prompt_text TEXT;
-- Index a gyors kereseshez
CREATE INDEX idx_szavak_prompt_hash ON szavak(prompt_hash);
CREATE INDEX idx_szavak_ai_generated ON szavak(ai_generated);
```
### Helper fuggveny
```python
# core/database.py (kiegeszites a letezo fajlhoz)
def get_cached_ai_word(prompt: str) -> Optional[str]:
"""Lekerdezi, hogy van-e mar elmentett szo erre a promptra."""
prompt_hash = hashlib.sha256(prompt.lower().strip().encode()).hexdigest()[:16]
try:
res = supabase.table(settings.TABLE_WORDS)\
.select("szo")\
.eq("prompt_hash", prompt_hash)\
.eq("ai_generated", True)\
.limit(1)\
.execute()
if res.data:
return res.data[0]["szo"].upper()
except Exception as e:
print(f"[AI-CACHE] Supabase lookup error: {e}")
return None
def save_ai_word(prompt: str, word: str, kategoria: str = "ai") -> dict:
"""Elment egy AI altal generalt szot az adatbazisba."""
prompt_hash = hashlib.sha256(prompt.lower().strip().encode()).hexdigest()[:16]
try:
# Duplikacio ellenorzes
existing = supabase.table(settings.TABLE_WORDS)\
.select("id")\
.eq("szo", word.upper())\
.eq("prompt_hash", prompt_hash)\
.execute()
if existing.data:
return existing.data[0]
res = supabase.table(settings.TABLE_WORDS)\
.insert({
"szo": word.upper(),
"kategoria": kategoria,
"prompt_hash": prompt_hash,
"prompt_text": prompt.lower().strip(),
"ai_generated": True,
})\
.execute()
return res.data[0] if res.data else {}
except Exception as e:
print(f"[AI-CACHE] Supabase insert error: {e}")
return {}
```
**Elozonyok:**
- Tul a szerver ujrainditasokon (perzisztens)
- Tobb worker is ugyanazt a cache-t hasznalja
- A generalt szavak statisztikazhatok, admin-olhatok
**Hatrany:**
- Adatbazis kor (10-50ms) minden lookupnal
- Felhalmozhat sok AI-general szot (de ez amugy is kell)
---
## 3. szint: AI API hivas (csak ha minden cache miss)
```python
# features/ai_word_generator.py
import hashlib
import time
import os
from typing import Optional
from openai import OpenAI # vagy anthropic, huggingface, stb.
from ..core.ai_cache import cache_get, cache_set
from ..core.database import get_cached_ai_word, save_ai_word, supabase
from ..core.config import settings
def get_or_generate_word(prompt: str) -> str:
"""
Haromszintu cache az AI hivasok deduplikaciojahoz.
Flow:
1. Memory cache (TTL 10 min)
2. Supabase DB (permanent)
3. AI API call
"""
prompt = prompt.strip()
if not prompt:
return "CRING" # Fallback
# 1. szint: Memory cache
cached = cache_get(prompt)
if cached:
print(f"[AI-CACHE] Memory hit: {prompt}")
return cached
# 2. szint: Database cache
cached = get_cached_ai_word(prompt)
if cached:
print(f"[AI-CACHE] DB hit: {prompt}")
cache_set(prompt, cached) # Frissitsuk a memory cache-t is
return cached
# 3. szint: AI API hivas
print(f"[AI-CACHE] AI API call: {prompt}")
word = call_ai_api(prompt)
# Mentes mindket cache-be
cache_set(prompt, word)
save_ai_word(prompt, word, kategoria="ai")
return word
def call_ai_api(prompt: str) -> str:
"""
AI API hivas. Csereld le a megfelelo providerre.
Pelda: OpenAI, Anthropic, Hugging Face Inference API,
vagy sajat LLM (llama.cpp a projektben van).
"""
# ------------------------------------------------------------------
# 1. opcio: OpenAI
# ------------------------------------------------------------------
# client = OpenAI(api_key=settings.AI_API_KEY)
# response = client.chat.completions.create(
# model="gpt-3.5-turbo",
# messages=[{
# "role": "system",
# "content": "You are a word game assistant. Generate ONE 5-letter word related to the user's prompt. Respond ONLY with the word, nothing else."
# }, {
# "role": "user",
# "content": prompt
# }],
# max_tokens=10,
# temperature=0.8,
# )
# word = response.choices[0].message.content.strip().upper()
# ------------------------------------------------------------------
# 2. opcio: Hugging Face Inference API (ingyenes tier)
# ------------------------------------------------------------------
# import httpx
# response = httpx.post(
# f"https://api-inference.huggingface.co/models/{settings.HF_MODEL}",
# headers={"Authorization": f"Bearer {settings.HF_API_KEY}"},
# json={"inputs": f"Generate one 5-letter word about: {prompt}"},
# timeout=15,
# )
# word = response.json()[0]["generated_text"].strip().upper()
# ------------------------------------------------------------------
# 3. opcio: Helyi llama.cpp (a projektben mar van)
# ------------------------------------------------------------------
# import subprocess
# result = subprocess.run(
# ["./AI/build/llama-cli", "-m", "AI/SmolLM2-135M-Instruct-Q4_K_M.gguf",
# "-p", f"Generate one 5-letter word about: {prompt}\nWord:", "-n", "10"],
# capture_output=True, text=True, timeout=30,
# )
# word = result.stdout.strip().upper()
# ------------------------------------------------------------------
# 4. opcio: Fallback (demo, AI nelkul)
# ------------------------------------------------------------------
import random
sample_words = {
"star wars": ["VADER", "FORCE", "JEDII", "SITHH", "STORM", "LIGHT", "DEATH"],
"harry potter": ["MAGIC", "WANDS", "HARRY", "SPELL", "HOGWA", "QUIDD"],
"marvel": ["STARK", "THORR", "LOKI_", "HULKK", "AVENG", "WANDA"],
"lord of the rings": ["FRODO", "GANDL", "RINGS", "MORIA", "ORCSS", "ELVES"],
}
for key, words in sample_words.items():
if key in prompt.lower():
return random.choice(words)
# Default: random angol 5-betus szo a 1000-common-bol
return _random_5letter_word()
def _random_5letter_word() -> str:
"""Visszaad egy random 5-betus angol szot a 1000-common fajlbol."""
from ..public.routes.game_routes import betoltesz_szavak_fajlbol
words = betoltesz_szavak_fajlbol("en")
ot_betus = [w for w in words if len(w) == 5]
if ot_betus:
import random
return random.choice(ot_betus)
return "BRAIN" # Ultimate fallback
```
---
## 3. szint (opcionalis): Redis
Ha tobb worker process van (pl. `gunicorn -w 4`), a memoriaban levo dict cache nem osztott. Ilyenkor Redis kell.
### docker-compose.yml kiegeszites
```yaml
services:
wordgame:
# ... meglΓ©vΕ‘ konfig ...
depends_on:
- redis
environment:
- REDIS_URL=redis://redis:6379/0
redis:
image: redis:7-alpine
restart: unless-stopped
ports:
- "6379:6379"
volumes:
- redis_data:/data
command: redis-server --appendonly yes --maxmemory 64mb --maxmemory-policy allkeys-lru
volumes:
redis_data:
```
### Redis client (requirements.txt kiegeszites)
```
redis>=5.0.0
hiredis>=2.0.0 # Opcionalis: gyorsabb parser
```
### Redis cache implementacio
```python
# core/ai_cache_redis.py
import hashlib
import json
from typing import Optional
import redis.asyncio as aioredis
_redis: Optional[aioredis.Redis] = None
CACHE_TTL = 600 # 10 perc
async def _get_redis():
global _redis
if _redis is None:
_redis = aioredis.from_url(
os.getenv("REDIS_URL", "redis://localhost:6379/0"),
decode_responses=True,
)
return _redis
async def cache_get_redis(prompt: str) -> Optional[str]:
redis = await _get_redis()
key = f"ai:word:{hashlib.sha256(prompt.lower().strip().encode()).hexdigest()[:16]}"
data = await redis.get(key)
if data:
return json.loads(data)["word"]
return None
async def cache_set_redis(prompt: str, word: str) -> None:
redis = await _get_redis()
key = f"ai:word:{hashlib.sha256(prompt.lower().strip().encode()).hexdigest()[:16]}"
await redis.setex(key, CACHE_TTL, json.dumps({"word": word}))
```
---
## Konfiguracio (config.py kiegeszites)
```python
# core/config.py – uj mezΕ‘k
# AI Cache
CACHE_TTL: int = 600 # 10 perc (masodpercben)
CACHE_TYPE: str = "memory" # "memory" | "redis" | "none"
# AI API (opcionalis)
AI_API_KEY: str = "" # OpenAI / HF token
AI_MODEL: str = "gpt-3.5-turbo" # vagy HF_INFERENCE_MODEL
AI_PROVIDER: str = "none" # "openai" | "huggingface" | "llamacpp" | "none"
AI_MAX_TOKENS: int = 10
AI_TEMPERATURE: float = 0.8
AI_TIMEOUT: int = 15 # masodperc
```
---
## Integracios pontok a letezo kodban
### 1. Dashboard – AI deck generalas (`dashboard_routes.py`)
A `create_deck` endpointben a `sample_words` helyett hivja meg az AI generatort:
```python
# Jelenlegi (statikus szavak):
words = sample_words.get(deck_req.category, sample_words["szleng"])[:deck_req.word_count]
# Atalakitva (AI-val):
words = []
for i in range(deck_req.word_count):
word = get_or_generate_word(f"{deck_req.category} word game")
if word not in words:
words.append(word)
```
### 2. Public game – AI tematikus napi szo (`game_routes.py`)
A `get_daily_word()` melle uj fuggveny:
```python
def get_ai_daily_word(prompt: str) -> str:
"""Napi szo AI prompt alapjan, cache-elve."""
today = date.today().isoformat()
full_prompt = f"{prompt} {today}"
return get_or_generate_word(full_prompt)
```
### 3. Szleng import – AI bovites (`slang_routes.py`)
Az importalt szleng szavak melle AI generalhat tovabbiakat.
---
## Flow abra (teljes)
```
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ POST /deck (create) β”‚
β”‚ { category: "star wars", word_count: 10 } β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
β”‚
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Loop i = 0..9 β”‚
β”‚ word = get_or_generate_word("star wars") β”‚
β”‚ β”‚ β”‚
β”‚ β”œβ”€ [1] Memory cache? ── hit ── return "VADER" β”‚
β”‚ β”‚ miss β”‚
β”‚ β”œβ”€ [2] Supabase DB? ─── hit ── cache[1] + ret β”‚
β”‚ β”‚ miss β”‚
β”‚ └─ [3] AI API call ─────────────────────┐ β”‚
β”‚ β”‚ β”‚ β”‚
β”‚ β”‚
β”‚ OpenAI / HF / llama.cpp save to DB β”‚
β”‚ β”‚ save to [1] β”‚
β”‚ β”‚ β”‚
β”‚ return "STORMTROOPER"[0:5] "STORM" β”€β”€β”€β”˜ β”‚
β”‚ β”‚
β”‚ Add "STORM" to deck β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```
---
## Menedzseles
### Cache torlese (ujrainditas nelkul)
```python
# Ezt meghivhatod egy admin endpointbol vagy shell-bol
from wordgame.core.ai_cache import cache_clear
deleted = cache_clear()
print(f"Cleared {deleted} expired cache entries")
```
### Monitorozas
```python
# core/ai_cache.py – kiegeszites
def cache_stats() -> dict:
"""Visszaadja a cache statisztikait."""
now = time.time()
total = len(_cache)
expired = sum(1 for v in _cache.values() if v["expires_at"] <= now)
return {
"total_entries": total,
"expired_entries": expired,
"active_entries": total - expired,
"ttl_seconds": CACHE_TTL,
}
```
### Admin endpoint (opcionalis)
```python
# private/routes/admin_routes.py – uj route
@router.get(f"/{ADMIN_PATH}/cache-stats")
async def cache_stats_endpoint(access_token: ...):
await require_admin(access_token=access_token)
from ...core.ai_cache import cache_stats, cache_clear
return {
"stats": cache_stats(),
"clear": f"POST /{settings.ADMIN_PATH}/cache-clear to clear",
}
@router.post(f"/{ADMIN_PATH}/cache-clear")
async def cache_clear_endpoint(access_token: ...):
await require_admin(access_token=access_token)
from ...core.ai_cache import cache_clear
deleted = cache_clear()
return {"cleared": deleted}
```
---
## Osszefoglalas
| Szint | Tarolas | TTL | Sebesseg | Perzisztens | Osztott |
|-------|---------|-----|----------|-------------|---------|
| 1. Memory dict | Python `dict` | 10 min | 0ms | Nem | Nem |
| 2. Supabase | PostgreSQL | Vegtelen | 10-50ms | Igen | Igen |
| 3. Redis (opt) | Redis | 10 min | 1-5ms | Opcionalis | Igen |
| AI API | - | - | 200-2000ms | - | - |
Ajanlott default: **1. + 2. szint** (memory dict + Supabase). A Redis csak akkor kell, ha 2+ worker process fut.