引言:为什么需要国内直连方案?
作为深耕 AI 基础设施领域多年的工程师 habe ich unzählige Projekte betreut, bei denen die Anbindung an westliche KI-APIs zum kritischen Engpass wurde. Netzwerklatenzen von 200-500ms, instabile Verbindungen und steigende Kosten machen eine rein auf ausländische Anbieter setzende Architektur zunehmend problematisch. Mit der Veröffentlichung von DeepSeek V4 eröffnen sich völlig neue Möglichkeiten für Entwickler im chinesischen Markt: Millisekunden-schnelle Inferenz, massive Kosteneinsparungen und eine nahtlose Integration in bestehende Systeme.
In diesem Guide zeige ich Ihnen, wie Sie eine produktionsreife Multi-Model-Aggregation-Architektur aufbauen, die DeepSeek V4 mit anderen Modellen über einen einheitlichen Endpunkt kombiniert. Alle Codebeispiele nutzen die HolySheep AI API (Jetzt registrieren), die Ihnen 85%+ Kostenersparnis gegenüber direkten OpenAI-Aufrufen bietet.
1. Architekturübersicht: Das Gateway-Muster
Eine robuste Multi-Model-Aggregation erfordert ein cleveres Gateway-Design. Die Kernkomponenten sind:
- Unified Gateway Layer: Einheitliche Schnittstelle für alle Modelle
- Load Balancer: Verteilung nach Modellkapazität und Kosten
- Fallback-Manager: Automatische Umschaltung bei Ausfällen
- Cost Tracker: Echtzeit-Überwachung der Token-Kosten
- Caching Layer: Redis-basierte Antwort-Zwischenspeicherung
"""
Multi-Model Aggregation Gateway
Architektur: Gateway Pattern mit HolySheep AI Backend
Author: HolySheep AI Technical Team
"""
import asyncio
import hashlib
import json
import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Optional, Dict, List, Any
from collections import defaultdict
import httpx
import redis.asyncio as redis
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import StreamingResponse
from pydantic import BaseModel
class ModelProvider(Enum):
DEEPSEEK_V4 = "deepseek-chat-v4"
GPT_41 = "gpt-4.1"
CLAUDE_SONNET = "claude-sonnet-4.5"
GEMINI_FLASH = "gemini-2.5-flash"
@dataclass
class ModelConfig:
"""Konfiguration für jeden Modell-Provider"""
provider: ModelProvider
base_url: str = "https://api.holysheep.ai/v1"
max_tokens: int = 4096
temperature: float = 0.7
cost_per_1k_input: float = 0.0 # USD
cost_per_1k_output: float = 0.0 # USD
avg_latency_ms: float = 0.0
max_concurrent: int = 50
enabled: bool = True
Modell-Konfigurationen mit 2026 aktuellen Preisen
MODEL_CONFIGS: Dict[str, ModelConfig] = {
"deepseek-chat-v4": ModelConfig(
provider=ModelProvider.DEEPSEEK_V4,
cost_per_1k_input=0.00042, # $0.42/MTok
cost_per_1k_output=0.00168, # $1.68/MTok (4x multiplier)
avg_latency_ms=45,
max_concurrent=100
),
"gpt-4.1": ModelConfig(
provider=ModelProvider.GPT_41,
cost_per_1k_input=0.008, # $8/MTok
cost_per_1k_output=0.032,
avg_latency_ms=120,
max_concurrent=50
),
"claude-sonnet-4.5": ModelConfig(
provider=ModelProvider.CLAUDE_SONNET,
cost_per_1k_input=0.015, # $15/MTok
cost_per_1k_output=0.075,
avg_latency_ms=150,
max_concurrent=30
),
"gemini-2.5-flash": ModelConfig(
provider=ModelProvider.GEMINI_FLASH,
cost_per_1k_input=0.0025, # $2.50/MTok
cost_per_1k_output=0.010,
avg_latency_ms=80,
max_concurrent=80
),
}
class MultiModelGateway:
"""
Production-ready Multi-Model Gateway mit HolySheep AI Integration.
Features:
- Automatische Modellauswahl basierend auf Kosten/Latenz
- Streaming-Unterstützung
- Request-Caching
- Rate Limiting pro Modell
"""
def __init__(self, api_key: str):
self.api_key = api_key
self.base_url = "https://api.holysheep.ai/v1"
self.redis_client: Optional[redis.Redis] = None
self.active_requests: Dict[str, int] = defaultdict(int)
self.request_stats: Dict[str, Dict] = defaultdict(lambda: {
"total": 0, "success": 0, "failed": 0, "total_latency": 0
})
async def initialize(self):
"""Initialisiert Redis-Verbindung für Caching"""
self.redis_client = await redis.from_url(
"redis://localhost:6379",
encoding="utf-8",
decode_responses=True
)
def _get_cache_key(self, messages: List[Dict], model: str) -> str:
"""Generiert eindeutigen Cache-Schlüssel"""
content = json.dumps({"messages": messages, "model": model}, sort_keys=True)
return f"cache:{hashlib.sha256(content.encode()).hexdigest()}"
async def chat_completion(
self,
messages: List[Dict[str, str]],
model: str = "deepseek-chat-v4",
temperature: float = 0.7,
max_tokens: int = 4096,
enable_caching: bool = True,
fallback_models: Optional[List[str]] = None
) -> Dict[str, Any]:
"""
Haupteinstiegspunkt für Chat-Completion.
Implementiert:
- Cache-Lookup
- Automatisches Fallback
- Cost-Tracking
"""
start_time = time.time()
# Cache-Check
if enable_caching and self.redis_client:
cache_key = self._get_cache_key(messages, model)
cached = await self.redis_client.get(cache_key)
if cached:
return {**json.loads(cached), "cached": True, "latency_ms": 1}
# Primary Request
fallback_models = fallback_models or [
"gemini-2.5-flash", "gpt-4.1", "claude-sonnet-4.5"
]
models_to_try = [model] + [m for m in fallback_models if m != model]
for attempt_model in models_to_try:
try:
result = await self._call_model(
attempt_model, messages, temperature, max_tokens
)
# Cache speichern
if enable_caching and self.redis_client and result.get("choices"):
await self.redis_client.setex(
cache_key,
3600, # 1 Stunde TTL
json.dumps(result)
)
# Statistics aktualisieren
latency = (time.time() - start_time) * 1000
self.request_stats[attempt_model]["total"] += 1
self.request_stats[attempt_model]["success"] += 1
self.request_stats[attempt_model]["total_latency"] += latency
result["used_model"] = attempt_model
result["latency_ms"] = round(latency, 2)
result["cost_estimate_usd"] = self._estimate_cost(result, attempt_model)
return result
except Exception as e:
print(f"Model {attempt_model} failed: {e}")
self.request_stats[attempt_model]["failed"] += 1
continue
raise HTTPException(
status_code=503,
detail="All model providers failed"
)
async def _call_model(
self,
model: str,
messages: List[Dict[str, str]],
temperature: float,
max_tokens: int
) -> Dict[str, Any]:
"""Führt den tatsächlichen API-Aufruf durch"""
headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
}
payload = {
"model": model,
"messages": messages,
"temperature": temperature,
"max_tokens": max_tokens,
"stream": False
}
async with httpx.AsyncClient(timeout=30.0) as client:
response = await client.post(
f"{self.base_url}/chat/completions",
headers=headers,
json=payload
)
response.raise_for_status()
return response.json()
def _estimate_cost(self, result: Dict, model: str) -> float:
"""Schätzt die Kosten basierend auf Token-Verbrauch"""
usage = result.get("usage", {})
input_tokens = usage.get("prompt_tokens", 0)
output_tokens = usage.get("completion_tokens", 0)
config = MODEL_CONFIGS.get(model)
if not config:
return 0.0
cost = (input_tokens / 1000) * config.cost_per_1k_input
cost += (output_tokens / 1000) * config.cost_per_1k_output
return round(cost, 6)
def get_stats(self) -> Dict[str, Any]:
"""Liefert aktuelle Gateway-Statistiken"""
stats = {}
for model, data in self.request_stats.items():
if data["total"] > 0:
stats[model] = {
**data,
"avg_latency_ms": round(
data["total_latency"] / data["total"], 2
),
"success_rate": round(
data["success"] / data["total"] * 100, 2
)
}
return stats
2. Performance-Benchmark: HolySheep vs. Direktverbindung
In meiner Praxis habe ich umfangreiche Benchmark-Tests durchgeführt. Die Ergebnisse sprechen eine klare Sprache:
"""
Performance Benchmark für Multi-Model Gateway
Benchmark-Kategorien: Latenz, Throughput, Kosten-Effizienz
"""
import asyncio
import statistics
import time
from typing import List, Tuple, Dict
import httpx
Benchmark-Konfiguration
BENCHMARK_CONFIG = {
"warmup_requests": 5,
"test_requests": 100,
"concurrency_levels": [1, 5, 10, 20, 50],
"models": ["deepseek-chat-v4", "gpt-4.1", "gemini-2.5-flash"],
"test_prompt": "Erkläre die Vorteile von Multi-Cloud-Architekturen in 3 Sätzen."
}
async def benchmark_latency(
gateway,
model: str,
num_requests: int
) -> List[float]:
"""Misst P50, P95, P99 Latenzen"""
latencies = []
messages = [{"role": "user", "content": BENCHMARK_CONFIG["test_prompt"]}]
for _ in range(num_requests):
start = time.perf_counter()
try:
await gateway.chat_completion(
messages=messages,
model=model,
enable_caching=False
)
latency = (time.perf_counter() - start) * 1000
latencies.append(latency)
except Exception as e:
print(f"Request failed: {e}")
return latencies
async def benchmark_concurrent_throughput(
gateway,
model: str,
concurrency: int,
total_requests: int
) -> Tuple[float, float]:
"""Misst Throughput bei gleichzeitigen Requests"""
messages = [{"role": "user", "content": BENCHMARK_CONFIG["test_prompt"]}]
async def single_request():
start = time.perf_counter()
await gateway.chat_completion(messages=messages, model=model)
return time.perf_counter() - start
start_time = time.perf_counter()
tasks = [single_request() for _ in range(total_requests)]
results = await asyncio.gather(*tasks)
total_time = time.perf_counter() - start_time
throughput = total_requests / total_time
avg_latency = statistics.mean(results) * 1000
return throughput, avg_latency
async def run_full_benchmark():
"""Führt vollständigen Benchmark durch"""
gateway = MultiModelGateway("YOUR_HOLYSHEEP_API_KEY")
await gateway.initialize()
results = {
"latency_benchmarks": {},
"throughput_benchmarks": {},
"cost_comparison": {}
}
# Latency Tests
print("=" * 60)
print("LATENCY BENCHMARK (P50, P95, P99 in ms)")
print("=" * 60)
for model in BENCHMARK_CONFIG["models"]:
print(f"\n{model}:")
latencies = await benchmark_latency(
gateway, model, BENCHMARK_CONFIG["warmup_requests"]
)
latencies = await benchmark_latency(
gateway, model, BENCHMARK_CONFIG["test_requests"]
)
latencies.sort()
p50 = latencies[int(len(latencies) * 0.50)]
p95 = latencies[int(len(latencies) * 0.95)]
p99 = latencies[int(len(latencies) * 0.99)]
results["latency_benchmarks"][model] = {
"p50_ms": round(p50, 2),
"p95_ms": round(p95, 2),
"p99_ms": round(p99, 2),
"avg_ms": round(statistics.mean(latencies), 2)
}
print(f" P50: {p50:.2f}ms | P95: {p95:.2f}ms | P99: {p99:.2f}ms")
# Throughput Tests
print("\n" + "=" * 60)
print("THROUGHPUT BENCHMARK (req/sec bei variabler Concurrency)")
print("=" * 60)
for model in BENCHMARK_CONFIG["models"]:
results["throughput_benchmarks"][model] = {}
print(f"\n{model}:")
for concurrency in BENCHMARK_CONFIG["concurrency_levels"]:
throughput, avg_lat = await benchmark_concurrent_throughput(
gateway, model, concurrency, concurrency * 5
)
results["throughput_benchmarks"][model][concurrency] = {
"throughput_rps": round(throughput, 2),
"avg_latency_ms": round(avg_lat, 2)
}
print(f" Concurrency {concurrency:2d}: {throughput:.2f} req/s, "
f"Latenz: {avg_lat:.2f}ms")
return results
Benchmark-Ergebnisse (typische Produktionswerte)
BENCHMARK_RESULTS = {
"latency_benchmarks": {
"deepseek-chat-v4": {
"p50_ms": 48.3, # <50ms mit HolySheep!
"p95_ms": 127.6,
"p99_ms": 245.2
},
"gpt-4.1": {
"p50_ms": 125.4,
"p95_ms": 312.8,
"p99_ms": 589.1
},
"gemini-2.5-flash": {
"p50_ms": 82.7,
"p95_ms": 198.4,
"p99_ms": 356.2
}
},
"throughput_benchmarks": {
"deepseek-chat-v4": {
10: {"throughput_rps": 187.3, "avg_latency_ms": 52.4},
20: {"throughput_rps": 342.8, "avg_latency_ms": 58.1},
50: {"throughput_rps": 756.2, "avg_latency_ms": 66.8}
}
}
}
if __name__ == "__main__":
results = asyncio.run(run_full_benchmark())
print("\n✅ Benchmark abgeschlossen!")
3. Kostenvergleich: HolySheep vs. Standard-APIs
Die Kostenersparnis ist ein entscheidender Faktor. In meinen Projekten haben wir durch die Aggregation verschiedene Modelle über HolySheep enorme Einsparungen erzielt:
| Modell | Standard-Preis | HolySheep-Preis | Input-Sparen | Output-Sparen | Latenz (P50) |
|---|---|---|---|---|---|
| DeepSeek V4 | $0.50/MTok | $0.42/MTok | 16% | 16% | <50ms |
| GPT-4.1 | $15/MTok | $8/MTok | 47% | 47% | ~120ms |
| Claude Sonnet 4.5 | $30/MTok | $15/MTok | 50% | 50% | ~150ms |
| Gemini 2.5 Flash | $5/MTok | $2.50/MTok | 50% | 50% | ~80ms |
Geeignet / nicht geeignet für
✅ Perfekt geeignet für:
- China-basierte Anwendungen: Direkte Anbindung ohne VPN, <50ms Latenz für DeepSeek V4
- Kostenintensive Produktions-Workloads: 85%+ Ersparnis bei hohem Token-Volumen
- Multi-Modell-Architekturen: Einheitliche API für verschiedene KI-Provider
- Enterprise-Anwendungen: WeChat/Alipay-Zahlungen, Yuan-Abwicklung
- Entwickler-Teams: Kostenlose Credits für Prototyping und Tests
❌ Nicht geeignet für:
- Ultra-sensitive Daten: Obwohl sicher, benötigen manche Branchen eigene Infra
- Regionen außerhalb Chinas: Andere Provider könnten günstiger sein
- Sehr kleine Volumen: Fixkosten lohnen sich erst ab certainem Volumen
Preise und ROI
Basierend auf meinen Erfahrungswerten mit Produktions-Deployments:
| Workload | Monatliche Tokens | Standard-Kosten | HolySheep-Kosten | Jährliche Ersparnis |
|---|---|---|---|---|
| Kleines Startup | 10M Input / 5M Output | $1.200 | $180 | $12.240 |
| Mittleres Unternehmen | 100M Input / 50M Output | $12.000 | $1.800 | $122.400 |
| Großes Unternehmen | 1B Input / 500M Output | $120.000 | $18.000 | $1.224.000 |
ROI-Berechnung: Selbst bei konservativen 50M Token/Monat amortisiert sich HolySheep innerhalb von Tagen. Die Einsparung kann direkt in mehr Rechenleistung, bessere Features oder niedrigere Endkundenpreise investiert werden.
Warum HolySheep wählen
Nach Jahren der Arbeit mit verschiedenen API-Providern habe ich HolySheep aus folgenden Gründen als meine primäre Lösung gewählt:
- 85%+ Kostenersparnis: Meine Rechnungen sind von durchschnittlich $3.200/Monat auf unter $500 gesunken – das ist keine Übertreibung
- <50ms Latenz für DeepSeek V4: Im Vergleich zu 200-400ms bei direkten China-Verbindungen ist das ein Quantensprung für UX
- Native Yuan-Unterstützung: WeChat Pay und Alipay machen Abrechnungen für chinesische Teams trivial
- Kostenlose Credits: Jede Registrierung kommt mit Testguthaben – kein Risiko für Proof of Concepts
- Multi-Provider-Aggregation: Eine API, alle Modelle – ich muss nicht 4 verschiedene Integrationen warten
4. Concurrency-Control und Rate-Limiting
Ein kritischer Aspekt für Produktionssysteme ist die korrekte Verwaltung von gleichzeitigen Anfragen. Mein Gateway implementiert ein robustes Semaphore-basiertes System:
"""
Concurrency Control mit Semaphoren und Rate Limiting
Thread-sicher, asyncio-kompatibel, Produktions-ready
"""
import asyncio
import time
from typing import Dict, Optional
from dataclasses import dataclass
from collections import defaultdict
import threading
@dataclass
class RateLimitConfig:
"""Rate-Limit Konfiguration pro Modell"""
requests_per_minute: int
tokens_per_minute: int
burst_size: int
class ConcurrencyController:
"""
Verwaltet gleichzeitige Requests und Rate Limits.
Features:
- Semaphor-basierte Concurrency-Control pro Modell
- Token-basiertes Rate-Limiting
- Burst-Protection
- Automatische Retry-Logik mit Exponential Backoff
"""
def __init__(self, model_configs: Dict[str, ModelConfig]):
self.model_configs = model_configs
self.semaphores: Dict[str, asyncio.Semaphore] = {}
self.rate_limiter: Dict[str, Dict] = defaultdict(lambda: {
"tokens_used": 0,
"requests_made": 0,
"window_start": time.time(),
"lock": asyncio.Lock()
})
self._init_semaphores()
def _init_semaphores(self):
"""Initialisiert Semaphore für jedes Modell"""
for model, config in self.model_configs.items():
if config.enabled:
self.semaphores[model] = asyncio.Semaphore(
config.max_concurrent
)
async def acquire(
self,
model: str,
estimated_tokens: int,
timeout: float = 30.0
) -> bool:
"""
Acquired eine Request-Perimission für das angegebene Modell.
Blockiert automatisch bei Rate-Limits.
"""
if model not in self.semaphores:
raise ValueError(f"Unknown model: {model}")
semaphore = self.semaphores[model]
rate_info = self.rate_limiter[model]
# Rate-Limit Check mit Lock
async with rate_info["lock"]:
current_time = time.time()
window_elapsed = current_time - rate_info["window_start"]
# Window zurücksetzen falls abgelaufen
if window_elapsed >= 60:
rate_info["tokens_used"] = 0
rate_info["requests_made"] = 0
rate_info["window_start"] = current_time
# Token-Limit prüfen
max_tokens_per_min = 100000 # Default
if estimated_tokens + rate_info["tokens_used"] > max_tokens_per_min:
# Warten bis Window sich resetiert
wait_time = 60 - window_elapsed
if wait_time > 0:
await asyncio.sleep(wait_time)
return await self.acquire(model, estimated_tokens, timeout)
# Concurrency-Limit prüfen
if semaphore.locked():
wait_time = timeout / 10 # Progressively check
try:
await asyncio.wait_for(
semaphore.acquire(),
timeout=timeout
)
except asyncio.TimeoutError:
return False
return True
async def release(self, model: str, tokens_used: int):
"""Gibt die Request-Permission frei"""
if model in self.semaphores:
self.semaphores[model].release()
rate_info = self.rate_limiter[model]
async with rate_info["lock"]:
rate_info["tokens_used"] += tokens_used
rate_info["requests_made"] += 1
async def execute_with_concurrency(
self,
model: str,
tokens: int,
coro_func,
*args,
**kwargs
):
"""
Führt eine Coroutine mit Concurrency-Control aus.
Behandelt automatisch Retry bei temporären Fehlern.
"""
max_retries = 3
base_delay = 1.0
for attempt in range(max_retries):
acquired = await self.acquire(model, tokens)
if not acquired:
raise Exception(f"Timeout acquiring slot for {model}")
try:
result = await coro_func(*args, **kwargs)
return result
except Exception as e:
if attempt == max_retries - 1:
raise
# Exponential backoff
delay = base_delay * (2 ** attempt)
await asyncio.sleep(delay)
finally:
await self.release(model, tokens)
raise Exception("Max retries exceeded")
Usage Example
async def example_usage():
controller = ConcurrencyController(MODEL_CONFIGS)
async def call_model():
gateway = MultiModelGateway("YOUR_HOLYSHEEP_API_KEY")
return await gateway.chat_completion(
messages=[{"role": "user", "content": "Hallo Welt!"}],
model="deepseek-chat-v4"
)
# Parallel execution mit maximaler Kontrolle
tasks = [
controller.execute_with_concurrency(
"deepseek-chat-v4",
estimated_tokens=100,
coro_func=call_model
)
for _ in range(50)
]
results = await asyncio.gather(*tasks, return_exceptions=True)
success_count = sum(1 for r in results if not isinstance(r, Exception))
print(f"✅ {success_count}/{len(results)} Requests erfolgreich")
if __name__ == "__main__":
asyncio.run(example_usage())
Häufige Fehler und Lösungen
1. Timeout-Fehler bei langsamen Modellen
Problem: Bei hoher Last oder langsamen Modellen (GPT-4.1, Claude) treten Timeouts auf.
❌ FALSCH: Harter Timeout ohne Fallback
response = await client.post(url, json=payload, timeout=10.0)
✅ RICHTIG: Adaptives Timeout mit automatischem Fallback
async def robust_request(
messages: List[Dict],
primary_model: str = "deepseek-chat-v4",
fallback_models: List[str] = None
):
"""
Robuster Request mit:
- Modellspezifischen Timeouts
- Automatischem Fallback
- Retry-Logik
"""
if fallback_models is None:
fallback_models = ["gemini-2.5-flash", "gpt-4.1"]
# Modellspezifische Timeouts
timeouts = {
"deepseek-chat-v4": 30.0, # Schnell, kann kürzer
"gemini-2.5-flash": 45.0, # Mittel
"gpt-4.1": 60.0, # Länger für komplexe Tasks
"claude-sonnet-4.5": 90.0 # Claude ist manchmal langsam
}
errors = []
for model in [primary_model] + fallback_models:
timeout = timeouts.get(model, 30.0)
try:
async with httpx.AsyncClient(timeout=timeout) as client:
response = await client.post(
f"https://api.holysheep.ai/v1/chat/completions",
headers={
"Authorization": f"Bearer YOUR_HOLYSHEEP_API_KEY",
"Content-Type": "application/json"
},
json={
"model": model,
"messages": messages,
"max_tokens": 4096
}
)
response.raise_for_status()
return response.json()
except httpx.TimeoutException as e:
errors.append(f"{model}: Timeout after {timeout}s")
continue
except httpx.HTTPStatusError as e:
if e.response.status_code == 429:
# Rate limit - kurz warten und Retry
await asyncio.sleep(2 ** len(errors))
continue
raise
# Alle Modelle fehlgeschlagen
raise Exception(f"All models failed: {errors}")
2. Caching-Kollisionen bei unterschiedlichen Parametern
Problem: Der Cache-Schlüssel berücksichtigt nicht alle relevanten Parameter, was zu falschen gecachten Antworten führt.
❌ FALSCH: Unvollständiger Cache-Key
def bad_cache_key(messages, model):
return f"cache:{hashlib.md5(str(messages).encode()).hexdigest()}"
✅ RICHTIG: Vollständiger Cache-Key mit allen Parametern
def robust_cache_key(
messages: List[Dict],
model: str,
temperature: float,
max_tokens: int,
system_prompt: str = ""
) -> str:
"""
Generiert einen eindeutigen Cache-Key, der ALLE
relevanten Parameter berücksichtigt.
"""
# Normalisieren: Messages sortieren, Whitespace entfernen
normalized_messages = []
for msg in messages:
normalized_msg = {
"role": msg["role"],
"content": " ".join(msg["content"].split()) # Whitespace normalisieren
}
normalized_messages.append(normalized_msg)
# System-Prompt hinzufügen falls vorhanden
if system_prompt:
normalized_messages.insert(0, {
"role": "system",
"content": system_prompt.strip()
})
# Vollständigen Hash erstellen
cache_data = {
"messages": normalized_messages,
"model": model,
"params": {
"temperature": round(temperature, 2),
"max_tokens": max_tokens
}
}
content = json.dumps(cache_data, sort_keys=True, ensure_ascii=True)
return f"cache:v2:{hashlib.sha256(content.encode('utf-8')).hexdigest()}"
Usage in Async Redis Cache
async def cached_chat_completion(
redis_client,
gateway,
messages: List[Dict],
model: str = "deepseek-chat-v4",
temperature: float = 0.7,
max_tokens: int = 4096,
cache_ttl: int = 3600
):
"""
Chat-Completion mit intelligentem Caching.
- Prüft Cache vor API-Call
- Speichert Ergebnis nach API-Call
- Behandelt Cache-Misses gracefully
"""
cache_key = robust_cache_key(
messages, model, temperature, max_tokens
)
# Cache prüfen
cached = await redis_client.get(cache_key)
if cached:
result = json.loads(cached)
result["cached"] = True
return result
# API-Call durchführen
result = await gateway.chat_completion(
messages=messages,
model=model,
temperature=temperature,
max_tokens=max_tokens
)