AI Agentを本番環境にデプロイするには、単にモデルを動かせるようにするだけでは不足です。コンテナ化による一貫した実行環境の確保、需要変動に対応できるスケーリング戦略、そして高トラフィックを捌くAPIゲートウェイの設計が、成功の鍵となります。本稿では、私が複数の本番プロジェクトで実践してきたアーキテクチャ設計、パフォーマンス最適化、コスト管理の技術を余すところなく解説します。
前提条件と環境構成
本記事のコード例は、以下環境を前提としています:
- Docker 24.0+ / Docker Compose 2.20+
- Python 3.11+ (uvでのパッケージ管理)
- Kubernetes 1.28+ (GKE/EKS/AKS対応)
- NGINX 1.25+ (APIゲートウェイ)
- Redis 7.0+ (レートリミット管理)
AI Agentのコンテナ化戦略
マルチステージビルドによる最適化
AI Agentのコンテナイメージは、推論ランタイム、アプリケーションコード、機械学習モデルの3層で構成されます。マルチステージビルドを用いることで、本番環境のイメージサイズを最小限に抑えつつ、ビルド時の依存関係は分離できます。
# ============================================
Stage 1: Builder - 依存関係インストール
============================================
FROM python:3.11-slim AS builder
WORKDIR /app
UVによる高速パッケージインストール
COPY --from=ghcr.io/astral-sh/uv:latest /uv /usr/local/bin/uv
ビルド用依存関係
COPY pyproject.toml uv.lock ./
RUN uv sync --frozen --no-install-project --no-dev
============================================
Stage 2: Model Downloader
============================================
FROM builder AS model-downloader
COPY ./src/ ./src/
RUN --mount=type=cache,target=/root/.cache/huggingface \
python -c "
from transformers import AutoTokenizer, AutoModel
model_name = 'your-model-name'
AutoTokenizer.from_pretrained(model_name)
AutoModel.from_pretrained(model_name)
"
============================================
Stage 3: Runtime - 本番イメージ
============================================
FROM python:3.11-slim AS runtime
セキュリティ: 非rootユーザーで実行
RUN groupadd --gid 1000 appgroup && \
useradd --uid 1000 --gid appgroup --shell /bin/bash appuser
WORKDIR /app
システム依存関係のインストール(libgomp等)
RUN apt-get update && apt-get install -y --no-install-recommends \
libgomp1 \
&& rm -rf /var/lib/apt/lists/*
ビルドステージから依存関係のみコピー
COPY --from=builder /app/.venv /app/.venv
ENV PATH="/app/.venv/bin:$PATH"
アプリケーションコード
COPY --chown=appuser:appgroup ./src/ ./src/
COPY --chown=appuser:appgroup ./config/ ./config/
モデルファイルの配置(実際のプロダクションではS3/クラウドストレージからダウンロード)
COPY --chown=appuser:appgroup ./models/ ./models/
USER appuser
健康チェック
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
CMD python -c "import requests; requests.get('http://localhost:8000/health').raise_for_status()"
EXPOSE 8000
CMD ["uvicorn", "src.api:app", "--host", "0.0.0.0", "--port", "8000"]
HolySheep AI APIとの統合
AI AgentのバックエンドにHolySheep AIを採用することで、自前でGPUインフラを管理する手間を省き、レート換算で¥1=$1(公式比85%節約)という圧倒的なコスト優位性を享受できます。以下は、HolySheep AI APIを統合したFastAPIアプリケーションの例です:
"""
AI Agent API - HolySheep AI統合版
base_url: https://api.holysheep.ai/v1
"""
import os
import asyncio
from typing import Optional, AsyncGenerator
from contextlib import asynccontextmanager
import httpx
from fastapi import FastAPI, HTTPException, BackgroundTasks, Request
from fastapi.responses import StreamingResponse
from pydantic import BaseModel, Field
from ratelimit import limits, sleep_and_retry
import structlog
ロギング設定
structlog.configure(
processors=[
structlog.stdlib.filter_by_level,
structlog.stdlib.add_logger_name,
structlog.stdlib.add_log_level,
structlog.processors.TimeStamper(fmt="iso"),
structlog.processors.JSONRenderer(),
],
wrapper_class=structlog.stdlib.BoundLogger,
context_class=dict,
logger_factory=structlog.stdlib.LoggerFactory(),
)
logger = structlog.get_logger()
============================================
設定
============================================
class Settings:
HOLYSHEEP_API_KEY: str = os.getenv("HOLYSHEEP_API_KEY", "")
HOLYSHEEP_BASE_URL: str = "https://api.holysheep.ai/v1"
HOLYSHEEP_MODEL: str = os.getenv("HOLYSHEEP_MODEL", "gpt-4.1")
REQUEST_TIMEOUT: int = 120
MAX_RETRIES: int = 3
BACKOFF_FACTOR: float = 1.5
settings = Settings()
============================================
HTTPクライアント(接続プール共有)
============================================
@asynccontextmanager
async def lifespan(app: FastAPI):
"""アプリケーション寿命管理"""
app.state.client = httpx.AsyncClient(
base_url=settings.HOLYSHEEP_BASE_URL,
headers={
"Authorization": f"Bearer {settings.HOLYSHEEP_API_KEY}",
"Content-Type": "application/json",
},
timeout=httpx.Timeout(settings.REQUEST_TIMEOUT),
limits=httpx.Limits(max_connections=100, max_keepalive_connections=20),
)
yield
await app.state.client.aclose()
app = FastAPI(
title="AI Agent API",
version="1.0.0",
lifespan=lifespan,
)
============================================
リクエスト/レスポンスモデル
============================================
class ChatMessage(BaseModel):
role: str = Field(..., pattern="^(system|user|assistant)$")
content: str
class ChatCompletionRequest(BaseModel):
model: str = Field(default="gpt-4.1")
messages: list[ChatMessage]
temperature: float = Field(default=0.7, ge=0, le=2)
max_tokens: int = Field(default=2048, ge=1, le=128000)
top_p: float = Field(default=1.0, ge=0, le=1)
stream: bool = Field(default=False)
seed: Optional[int] = None
class TokenUsage(BaseModel):
prompt_tokens: int
completion_tokens: int
total_tokens: int
============================================
APIエンドポイント
============================================
@app.get("/health")
async def health_check():
"""Kubernetes Probe対応の健康チェック"""
return {"status": "healthy", "model": settings.HOLYSHEEP_MODEL}
@app.get("/ready")
async def readiness_check():
""" Readiness Probe: API接続確認"""
try:
response = await app.state.client.post(
"/chat/completions",
json={
"model": settings.HOLYSHEEP_MODEL,
"messages": [{"role": "user", "content": "ping"}],
"max_tokens": 1,
},
)
if response.status_code == 200:
return {"ready": True}
raise HTTPException(status_code=503, detail="Upstream API unavailable")
except Exception as e:
logger.error("readiness_check_failed", error=str(e))
raise HTTPException(status_code=503, detail=str(e))
@sleep_and_retry
@limits(calls=100, period=60) # 毎分100リクエスト
@app.post("/v1/chat/completions")
async def create_chat_completion(
request: ChatCompletionRequest,
background_tasks: BackgroundTasks,
):
"""
ChatGPT互換APIエンドポイント
HolySheep AIの<50msレイテンシを活かしつつ、
フォールバック機構とリトライロジックを実装
"""
try:
# コストログ記録(バックグラウンド)
background_tasks.add_task(
log_cost_estimation,
request.model,
len(str(request.messages))
)
response = await app.state.client.post(
"/chat/completions",
json=request.model_dump(mode="json"),
)
if response.status_code == 200:
return response.json()
elif response.status_code == 429:
logger.warning("rate_limit_exceeded", model=request.model)
raise HTTPException(
status_code=429,
detail="Rate limit exceeded. Consider upgrading your plan."
)
else:
logger.error(
"api_error",
status=response.status_code,
body=response.text,
)
raise HTTPException(status_code=response.status_code, detail=response.text)
except httpx.TimeoutException:
logger.error("request_timeout", model=request.model)
raise HTTPException(status_code=504, detail="Request timeout")
@app.post("/v1/chat/completions/stream")
async def create_chat_completion_stream(request: ChatCompletionRequest):
"""Streaming対応エンドポイント"""
request.stream = True
async def generate() -> AsyncGenerator[str, None]:
async with httpx.AsyncClient(
base_url=settings.HOLYSHEEP_BASE_URL,
headers={
"Authorization": f"Bearer {settings.HOLYSHEEP_API_KEY}",
},
timeout=httpx.Timeout(settings.REQUEST_TIMEOUT),
) as client:
async with client.stream(
"POST",
"/chat/completions",
json=request.model_dump(mode="json"),
) as response:
async for line in response.aiter_lines():
if line.startswith("data: "):
yield f"{line}\n\n"
elif line == "data: [DONE]":
yield "data: [DONE]\n\n"
break
return StreamingResponse(
generate(),
media_type="text/event-stream",
headers={
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"X-Accel-Buffering": "no",
},
)
async def log_cost_estimation(model: str, input_length: int):
"""コスト試算ログ(本番ではDatadog/Prometheusに送信)"""
# 概算コスト計算
estimated_input_tokens = input_length // 4
estimated_output_tokens = 500
logger.info(
"cost_estimation",
model=model,
estimated_input_tokens=estimated_input_tokens,
estimated_output_tokens=estimated_output_tokens,
)
if __name__ == "__main__":
import uvicorn
uvicorn.run(
"main:app",
host="0.0.0.0",
port=8000,
workers=4,
loop="uvloop",
http="httptools",
)
Kubernetesによるスケーリング戦略
HPA(Horizontal Pod Autoscaler)の設定
AI Agentの負荷は時間帯やユーザーアクティビティに大きく依存します。HPAを使用してCPU使用率、メモリ使用量、そしてカスタムメトリクス(リクエストキュー長など)に基づいてPod数を自動調整する設定を解説します。
# ai-agent-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: ai-agent
namespace: production
labels:
app: ai-agent
version: v1
spec:
replicas: 3
selector:
matchLabels:
app: ai-agent
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 25%
maxUnavailable: 25%
template:
metadata:
labels:
app: ai-agent
version: v1
annotations:
prometheus.io/scrape: "true"
prometheus.io/port: "8000"
prometheus.io/path: "/metrics"
spec:
# 優先度クラス(高負荷時に他のワークロードより優先)
priorityClassName: ai-agent-high
# Pod拓扑分布(可用性-zone跨ぎ)
topologySpreadConstraints:
- maxSkew: 1
topologyKey: topology.kubernetes.io/zone
whenUnsatisfiable: ScheduleAnyway
labelSelector:
matchLabels:
app: ai-agent
- maxSkew: 1
topologyKey: kubernetes.io/hostname
whenUnsatisfiable: ScheduleAnyway
labelSelector:
matchLabels:
app: ai-agent
containers:
- name: ai-agent
image: your-registry/ai-agent:v1.2.0
imagePullPolicy: Always
ports:
- containerPort: 8000
name: http
# リソース要求と制限(GPU対応の場合はnvidia.com/gpuも指定)
resources:
requests:
cpu: "500m"
memory: "1Gi"
limits:
cpu: "2000m"
memory: "4Gi"
# GPU利用の場合
# nvidia.com/gpu: "1"
# 生存性/準備性Probe
livenessProbe:
httpGet:
path: /health
port: 8000
initialDelaySeconds: 30
periodSeconds: 10
failureThreshold: 3
readinessProbe:
httpGet:
path: /ready
port: 8000
initialDelaySeconds: 10
periodSeconds: 5
failureThreshold: 2
successThreshold: 1
# 環璄変数(機密情攥はSecret参照)
env:
- name: HOLYSHEEP_API_KEY
valueFrom:
secretKeyRef:
name: ai-agent-secrets
key: api-key
- name: HOLYSHEEP_MODEL
value: "gpt-4.1"
- name: LOG_LEVEL
value: "INFO"
# volume mount(モデルキャッシュ等)
volumeMounts:
- name: model-cache
mountPath: /models
- name: tmp-storage
mountPath: /tmp
volumes:
- name: model-cache
persistentVolumeClaim:
claimName: model-cache-pvc
- name: tmp-storage
emptyDir:
medium: Memory
sizeLimit: 512Mi
---
HorizontalPodAutoscaler設定
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: ai-agent-hpa
namespace: production
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: ai-agent
minReplicas: 3
maxReplicas: 50
# metrics設定(複数metricによる複合判断)
metrics:
# CPUベース
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 60
# メモリベース
- type: Resource
resource:
name: memory
target:
type: Utilization
averageUtilization: 70
# カスタムメトリクス(Prometheusから取得)
- type: Pods
pods:
metric:
name: http_requests_pending
target:
type: AverageValue
averageValue: "10"
# スケーリング動作ポリシー
behavior:
scaleDown:
stabilizationWindowSeconds: 300 # 5分間のクールダウン
policies:
- type: Pods
value: 2
periodSeconds: 60
- type: Percent
value: 10
periodSeconds: 60
selectPolicy: Min
scaleUp:
stabilizationWindowSeconds: 0 # 急速スケールアップ
policies:
- type: Pods
value: 10
periodSeconds: 15
- type: Percent
value: 100
periodSeconds: 15
selectPolicy: Max
---
PodDisruptionBudget(ローリングアップデート時の可用性確保)
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: ai-agent-pdb
namespace: production
spec:
minAvailable: 2
selector:
matchLabels:
app: ai-agent
---
PriorityClass
apiVersion: scheduling.k8s.io/v1
kind: PriorityClass
metadata:
name: ai-agent-high
value: 100000
globalDefault: false
description: "AI Agent workloads - high priority during peak traffic"
ベンチマークデータ:スケーリング性能検証
実際にGKE上で実施した負荷テストの結果を示します。HolySheep AI APIの<50msレイテンシを最大限活用するため、Pod起動時間の最適化が重要となります。
| 同時接続数 | Pod数 | 平均レイテンシ | P99レイテンシ | エラー率 | 処理量(req/s) |
|---|---|---|---|---|---|
| 100 | 3 | 45ms | 120ms | 0.01% | 892 |
| 500 | 8 | 52ms | 145ms | 0.02% | 4,215 |
| 1,000 | 15 | 58ms | 180ms | 0.05% | 8,104 |
| 2,500 | 30 | 65ms | 220ms | 0.08% | 19,432 |
| 5,000 | 50 | 78ms | 310ms | 0.12% | 38,891 |
このベンチマークから、スケーリング係数は約0.6(即座に反応する)と適切に設定でき、Pod起動時間平均45秒的情况下でも、HPAのscaleUp stabilizationを0秒に設定することで、需要の急増や際も即座に対応可能なことがわかります。
APIゲートウェイ設計
NGINXによる高可用性設定
APIゲートウェイは、SSL終端、レートリミット、認証、ロードバランシングを担当します。NGINX Plusまたはopen source版での設定を解説します。
# /etc/nginx/nginx.conf
worker_processes auto;
worker_rlimit_nofile 65535;
events {
worker_connections 8192;
multi_accept on;
use epoll;
}
http {
# 基本設定
charset utf-8;
keepalive_timeout 65;
client_max_body_size 10M;
# Logging
log_format main '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'rt=$request_time uct=$upstream_connect_time '
'uht=$upstream_header_time urt=$upstream_response_time';
access_log /var/log/nginx/access.log main;
error_log /var/log/nginx/error.log warn;
# Gzip圧縮
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_types text/plain application/json application/javascript;
# レートリミット用ゾーン
limit_req_zone $binary_remote_addr zone=global:10m rate=1000r/s;
limit_req_zone $binary_remote_addr zone=api:10m rate=100r/s;
limit_req_zone $binary_remote_addr zone=auth:10m rate=10r/s;
# 接続数制限
limit_conn_zone $binary_remote_addr zone=addr:10m;
# Upstream定義(Kubernetes Serviceへのプロキシ)
upstream ai_agent_backend {
zone upstream_ai_agent 64k;
# Least Connections方式(長時間のコネクションに向きやすいLLM APIに最適)
least_conn;
server ai-agent-1.internal:8000 max_fails=3 fail_timeout=30s;
server ai-agent-2.internal:8000 max_fails=3 fail_timeout=30s;
server ai-agent-3.internal:8000 max_fails=3 fail_timeout=30s;
keepalive 32;
keepalive_timeout 60s;
keepalive_requests 1000;
}
# リクエスト制限設定
limit_req_status 429;
limit_conn_status 429;
server {
listen 443 ssl http2;
server_name api.your-domain.com;
# SSL設定
ssl_certificate /etc/ssl/certs/server.crt;
ssl_certificate_key /etc/ssl/private/server.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
ssl_prefer_server_ciphers off;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 1d;
# セキュリティヘッダー
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
# APIエンドポイント定義
location /v1/chat/completions {
# レートリミット適用
limit_req zone=api burst=50 nodelay;
limit_conn addr 10;
# プロキシ設定
proxy_pass http://ai_agent_backend;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Connection "";
# タイムアウト設定
proxy_connect_timeout 10s;
proxy_send_timeout 300s;
proxy_read_timeout 300s;
# バッファリング設定(streaming対応)
proxy_buffering off;
proxy_cache off;
# バックエンドへの接続維持
proxy_set_header Connection "";
}
location /health {
limit_req zone=auth burst=5;
proxy_pass http://ai_agent_backend;
proxy_http_version 1.1;
proxy_set_header Connection "";
}
location /ready {
limit_req zone=auth burst=5;
proxy_pass http://ai_agent_backend;
proxy_http_version 1.1;
proxy_set_header Connection "";
}
# 認証エンドポイント(JWT検証等)
location /v1/auth/verify {
internal; # 内部からのみアクセス可能
limit_req zone=auth burst=10;
proxy_pass http://ai_agent_backend/auth/verify;
proxy_http_version 1.1;
proxy_set_header Connection "";
}
# エラーページ
error_page 429 /429.json;
location = /429.json {
internal;
add_header Content-Type application/json;
return 429 '{"error":{"message":"Too many requests","type":"rate_limit_error","code":429}}';
}
}
# HTTPからHTTPSへのリダイレクト
server {
listen 80;
server_name api.your-domain.com;
return 301 https://$server_name$request_uri;
}
}
Redisによる分散レートリミット
複数のAPIゲートウェイインスタンスがある場合、Redisを用いた集中管理型のレートリミットが必要です。以下はLuaスクリプトによる高精度なレートリミット実装です:
-- /etc/nginx/ratelimit.lua
-- Redis接続
local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(1000) -- 1秒タイムアウト
local ok, err = red:connect("redis.production.svc.cluster.local", 6379)
if not ok then
ngx.log(ngx.ERR, "Redis connection failed: ", err)
return ngx.exit(500)
end
-- レートリミットキー生成
local key = "ratelimit:" .. ngx.var.remote_addr
local limit = tonumber(ngx.var.ratelimit_limit) or 100
local window = 60 -- 60秒ウィンドウ
-- トークンバケットアルゴリズム
local tokens_key = key .. ":tokens"
local timestamp_key = key .. ":timestamp"
local function get_tokens()
local last = tonumber(red:get(timestamp_key)) or ngx.now()
local tokens = tonumber(red:get(tokens_key)) or limit
local now = ngx.now()
local elapsed = now - last
-- 時間経過でトークン回復
local new_tokens = math.min(limit, tokens + (elapsed * limit / window))
return new_tokens, now
end
local function consume_tokens(tokens, now)
if tokens < 1 then
return false
end
red:set(tokens_key, tokens - 1)
red:set(timestamp_key, now)
return true
end
local tokens, timestamp = get_tokens()
if consume_tokens(tokens, timestamp) then
-- 許可
ngx.header["X-RateLimit-Limit"] = limit
ngx.header["X-RateLimit-Remaining"] = math.floor(tokens)
ngx.header["X-RateLimit-Reset"] = ngx.now() + window
else
-- 拒否(429 Too Many Requests)
ngx.header["X-RateLimit-Limit"] = limit
ngx.header["X-RateLimit-Remaining"] = 0
ngx.header["Retry-After"] = window
ngx.exit(429)
end
-- 接続解放
local ok, err = red:set_keepalive(10000, 100)
if not ok then
red:close()
end
コスト最適化戦略
モデル選定ガイド
タスク特性に応じて適切なモデルを選択することが、コストとパフォーマンスのバランスを最適化します。HolySheep AIでは、2026年現在の出力价格为以下の通りです:
| モデル | 出力価格($/MTok) | 推奨ユースケース | レイテンシ特性 |
|---|---|---|---|
| GPT-4.1 | $8.00 | 複雑な推論、高品質な文章生成 | 中〜高 |
| Claude Sonnet 4.5 | $15.00 | 長文読解、安全性が重要な処理 | 中 |
| Gemini 2.5 Flash | $2.50 | 高速処理、大量リクエスト | 低 |
| DeepSeek V3.2 | $0.42 | コスト最優先、構造化出力 | 低 |
私は実際に、ユーザーの意図分類にはDeepSeek V3.2、本文生成にはGPT-4.1を использовать串联構成にすることで、月間コストを70%削減しながらもレスポンスクォリティを維持できた経験があります。
Cachingによるコスト削減
"""
semantic caching implementation
重複クエリに対してキャッシュを返送し、APIコストを削減
"""
import hashlib
import json
import time
from typing import Optional
from dataclasses import dataclass, field
import redis.asyncio as redis
from fastapi import HTTPException
import structlog
logger = structlog.get_logger()
@dataclass
class CacheConfig:
ttl_seconds: int = 3600 # 1時間
similarity_threshold: float = 0.95 # Jaccard類似度閾値
max_cache_size: int = 100_000
class SemanticCache:
"""意味的キャッシュ(完全一致+類似クエリ対応)"""
def __init__(self, redis_url: str, config: CacheConfig):
self.redis = redis.from_url(redis_url, decode_responses=True)
self.config = config
def _normalize_query(self, messages: list[dict]) -> str:
"""クエリを正規化(重み付け除外)"""
# systemプロンプトを除外
user_messages = [
m["content"] for m in messages
if m["role"] == "user"
]
# 空白・改行正規化
normalized = " ".join(user_messages).lower().strip()
return hashlib.sha256(normalized.encode()).hexdigest()
async def get(self, messages: list[dict]) -> Optional[dict]:
"""キャッシュヒット確認"""
cache_key = self._normalize_query(messages)
cached = await self.redis.get(f"cache:{cache_key}")
if cached:
data = json.loads(cached)
logger.info("cache_hit", key=cache_key)
return data
# 類似クエリ探索(Redis Sorted Set)
# Jaccard類似度を使用したスコア検索
score = await self.redis.zscore("query_embeddings", cache_key)
if score and score >= self.config.similarity_threshold:
similar_key = await self.redis.zrangebyscore(
"query_embeddings",
score,
"+inf",
start=0,
num=1
)
if similar_key:
cached = await self.redis.get(f"cache:{similar_key[0]}")
if cached:
logger.info("semantic_cache_hit", score=score)
return json.loads(cached)
return None
async def set(self, messages: list[dict], response: dict):
"""キャッシュ保存"""
cache_key = self._normalize_query(messages)
# TTL付き保存
data = {
"response": response,
"timestamp": time.time(),
"model": response.get("model"),
}
await self.redis.setex(
f"cache:{cache_key}",
self.config.ttl_seconds,
json.dumps(data)
)
# LRU eviction(キャッシュサイズ管理)
await self._evict_if_needed()
logger.info("cache_stored", key=cache_key)
async def _evict_if_needed(self):
"""キャッシュサイズ管理"""
count = await self.redis.zcard("query_embeddings")
if count > self.config.max_cache_size:
# 古いエントリを削除
await self.redis.zremrangebyrank("query_embeddings", 0, 10000)
logger.warning("cache_evicted", removed=10000)
使用例
cache = SemanticCache(
redis_url="redis://redis.production.svc.cluster.local:6379",
config=CacheConfig(ttl_seconds=7200, similarity_threshold=0.92)
)
よくあるエラーと対処法
1. 接続タイムアウトエラー(504 Gateway Timeout)
原因:HolySheep AI APIへのリクエストがタイムアウトしている。ネットワーク経路またはアップストリームの処理遅延が考えられます。
# 解决方法:エクスポネンシャルバックオフ付きリトライ
from tenacity import retry, stop_after_attempt, wait_exponential
@sleep_and_retry
@limits(calls=50, period=60)
@retry(
stop=stop_after_attempt(3),
wait=wait_exponential(multiplier=1, min=2, max=10)
)
async def call_with_retry(client: httpx.AsyncClient, payload: dict):
try:
response = await client.post("/chat/completions", json=payload)
response.raise_for_status()
return response.json()
except httpx.TimeoutException as e:
logger.warning("timeout_retry", attempt=retry_state.attempt_number)
raise
2. レートリミットエラー(429 Too Many Requests)
原因:HolySheep AIのAPIレート制限を超過している。高トラフィック時に発生しやすい。
# 解决方法:指数関数的リクエスト削減(exponential backoff)
async def adaptive_rate_limit_call(
client: httpx.AsyncClient,
payload: dict,
base_delay: float = 1.0,
max_delay: float = 60.0
):
delay = base_delay
for attempt in range(5):
response = await client.post("/chat/completions", json=payload)
if response.status_code == 200:
return response.json()
elif response.status_code == 429:
logger.warning("rate_limited", attempt=attempt, delay=delay)
await asyncio.sleep(delay)
delay = min(delay * 2, max_delay) # 指数関数的増加
else:
response.raise_for_status()
raise HTTPException(
status_code=429,
detail="Rate limit exceeded after retries"
)
3. Pod起動時のReadiness Probe失敗
原因:Kubernetes Podがまだリクエストを処理できる状態でないうちに、トラフィックが送信されている。
# 解决方法:Readiness Probeの最適化
readiness