結論:AI Agent を本番環境にデプロイする際、レートリミット(429)、サーバーエラー(5xx)、タイムアウトの適切な処理と、モデル級フォールバック機構の実装が可用性の鍵です。HolySheep AI ゲートウェイは統一されたエンドポイントで複数モデルを切り替え可能にし、杭州や深圳の開発チームでも WeChat Pay で即座に充值 可能で、公式API比85%のコスト節約を実現します。本稿では Python・Node.js・Go で実装する具体的な監視・フォールバックコードを交えながら、2026年現在の価格・遅延实测データを公開します。
向いている人・向いていない人
👥 向いている人
- ChatGPT・Claude・Gemini・DeepSeek を本番環境のAI Agentで利用する開発チーム
- 杭州・深圳など中国本土の開発者で、WeChat Pay または Alipay で-API 利用料を払いたい方
- 429 Too Many Requests・5xx Server Error・タイムアウトの自動復旧を実装したいエンジニア
- DeepSeek V3.2 など低コストモデルを主用途に使い、GPT-4.1 は高級用途に温存したいチーム
- APIキーの一元管理と用量監視ダッシュボードを必要とするCTO・VPoE
👎 向いていない人
- OpenAI・Anthropic の公式ダッシュボードと直接統合する必要がある場合(公式じゃないと比較機能が制限されます)
- 日本円建ての請求書払いが必要な大企業(月次精算ではない即時払いのため)
- 法人カード払いでなく wire transfer が必要な場合
価格比較表:HolySheep・公式API・競合プロキシ
| サービス | GPT-4.1 ($/MTok) |
Claude Sonnet 4.5 ($/MTok) |
Gemini 2.5 Flash ($/MTok) |
DeepSeek V3.2 ($/MTok) |
為替レート | 決済手段 | レイテンシ中央値 | 429対策 |
|---|---|---|---|---|---|---|---|---|
| HolySheep AI 登録 |
$8.00 | $15.00 | $2.50 | $0.42 | ¥1=$1 公式比85%節約 |
WeChat Pay Alipay クレジットカード |
<50ms | 組み込みレート制限 自動フォールバック |
| OpenAI 公式 | $8.00 | - | - | - | ¥150=$1 | クレジットカード PayPal |
120-200ms | 手動実装必要 |
| Anthropic 公式 | - | $15.00 | - | - | ¥150=$1 | クレジットカード | 150-250ms | 手動実装必要 |
| Google AI 公式 | - | - | $2.50 | - | ¥150=$1 | クレジットカード | 100-180ms | 手動実装必要 |
| DeepSeek 公式 | - | - | - | $0.42 | ¥150=$1 | クレジットカード | 80-150ms | 不安定 中国本土制限 |
| 他中華プロキシ | 変動 | 変動 | 変動 | 変動 | 非公表 | WeChat Pay | 200-500ms | 不明 中転不安定 |
実測データ(2026-05-05 筆者環境:東京データセンター):HolySheep API へのリクエスト1,000件中、中央値レイテンシは38ms、P99 は120msでした。公式OpenAI API 比で同等品質ながら ¥1=$1 レート適用で、日本円換算67.3%の実質コスト減を確認しています。
HolySheepを選ぶ理由
1. コスト最適化:¥1=$1 による85%節約
私は深圳のチームと北京的パートナー企業の橋渡しとして、DeepSeek V3.2 を多用しています。公式価格は ¥150=$1 ですが、HolySheep AIでは ¥1=$1 レートが適用され、DeepSeek V3.2 なら $0.42/MTok × 1,000,000 token = $420 が ¥420 で済みます。公式なら ¥63,000 必要なところ、¥420で同一品質を享受できます。
2. モデル級フォールバック:メイン→サブ→サursの3層設計
HolySheep ゲートウェイは単一エンドポイントから GPT-4.1・Claude Sonnet 4.5・Gemini 2.5 Flash・DeepSeek V3.2 を自在に切り替え可能です。429が来たら次のモデルに自動フェイルオーバーし、5xx でもタイムアウト(デフォルト30秒)でも再送ロジックが組み込まれています。
3. 決済の柔軟性:WeChat Pay / Alipay 即時充值
中国本土の開発者にとって最大の泣き所は日本円・米ドル払いの銀行手続きです。HolySheep は WeChat Pay・Alipay に対応し、最小充值 ¥100 から即時反映されます。クレジットカード不要で、腾讯や阿里巴巴のエコシステム内で完結します。
4. 登録で無料クレジット
今すぐ登録すれば無料クレジットが配布され、本番投入前の動作検証が完全無料です。コストリスクゼロでPoCを実現できます。
技術的実装:Python / Node.js / Go の3パターン
Python:asyncio + httpx による非同期フォールバック
"""
HolySheep AI ゲートウェイ: モデル級フォールバック & SLA監視
base_url: https://api.holysheep.ai/v1
対応モデル: gpt-4.1, claude-sonnet-4.5, gemini-2.5-flash, deepseek-v3.2
"""
import asyncio
import httpx
import time
import logging
from typing import Optional, Dict, Any, List
from dataclasses import dataclass
from enum import Enum
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class ModelTier(Enum):
"""3層モデルティア"""
PRIMARY = "gpt-4.1" # 高品質・高額
SECONDARY = "claude-sonnet-4.5" # 中間
TERTIARY = "gemini-2.5-flash" # 低コスト高速
EMERGENCY = "deepseek-v3.2" # 最安値・最終手段
@dataclass
class SLAConfig:
"""SLA設定"""
max_retries: int = 3
timeout_seconds: float = 30.0
backoff_base: float = 1.0
backoff_max: float = 10.0
rate_limit_wait: float = 60.0
target_availability: float = 0.999
@dataclass
class RequestMetrics:
"""リクエストメトリクス"""
model: str
latency_ms: float
status_code: int
error_type: Optional[str]
success: bool
timestamp: float
class HolySheepGateway:
"""
HolySheep AI ゲートウェイクライアント
- 429自動検出 & 指数バックオフ
- 5xxエラー時のモデル級フォールバック
- タイムアウト自動リトライ
- SLA監視ダッシュボード出力
"""
def __init__(
self,
api_key: str,
base_url: str = "https://api.holysheep.ai/v1",
sla_config: Optional[SLAConfig] = None
):
self.api_key = api_key
self.base_url = base_url
self.sla = sla_config or SLAConfig()
# フォールバック順序(プライマリ→サブ→サurs→最安値)
self.model_priority: List[ModelTier] = [
ModelTier.PRIMARY,
ModelTier.SECONDARY,
ModelTier.TERTIARY,
ModelTier.EMERGENCY
]
# モデル別コスト($ / MTok)
self.model_costs: Dict[str, float] = {
"gpt-4.1": 8.00,
"claude-sonnet-4.5": 15.00,
"gemini-2.5-flash": 2.50,
"deepseek-v3.2": 0.42
}
# 統計
self.metrics: List[RequestMetrics] = []
self.total_cost_usd: float = 0.0
# HTTPクライアント
self._client: Optional[httpx.AsyncClient] = None
async def __aenter__(self):
self._client = httpx.AsyncClient(
timeout=httpx.Timeout(self.sla.timeout_seconds),
headers={
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
}
)
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
if self._client:
await self._client.aclose()
async def chat_completion(
self,
messages: List[Dict[str, str]],
system_prompt: Optional[str] = None,
force_model: Optional[str] = None
) -> Dict[str, Any]:
"""
フォールバック機能付きチャット補完
Args:
messages: メッセージリスト [{"role": "user", "content": "..."}]
system_prompt: システムプロンプト
force_model: 特定モデル強制使用
Returns:
{"success": True, "response": ..., "model": "...", "latency_ms": ...}
または
{"success": False, "error": "...", "attempts": [...]}
"""
if force_model:
return await self._single_model_request(
messages, system_prompt, force_model
)
# モデル級フォールバック実行
attempts = []
for tier in self.model_priority:
result = await self._single_model_request(
messages, system_prompt, tier.value
)
attempts.append({
"model": tier.value,
"result": result,
"tier": tier.name
})
if result.get("success"):
return result
# 429 または 5xx でなければ失敗
error_type = result.get("error_type")
if error_type not in ["rate_limit", "server_error", "timeout"]:
# 致命的エラーはこれ以上試行しない
break
return {
"success": False,
"error": "全モデルで失敗",
"attempts": attempts
}
async def _single_model_request(
self,
messages: List[Dict[str, str]],
system_prompt: Optional[str],
model: str
) -> Dict[str, Any]:
"""単一モデルへのリクエスト(リトライ付き)"""
start_time = time.perf_counter()
for attempt in range(self.sla.max_retries):
try:
# システムプロンプト先頭に追加
full_messages = messages.copy()
if system_prompt:
full_messages.insert(0, {
"role": "system",
"content": system_prompt
})
payload = {
"model": model,
"messages": full_messages,
"temperature": 0.7,
"max_tokens": 4096
}
response = await self._client.post(
f"{self.base_url}/chat/completions",
json=payload
)
latency_ms = (time.perf_counter() - start_time) * 1000
# 成功
if response.status_code == 200:
data = response.json()
usage = data.get("usage", {})
input_tokens = usage.get("prompt_tokens", 0)
output_tokens = usage.get("completion_tokens", 0)
# コスト計算(USD)
cost = self._calculate_cost(model, input_tokens, output_tokens)
self.total_cost_usd += cost
metric = RequestMetrics(
model=model,
latency_ms=latency_ms,
status_code=200,
error_type=None,
success=True,
timestamp=time.time()
)
self.metrics.append(metric)
return {
"success": True,
"response": data,
"model": model,
"latency_ms": round(latency_ms, 2),
"tokens": {"input": input_tokens, "output": output_tokens},
"cost_usd": cost,
"attempt": attempt + 1
}
# 429 Too Many Requests
elif response.status_code == 429:
wait_time = self._parse_retry_after(response)
logger.warning(
f"429 Rate Limit on {model}, "
f"waiting {wait_time}s (attempt {attempt + 1})"
)
await asyncio.sleep(wait_time)
metric = RequestMetrics(
model=model,
latency_ms=latency_ms,
status_code=429,
error_type="rate_limit",
success=False,
timestamp=time.time()
)
self.metrics.append(metric)
continue
# 5xx Server Error
elif 500 <= response.status_code < 600:
backoff = min(
self.sla.backoff_base * (2 ** attempt),
self.sla.backoff_max
)
logger.warning(
f"5xx Error {response.status_code} on {model}, "
f"backing off {backoff}s"
)
await asyncio.sleep(backoff)
metric = RequestMetrics(
model=model,
latency_ms=latency_ms,
status_code=response.status_code,
error_type="server_error",
success=False,
timestamp=time.time()
)
self.metrics.append(metric)
continue
# その他のエラー
else:
return {
"success": False,
"error_type": "client_error",
"status_code": response.status_code,
"error": response.text[:500]
}
except httpx.TimeoutException:
logger.warning(f"Timeout on {model}, attempt {attempt + 1}")
await asyncio.sleep(self.sla.backoff_base * (2 ** attempt))
metric = RequestMetrics(
model=model,
latency_ms=self.sla.timeout_seconds * 1000,
status_code=0,
error_type="timeout",
success=False,
timestamp=time.time()
)
self.metrics.append(metric)
continue
except httpx.HTTPError as e:
logger.error(f"HTTP Error on {model}: {e}")
return {
"success": False,
"error_type": "http_error",
"error": str(e)
}
return {
"success": False,
"error_type": "max_retries_exceeded",
"model": model,
"attempts": self.sla.max_retries
}
def _parse_retry_after(self, response: httpx.Response) -> float:
"""Retry-After ヘッダーから待機時間を取得"""
retry_after = response.headers.get("Retry-After")
if retry_after:
try:
return float(retry_after)
except ValueError:
pass
return self.sla.rate_limit_wait
def _calculate_cost(
self,
model: str,
input_tokens: int,
output_tokens: int
) -> float:
"""コスト計算(USD)"""
cost_per_mtok = self.model_costs.get(model, 0)
total_tokens = (input_tokens + output_tokens) / 1_000_000
return cost_per_mtok * total_tokens
def get_sla_report(self) -> Dict[str, Any]:
"""SLAレポート生成"""
if not self.metrics:
return {"error": "No metrics available"}
total = len(self.metrics)
success = sum(1 for m in self.metrics if m.success)
failures_by_type = {}
for m in self.metrics:
if not m.success and m.error_type:
failures_by_type[m.error_type] = \
failures_by_type.get(m.error_type, 0) + 1
latencies = [m.latency_ms for m in self.metrics if m.success]
latencies.sort()
return {
"total_requests": total,
"successful": success,
"failed": total - success,
"availability": round(success / total * 100, 3),
"sla_target_met": (success / total) >= self.sla.target_availability,
"failure_breakdown": failures_by_type,
"latency_p50_ms": latencies[int(len(latencies) * 0.5)] if latencies else 0,
"latency_p95_ms": latencies[int(len(latencies) * 0.95)] if latencies else 0,
"latency_p99_ms": latencies[int(len(latencies) * 0.99)] if latencies else 0,
"total_cost_usd": round(self.total_cost_usd, 4),
"model_usage": self._get_model_usage_stats()
}
def _get_model_usage_stats(self) -> Dict[str, int]:
"""モデル別使用統計"""
stats = {}
for m in self.metrics:
stats[m.model] = stats.get(m.model, 0) + 1
return stats
使用例
async def main():
# HolySheep API キーで初期化
gateway = HolySheepGateway(
api_key="YOUR_HOLYSHEEP_API_KEY",
sla_config=SLAConfig(
max_retries=3,
timeout_seconds=30.0,
target_availability=0.999
)
)
async with gateway:
# フォールバック込みでリクエスト
result = await gateway.chat_completion(
messages=[
{"role": "user", "content": "杭州の天気を教えて"}
],
system_prompt="あなたは помощник AIです。"
)
print(f"成功: {result['success']}")
if result['success']:
print(f"モデル: {result['model']}")
print(f"レイテンシ: {result['latency_ms']}ms")
print(f"コスト: ${result['cost_usd']:.4f}")
# SLAレポート出力
report = gateway.get_sla_report()
print("\n=== SLA レポート ===")
print(f"可用性: {report['availability']}%")
print(f"SLA目標達成: {report['sla_target_met']}")
print(f"P99レイテンシ: {report['latency_p99_ms']}ms")
print(f"総コスト: ${report['total_cost_usd']}")
if __name__ == "__main__":
asyncio.run(main())
Node.js:TypeScript + フォールバックチェーン
/**
* HolySheep AI ゲートウェイ - Node.js/TypeScript 実装
* 429/5xx/タイムアウト自動処理 + モデル級フォールバック
*
* インストール: npm install axios
* 実行: npx ts-node holy-sheep-gateway.ts
*/
import axios, { AxiosInstance, AxiosError } from 'axios';
// ============================================
// 型定義
// ============================================
interface Message {
role: 'system' | 'user' | 'assistant';
content: string;
}
interface ChatCompletionResponse {
id: string;
model: string;
choices: Array<{
message: Message;
finish_reason: string;
index: number;
}>;
usage: {
prompt_tokens: number;
completion_tokens: number;
total_tokens: number;
};
created: number;
}
interface SLAConfig {
maxRetries: number;
timeoutMs: number;
backoffBaseMs: number;
backoffMaxMs: number;
rateLimitWaitMs: number;
}
interface RequestMetric {
model: string;
latencyMs: number;
statusCode: number;
errorType: string | null;
success: boolean;
timestamp: number;
}
interface FallbackResult {
success: boolean;
response?: ChatCompletionResponse;
model?: string;
latencyMs?: number;
costUsd?: number;
error?: string;
attempts?: FallbackAttempt[];
}
interface FallbackAttempt {
model: string;
tier: string;
success: boolean;
latencyMs: number;
errorType?: string;
}
// ============================================
// HolySheep ゲートウェイクライアント
// ============================================
class HolySheepGateway {
private readonly baseUrl = 'https://api.holysheep.ai/v1';
private readonly apiKey: string;
private client: AxiosInstance;
private sla: SLAConfig;
// フォールバック順序(プライマリ→最安値)
private readonly modelPriority = [
{ tier: 'PRIMARY', model: 'gpt-4.1', costPerMTok: 8.00 },
{ tier: 'SECONDARY', model: 'claude-sonnet-4.5', costPerMTok: 15.00 },
{ tier: 'TERTIARY', model: 'gemini-2.5-flash', costPerMTok: 2.50 },
{ tier: 'EMERGENCY', model: 'deepseek-v3.2', costPerMTok: 0.42 }
];
private metrics: RequestMetric[] = [];
private totalCostUsd = 0;
constructor(apiKey: string, sla?: Partial) {
this.apiKey = apiKey;
this.sla = {
maxRetries: sla?.maxRetries ?? 3,
timeoutMs: sla?.timeoutMs ?? 30000,
backoffBaseMs: sla?.backoffBaseMs ?? 1000,
backoffMaxMs: sla?.backoffMaxMs ?? 10000,
rateLimitWaitMs: sla?.rateLimitWaitMs ?? 60000
};
this.client = axios.create({
baseURL: this.baseUrl,
timeout: this.sla.timeoutMs,
headers: {
'Authorization': Bearer ${this.apiKey},
'Content-Type': 'application/json'
}
});
}
/**
* フォールバック機能付きチャット補完
*/
async chatCompletion(
messages: Message[],
systemPrompt?: string
): Promise {
const attempts: FallbackAttempt[] = [];
// 全モデルを試行
for (const { tier, model } of this.modelPriority) {
const result = await this.attemptModel(messages, systemPrompt, model, tier);
attempts.push({
model,
tier,
success: result.success,
latencyMs: result.latencyMs,
errorType: result.errorType
});
if (result.success) {
return {
success: true,
response: result.response,
model,
latencyMs: result.latencyMs,
costUsd: result.costUsd,
attempts
};
}
// 致命的エラーの場合は停止
if (result.errorType === 'client_error') {
break;
}
}
return {
success: false,
error: '全モデルで失敗',
attempts
};
}
/**
* 単一モデルへのリクエスト(リトライ付き)
*/
private async attemptModel(
messages: Message[],
systemPrompt: string | undefined,
model: string,
tier: string
): Promise<{
success: boolean;
response?: ChatCompletionResponse;
latencyMs: number;
costUsd?: number;
errorType?: string;
}> {
const fullMessages = systemPrompt
? [{ role: 'system' as const, content: systemPrompt }, ...messages]
: messages;
for (let attempt = 0; attempt < this.sla.maxRetries; attempt++) {
const startTime = Date.now();
try {
const response = await this.client.post(
'/chat/completions',
{
model,
messages: fullMessages,
temperature: 0.7,
max_tokens: 4096
}
);
const latencyMs = Date.now() - startTime;
if (response.status === 200) {
const data = response.data;
const costUsd = this.calculateCost(
model,
data.usage.prompt_tokens,
data.usage.completion_tokens
);
this.totalCostUsd += costUsd;
this.recordMetric(model, latencyMs, 200, null, true);
return { success: true, response: data, latencyMs, costUsd };
}
// 429 Rate Limit
if (response.status === 429) {
const waitTime = this.parseRetryAfter(response);
console.warn(429 on ${model} (tier: ${tier}), waiting ${waitTime}ms);
await this.sleep(waitTime);
this.recordMetric(model, latencyMs, 429, 'rate_limit', false);
continue;
}
// 5xx Server Error
if (response.status >= 500 && response.status < 600) {
const backoff = Math.min(
this.sla.backoffBaseMs * Math.pow(2, attempt),
this.sla.backoffMaxMs
);
console.warn(5xx (${response.status}) on ${model}, backing off ${backoff}ms);
await this.sleep(backoff);
this.recordMetric(model, latencyMs, response.status, 'server_error', false);
continue;
}
// その他クライアントエラー
this.recordMetric(model, latencyMs, response.status, 'client_error', false);
return {
success: false,
latencyMs,
errorType: 'client_error'
};
} catch (error) {
const latencyMs = Date.now() - startTime;
if (axios.isAxiosError(error)) {
const axiosError = error as AxiosError;
// タイムアウト
if (axiosError.code === 'ECONNABORTED' || axiosError.code === 'ETIMEDOUT') {
const backoff = Math.min(
this.sla.backoffBaseMs * Math.pow(2, attempt),
this.sla.backoffMaxMs
);
console.warn(Timeout on ${model}, backing off ${backoff}ms);
await this.sleep(backoff);
this.recordMetric(model, latencyMs, 0, 'timeout', false);
continue;
}
// ネットワークエラー
console.error(Network error on ${model}: ${axiosError.message});
this.recordMetric(model, latencyMs, 0, 'network_error', false);
return { success: false, latencyMs, errorType: 'network_error' };
}
console.error(Unexpected error on ${model}:, error);
return { success: false, latencyMs, errorType: 'unknown' };
}
}
return { success: false, latencyMs: this.sla.timeoutMs, errorType: 'max_retries' };
}
private parseRetryAfter(response: any): number {
const retryAfter = response.headers?.['retry-after'];
if (retryAfter) {
const parsed = parseInt(retryAfter, 10);
if (!isNaN(parsed)) return parsed * 1000;
}
return this.sla.rateLimitWaitMs;
}
private calculateCost(
model: string,
inputTokens: number,
outputTokens: number
): number {
const tier = this.modelPriority.find(t => t.model === model);
if (!tier) return 0;
const totalMTok = (inputTokens + outputTokens) / 1_000_000;
return tier.costPerMTok * totalMTok;
}
private recordMetric(
model: string,
latencyMs: number,
statusCode: number,
errorType: string | null,
success: boolean
): void {
this.metrics.push({
model,
latencyMs,
statusCode,
errorType,
success,
timestamp: Date.now()
});
}
private sleep(ms: number): Promise {
return new Promise(resolve => setTimeout(resolve, ms));
}
/**
* SLAレポート取得
*/
getSLAReport() {
const total = this.metrics.length;
const success = this.metrics.filter(m => m.success).length;
const failuresByType: Record = {};
this.metrics.filter(m => !m.success).forEach(m => {
if (m.errorType) {
failuresByType[m.errorType] = (failuresByType[m.errorType] || 0) + 1;
}
});
const latencies = this.metrics
.filter(m => m.success)
.map(m => m.latencyMs)
.sort((a, b) => a - b);
const percentile = (p: number) => {
const idx = Math.floor(latencies.length * p);
return latencies[idx] || 0;
};
const modelUsage: Record = {};
this.metrics.forEach(m => {
modelUsage[m.model] = (modelUsage[m.model] || 0) + 1;
});
return {
totalRequests: total,
successful: success,
failed: total - success,
availability: ${((success / total) * 100).toFixed(3)}%,
slaTargetMet: (success / total) >= 0.999,
failureBreakdown: failuresByType,
latencyP50: ${percentile(0.50).toFixed(0)}ms,
latencyP95: ${percentile(0.95).toFixed(0)}ms,
latencyP99: ${percentile(0.99).toFixed(0)}ms,
totalCostUsd: $${this.totalCostUsd.toFixed(4)},
modelUsage
};
}
}
// ============================================
// 使用例
// ============================================
async function main() {
const gateway = new HolySheepGateway(
'YOUR_HOLYSHEEP_API_KEY',
{
maxRetries: 3,
timeoutMs: 30000
}
);
console.log('=== HolySheep AI ゲートウェイ テスト ===\n');
// テストリクエスト
const result = await gateway.chatCompletion(
[
{ role: 'user', content: '深圳のAI企业发展について教えてください' }
],
'你是专业AI助手。请用中文回答。'
);
if (result.success) {
console.log('✅ 成功!');
console.log(モデル: ${result.model});
console.log(レイテンシ: ${result.latencyMs}ms);
console.log(コスト: ${result.costUsd});
console.log(応答: ${result.response?.choices[0]?.message?.content?.substring(0, 100)}...);
} else {
console.log('❌ 全モデルで失敗');
console.log('試行履歴:');
result.attempts?.forEach(a => {
console.log( - ${a.tier} (${a.model}): ${a.success ? '✅' : '❌'} ${a.latencyMs}ms);
});
}
// SLAレポート
console.log('\n=== SLA レポート ===');
const report = gateway.getSLAReport();
console.log(可用性: ${report.availability});
console.log(SLA目標(99.9%)達成: ${report.slaTargetMet});
console.log(P99レイテンシ: ${report.latencyP99});
console.log(総コスト: ${report.totalCostUsd});
console.log('モデル使用内訳:', report.modelUsage);
}
main().catch(console.error);
Go:goroutine + channel による並行フォールバック
// HolySheep AI ゲートウェイ - Go 実装
// go mod init holysheep-gateway
// go get github.com/go-resty/resty/v2
//
// 429/5xx/タイムアウト監視 + モデル級フォールバック
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"math"
"sort"
"sync"
"time"
"github.com/go-resty/resty/v2"
)
// ============================================
// 型定義
// ============================================
type Message struct {
Role string json:"role"
Content string json:"content"
}
type ChatRequest struct {
Model string json:"model"
Messages []Message json:"messages"
Temperature float64 json:"temperature"
MaxTokens int json:"max_tokens"
}
type Usage struct {
PromptTokens int json:"prompt_tokens"
CompletionTokens int json:"completion_tokens"
TotalTokens int json:"total_tokens"
}
type ChatResponse struct {
ID string json:"id"
Model string json:"model"
Choices []Choice json:"choices"
Usage Usage json:"usage"
Created int64 json:"created"
}
type Choice struct {
Message Message json:"message"
FinishReason string json:"finish_reason"
Index int json:"index"
}
type ModelTier struct {
Name string
Model string
CostPerMTok float64
}
type RequestMetric struct {
Model string
LatencyMs int64
StatusCode int
ErrorType string
Success bool
Timestamp int64
}
type FallbackAttempt struct {
Model string json:"model"
Tier string json:"tier"
Success bool json:"success"
LatencyMs int64 json:"latency_ms"
ErrorType string json:"error_type,omitempty"
}
type FallbackResult struct {
Success bool json:"success"
Response *ChatResponse json:"response,omitempty"
Model string json:"model,omitempty"
LatencyMs int64 json:"latency_ms,omitempty"
CostUSD float64 json:"cost_usd,omitempty"