ml-api-endpoint について
機械学習エンジニア向けのAPIエンドポイント設計・デプロイスキルです。FastAPI推論、入力検証、性能最適化、ヘルスチェック、Dockerデプロイを扱います。
主な機能
- 01ステートレスAPIとレスポンス設計
- 02FastAPI推論エンドポイントの例
- 03入力検証とバッチ予測
- 04予測キャッシュと性能最適化
- 05ヘルスチェックとDockerデプロイ
活用シーン
- 01機械学習モデルの推論APIを設計
- 02入力検証付きバッチ予測を実装
- 03決定論的モデルの予測結果をキャッシュ
- 04ヘルスチェックを追加してモデルサービスをデプロイ
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ dengineproblem/ agents-monorepo --skill ml-api-endpointインストール後、Claude Code で/ml-api-endpointを入力して読み込まれたか確認します。
詳細
ML API エンドポイントのエキスパート
機械学習 API エンドポイントの設計とデプロイに関するエキスパートです。
基本原則
API 設計
- ステートレス設計:各リクエストに必要な情報をすべて含めます
- 一貫したレスポンス形式:成功時とエラー時の構造を標準化します
- バージョン管理戦略:モデルの更新を想定して計画します
- 入力検証:推論前に厳密な検証を行います
FastAPI の実装
基本的な ML エンドポイント
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, validator
import joblib
import numpy as np
app = FastAPI(title="ML Model API", version="1.0.0")
model = None
@app.on_event("startup")
async def load_model():
global model
model = joblib.load("model.pkl")
class PredictionInput(BaseModel):
features: list[float]
@validator('features')
def validate_features(cls, v):
if len(v) != 10:
raise ValueError('Expected 10 features')
return v
class PredictionResponse(BaseModel):
prediction: float
confidence: float | None = None
model_version: str
request_id: str
@app.post("/predict", response_model=PredictionResponse)
async def predict(input_data: PredictionInput):
features = np.array([input_data.features])
prediction = model.predict(features)[0]
return PredictionResponse(
prediction=float(prediction),
model_version="v1",
request_id=generate_request_id()
)
バッチ予測
class BatchInput(BaseModel):
instances: list[list[float]]
@validator('instances')
def validate_batch_size(cls, v):
if len(v) > 100:
raise ValueError('Batch size cannot exceed 100')
return v
@app.post("/predict/batch")
async def batch_predict(input_data: BatchInput):
features = np.array(input_data.instances)
predictions = model.predict(features)
return {
"predictions": predictions.tolist(),
"count": len(predictions)
}
パフォーマンスの最適化
モデルのキャッシュ
class ModelCache:
def __init__(self, ttl_seconds=300):
self.cache = {}
self.ttl = ttl_seconds
def get(self, features):
key = hashlib.md5(str(features).encode()).hexdigest()
if key in self.cache:
result, timestamp = self.cache[key]
if time.time() - timestamp < self.ttl:
return result
return None
def set(self, features, prediction):
key = hashlib.md5(str(features).encode()).hexdigest()
self.cache[key] = (prediction, time.time())
ヘルスチェック
@app.get("/health")
async def health_check():
return {
"status": "healthy",
"model_loaded": model is not None
}
@app.get("/metrics")
async def get_metrics():
return {
"requests_total": request_counter,
"prediction_latency_avg": avg_latency,
"error_rate": error_rate
}
Docker によるデプロイ
FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "4"]
ベストプラクティス
- I/O 操作には async/await を使用します
- データ型、範囲、ビジネスルールを検証します
- 決定論的なモデルの予測をキャッシュします
- フォールバックレスポンスでモデルの障害に対処します
- 予測、レイテンシ、エラーをログに記録します
- 複数のモデルバージョンに対応します
- メモリと CPU の制限を設定します
コメント
Markdown 対応