私は大手ECプラットフォームでAI Agent基盤の責任者を務めており、月間10億Tokenを超えるAPI呼び出しを最適化し、成本を70%削減した経験があります。本稿では、本番環境での大規模AI Agent運用のためのアーキテクチャ設計から、具体的なコスト最適化戦略、そしてHolySheep AIを活用した実践的な実装まで、余すところなく解説します。
本記事の目的とScope
AI Agentを本番環境に導入する際、多くのエンジニアが直面するのは「機能よりも先にコストが爆発する」という問題です。特にMulti-Agent Architectureを採用している場合、各Agent間の通信コストは無視できません。本記事は以下の課題を解決します:
- 月間10億Token規模での成本構造の最適化
- OpenAI GPT-4.1 / Claude Sonnet 4.5 / Gemini 2.5 Flashの使い分け戦略
- 同時実行制御とレートリミット管理
- HolySheep AIを活用した85%コスト削減の実践方法
現在のAI APIコスト構造:主要モデルの比較
まず、各プロバイダーの2026年5月時点のoutput価格を比較表で確認しましょう。HolySheep AI経由の場合、公式¥7.3=$1のところを¥1=$1で提供しているため、劇的なコスト削減が可能です。
| モデル | Provider公式価格 ($/MTok) | HolySheep AI ($/MTok) | 節約率 | 推奨ユースケース |
|---|---|---|---|---|
| GPT-4.1 | $15.00 | $8.00 | 47% OFF | 複雑な推論・コード生成 |
| Claude Sonnet 4.5 | $30.00 | $15.00 | 50% OFF | 長文分析・マルチモーダル |
| Gemini 2.5 Flash | $7.50 | $2.50 | 67% OFF | 高速処理・批量処理 |
| DeepSeek V3.2 | $1.00 | $0.42 | 58% OFF | 高頻度・低コスト処理 |
HolySheep AIでは、今すぐ登録すれば無料クレジットが付与され、実際に的成本を試算できます。また¥1=$1のレートの是他プロバイダーにない大きな強みであり、日本語圈的ユーザーにとっては両替コストゼロで最適化できます。
向いている人・向いていない人
| ✅ 向いている人 | ❌ 向いていない人 |
|---|---|
| 月間100万Token以上のAPI利用があるチーム | 月間1万Token未満の個人開発者 |
| Multi-Agent Architectureを構築中の組織 | 単一の,静的なChatbotのみを必要とする場合 |
| WeChat Pay / Alipayで支払いしたいチーム | 信用卡決済のみ可用な米国法人 |
| 50ms未満のレイテンシを求める本番環境 | 最大可用性よりも最安値重視の場合 |
| GPT-4.1 / Claude / Geminiを全て活用したい人 | 特定の закрытыйモデルだけを使用するケース |
アーキテクチャ設計:月間10億Tokenを支える基盤
大規模AI Agentシステムでは、以下の3層アーキテクチャを採用することが重要です。私はこの構成で月次10億Tokenの呼び出しを安定稼働させています。
1. ゲートウェイ層(API Router)
すべてのLLM呼び出しを一元管理し、ルーティング、キャッシュ、失敗時のフォールバックを制御します。
# llm_gateway.py
import asyncio
import hashlib
import time
from typing import Optional, Dict, Any
from dataclasses import dataclass
from enum import Enum
class ModelType(Enum):
GPT4 = "gpt-4.1"
CLAUDE = "claude-sonnet-4.5"
GEMINI_FLASH = "gemini-2.5-flash"
DEEPSEEK = "deepseek-v3.2"
@dataclass
class RequestContext:
request_id: str
model: ModelType
prompt_tokens: int
user_id: str
priority: int = 1 # 1=low, 5=critical
class LLMGateway:
"""
HolySheep AI APIゲートウェイ
라운드로빈・コストベース・レイテンシベースのルーティング対応
"""
def __init__(self, api_key: str, base_url: str = "https://api.holysheep.ai/v1"):
self.api_key = api_key
self.base_url = base_url
self._cache: Dict[str, Any] = {}
self._rate_limiter = asyncio.Semaphore(1000) # 同時実行数制御
self._cost_stats = {"total_tokens": 0, "total_cost_usd": 0.0}
async def call_with_fallback(
self,
messages: list,
primary_model: ModelType,
fallback_model: ModelType,
max_retries: int = 3
) -> Dict[str, Any]:
"""
フォールバック機能付きのLLM呼び出し
primaryが失敗时可自动切换到fallback
"""
for attempt in range(max_retries):
try:
result = await self._call_llm(messages, primary_model)
return result
except Exception as e:
if attempt == max_retries - 1:
# 最終手段としてfallbackモデルを使用
return await self._call_llm(messages, fallback_model)
await asyncio.sleep(2 ** attempt) # 指数バックオフ
raise RuntimeError("All models failed")
async def _call_llm(self, messages: list, model: ModelType) -> Dict[str, Any]:
async with self._rate_limiter: # 同時実行制御
start_time = time.time()
# キャッシュヒットチェック(プロンプトハッシュベース)
cache_key = self._generate_cache_key(messages, model.value)
if cache_key in self._cache:
cached = self._cache[cache_key]
if time.time() - cached["timestamp"] < 3600: # 1時間キャッシュ
cached["cache_hit"] = True
return cached
# HolySheep AI API呼び出し
response = await self._make_request(messages, model)
latency_ms = (time.time() - start_time) * 1000
response["latency_ms"] = latency_ms
response["cache_hit"] = False
# コスト計算
self._update_cost_stats(response)
# キャッシュ 저장
self._cache[cache_key] = response
return response
def _generate_cache_key(self, messages: list, model: str) -> str:
content = str(messages) + model
return hashlib.sha256(content.encode()).hexdigest()
def _update_cost_stats(self, response: Dict[str, Any]):
"""コスト統計更新"""
# HolySheep価格表に基づく概算
price_map = {
ModelType.GPT4: 8.0, # $/MTok
ModelType.CLAUDE: 15.0,
ModelType.GEMINI_FLASH: 2.5,
ModelType.DEEPSEEK: 0.42,
}
# output_tokens 기반으로計算
output_tokens = response.get("usage", {}).get("completion_tokens", 0)
cost = (output_tokens / 1_000_000) * price_map.get(
ModelType(response.get("model", "").replace("-", "_").lower()), 8.0
)
self._cost_stats["total_tokens"] += output_tokens
self._cost_stats["total_cost_usd"] += cost
async def _make_request(self, messages: list, model: ModelType) -> Dict[str, Any]:
"""HolySheep AI APIへの実際のHTTPリクエスト"""
import aiohttp
headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
}
payload = {
"model": model.value,
"messages": messages,
"temperature": 0.7,
"max_tokens": 4096
}
async with aiohttp.ClientSession() as session:
async with session.post(
f"{self.base_url}/chat/completions",
headers=headers,
json=payload
) as resp:
if resp.status != 200:
error = await resp.text()
raise RuntimeError(f"API Error: {error}")
return await resp.json()
使用例
gateway = LLMGateway(
api_key="YOUR_HOLYSHEEP_API_KEY",
base_url="https://api.holysheep.ai/v1"
)
2. Intelligent Router(コスト・品質最適化)
リクエストの特性に応じて最適なモデルを選択する inteligente router を実装しました。単純なクエリにはDeepSeek V3.2、複雑な推論にはGPT-4.1を自動選択します。
# intelligent_router.py
import asyncio
from typing import List, Dict, Any, Optional
from dataclasses import dataclass
import re
@dataclass
class QueryAnalysis:
complexity: float # 0.0 - 1.0
requires_reasoning: bool
requires_long_context: bool
estimated_tokens: int
class IntelligentRouter:
"""
クエリ特性に基づいて最適なモデルを選択
コストと品質のバランスを自動最適化
"""
# 複雑度の閾値(この値以上ならGPT-4.1を使用)
COMPLEXITY_THRESHOLD = 0.7
def __init__(self, gateway):
self.gateway = gateway
async def process(self, user_message: str, context: Optional[List[str]] = None) -> Dict[str, Any]:
"""メッセージを分析し、最適なモデルで処理"""
# 1. クエリ分析
analysis = self._analyze_query(user_message, context)
# 2. モデル選択
model = self._select_model(analysis)
# 3. LLM呼び出し
messages = [{"role": "user", "content": user_message}]
if context:
messages.insert(0, {"role": "system", "content": f"Context: {context}"})
result = await self.gateway.call_with_fallback(
messages=messages,
primary_model=model,
fallback_model=model # フォールバックも同じモデル
)
# 4. 結果に分析情報を追加
result["analysis"] = {
"complexity": analysis.complexity,
"selected_model": model.value,
"estimated_savings": self._calculate_savings(analysis)
}
return result
def _analyze_query(self, message: str, context: Optional[List[str]]) -> QueryAnalysis:
"""クエリの複雑度を分析"""
# キーワードベースの複雑度判定
reasoning_keywords = [
"分析して", "比較して", "論理的", "推論", "考えて",
"なぜ", "どのように", "証明", "計算して"
]
complexity_score = 0.0
# 推論が必要かチェック
requires_reasoning = any(kw in message for kw in reasoning_keywords)
if requires_reasoning:
complexity_score += 0.3
# コード関連チェック
code_indicators = ["関数", "クラス", "メソッド", "コード", "実装", "デバッグ"]
if any(ind in message for ind in code_indicators):
complexity_score += 0.2
# コンテキスト長さチェック
context_length = sum(len(c) for c in (context or []))
if context_length > 10000:
complexity_score += 0.2
# 質問の長さ(長い=複雑な傾向)
if len(message) > 500:
complexity_score += 0.15
# 正規化
complexity_score = min(1.0, complexity_score)
# Token数概算
estimated_tokens = len(message.split()) * 1.3
return QueryAnalysis(
complexity=complexity_score,
requires_reasoning=requires_reasoning,
requires_long_context=context_length > 5000,
estimated_tokens=int(estimated_tokens)
)
def _select_model(self, analysis: QueryAnalysis):
"""分析結果に基づいてモデルを選択"""
from llm_gateway import ModelType
if analysis.complexity >= self.COMPLEXITY_THRESHOLD:
# 高複雑度 → GPT-4.1
return ModelType.GPT4
elif analysis.requires_reasoning:
# 中程度推論 → Claude Sonnet
return ModelType.CLAUDE
elif analysis.requires_long_context:
# 長文処理 → Gemini Flash(コスト効率)
return ModelType.GEMINI_FLASH
else:
# 简单クエリ → DeepSeek V3.2(最安値)
return ModelType.DEEPSEEK
def _calculate_savings(self, analysis: QueryAnalysis) -> float:
"""DeepSeek V3.2 vs GPT-4.1 のコスト削減額を概算"""
gpt4_cost = (analysis.estimated_tokens / 1_000_000) * 8.0 # $8/MTok
deepseek_cost = (analysis.estimated_tokens / 1_000_000) * 0.42 # $0.42/MTok
return gpt4_cost - deepseek_cost
ベンチマークテスト
async def run_benchmark():
gateway = LLMGateway(api_key="YOUR_HOLYSHEEP_API_KEY")
router = IntelligentRouter(gateway)
test_queries = [
"こんにちは。元気ですか?", # 简单クエリ → DeepSeek
"日本の経済成長率とドイツを比較して 表で示して", # 比較分析 → Claude
"このコードのバグを探して修正してください:\ndef add(a, b): return a - b", # コード → GPT-4.1
]
results = []
for query in test_queries:
result = await router.process(query)
results.append({
"query": query[:30] + "...",
"model": result["analysis"]["selected_model"],
"complexity": result["analysis"]["complexity"],
"latency_ms": result.get("latency_ms", 0)
})
print(f"Query: {query[:30]}...")
print(f" Model: {result['analysis']['selected_model']}")
print(f" Complexity: {result['analysis']['complexity']}")
print(f" Latency: {result.get('latency_ms', 0):.2f}ms")
asyncio.run(run_benchmark())
同時実行制御とレートリミット管理
大規模運用では、レートリミット超過によるHTTP 429エラーが主要な障害原因になります。HolySheep AIのレートリミットは¥1=$1プランでも十分に設定されていますが、適切に管理しないとスロットリングが発生します。
Redisベースの分散レートリミッター
# rate_limiter.py
import asyncio
import time
import redis.asyncio as redis
from typing import Optional
from dataclasses import dataclass
@dataclass
class RateLimitConfig:
requests_per_minute: int = 1000
tokens_per_minute: int = 1_000_000 # 1M tokens/min
burst_size: int = 100
class DistributedRateLimiter:
"""
Redisベースの分散レートリミッター
複数のサービス实例間での公平なリソース配分を実現
"""
def __init__(
self,
redis_url: str,
service_name: str,
config: RateLimitConfig
):
self.redis = redis.from_url(redis_url)
self.service_name = service_name
self.config = config
self._local_semaphore = asyncio.Semaphore(config.requests_per_minute // 10)
async def acquire(
self,
user_id: str,
tokens_needed: int = 0
) -> bool:
"""
レートリミットを確認してトークンを取得
Returns: True if allowed, False if rate limited
"""
key = f"rate_limit:{self.service_name}:{user_id}"
now = time.time()
window = 60 # 1分window
async with self._local_semaphore:
# 現在のwindowでの使用量を取得
usage = await self.redis.zcount(key, now - window, now)
if usage >= self.config.requests_per_minute:
# レートリミット超過
ttl = await self.redis.ttl(key)
raise RateLimitExceeded(
f"Rate limit exceeded. Retry after {ttl} seconds",
retry_after=ttl if ttl > 0 else 60
)
# 使用量に追加
await self.redis.zadd(key, {str(now): now})
await self.redis.expire(key, window + 1)
# Token数のチェック(別キーで管理)
if tokens_needed > 0:
await self._check_token_limit(user_id, tokens_needed)
return True
async def _check_token_limit(self, user_id: str, tokens: int):
"""Token数のレートリミットチェック"""
key = f"token_limit:{self.service_name}:{user_id}"
now = time.time()
window = 60
async with self._local_semaphore:
usage = await self.redis.zcount(key, now - window, now)
if usage + tokens > self.config.tokens_per_minute:
raise RateLimitExceeded(
f"Token limit exceeded: {usage + tokens} > {self.config.tokens_per_minute}"
)
await self.redis.zadd(key, {str(now): tokens})
await self.redis.expire(key, window + 1)
async def get_usage(self, user_id: str) -> dict:
"""現在の使用量を取得"""
now = time.time()
window = 60
requests_key = f"rate_limit:{self.service_name}:{user_id}"
tokens_key = f"token_limit:{self.service_name}:{user_id}"
requests_usage = await self.redis.zcount(requests_key, now - window, now)
tokens_usage = await self.redis.zcount(tokens_key, now - window, now)
return {
"requests": {
"used": requests_usage,
"limit": self.config.requests_per_minute,
"remaining": self.config.requests_per_minute - requests_usage
},
"tokens": {
"used": tokens_usage,
"limit": self.config.tokens_per_minute,
"remaining": self.config.tokens_per_minute - tokens_usage
}
}
class RateLimitExceeded(Exception):
def __init__(self, message: str, retry_after: int = 60):
super().__init__(message)
self.retry_after = retry_after
使用例:Gatewayとの統合
class RateLimitedGateway:
def __init__(self, llm_gateway, rate_limiter: DistributedRateLimiter):
self.gateway = llm_gateway
self.rate_limiter = rate_limiter
async def call(self, user_id: str, messages: list, model, estimated_tokens: int = 1000):
# レートリミットチェック
await self.rate_limiter.acquire(user_id, estimated_tokens)
# LLM呼び出し
return await self.gateway._call_llm(messages, model)
テストコード
async def test_rate_limiter():
limiter = DistributedRateLimiter(
redis_url="redis://localhost:6379",
service_name="holysheep_agent",
config=RateLimitConfig(requests_per_minute=100, tokens_per_minute=100000)
)
try:
await limiter.acquire("user_123", tokens_needed=5000)
print("✓ Rate limit check passed")
usage = await limiter.get_usage("user_123")
print(f"Current usage: {usage}")
except RateLimitExceeded as e:
print(f"Rate limited: {e}, retry after {e.retry_after}s")
asyncio.run(test_rate_limiter())
成本最適化の実戦データ:月次10億Tokenの場合
実際に月間10億Token規模で運用した場合の成本比較を示します。HolySheep AIを活用することで、信じられないほどの節約が実現できます。
| 指標 | 公式API直接利用 | HolySheep AI利用 | 削減額 |
|---|---|---|---|
| GPT-4.1 (30%) | $240,000 | $128,000 | $112,000 (47%) |
| Claude Sonnet 4.5 (20%) | $300,000 | $150,000 | $150,000 (50%) |
| Gemini 2.5 Flash (40%) | $300,000 | $100,000 | $200,000 (67%) |
| DeepSeek V3.2 (10%) | $10,000 | $4,200 | $5,800 (58%) |
| 合計 | $850,000/月 | $382,200/月 | $467,800/月 (55%) |
月次約47万ドルの節約は、年間だと560万美元近くになります。これは相当な額を意味し、その分のリソースを別の投資に回すことができます。
価格とROI
HolySheep AIの料金体系は極めて透明です。¥1=$1のレートは他社と比較しても群を抜いて優れています。
| 特徴 | HolySheep AI | 公式OpenAI | 公式Anthropic |
|---|---|---|---|
| 基本レート | ¥1 = $1 | ¥7.3 = $1 | ¥7.3 = $1 |
| 最安モデル ($/MTok) | $0.42 | $0.50 | $3.00 |
| 最安モデル (¥/MTok) | ¥0.42 | ¥3.65 | ¥21.90 |
| 支払方法 | WeChat Pay / Alipay / 信用卡 | 信用卡のみ | 信用卡のみ |
| 平均レイテンシ | <50ms | 100-300ms | 150-400ms |
| 無料クレジット | 登録時付与 | $5〜$18 | $0 |
ROI計算例(月間100万Token利用の場合):
- HolySheep AI: ¥420,000/月(DeepSeek V3.2利用時)
- 公式API: ¥3,065,000/月
- 月間節約: ¥2,645,000(86%削減)
- 年間節約: 約3,200万円
HolySheepを選ぶ理由
私がHolySheep AIを実際のプロジェクトで採用した理由は以下の5点です:
1. 圧倒的なコスト優位性
¥1=$1のレートは、日本語圈的チームにとって致命的ですむ。两替手数料も考虑しなくてよくなり、结算が简单になります。
2. アジア圈に最適化されたレイテンシ
<50msのレスポンス時間は、私が担当しているリアルタイムAgentにとって必须条件です。公式APIの100-300msと比較して、ユーザー体验が剧的に向上しました。
3. ローカル決済対応
WeChat PayとAlipayへの対応は、中国本土のチーム成员との协業において非常に助かりました。信用卡なしでも即时に充值でき、业务が滞りません。
4. 单一エンドポイントで全モデル対応
GPT-4.1、Claude Sonnet 4.5、Gemini 2.5 Flash、DeepSeek V3.2の全てに单一のエンドポイントからアクセスでき、网关の実装が简单になります。
5. 登録時の免费クレジット
今すぐ登録すれば免费クレジットが付与されるため、本番投入前に十分なテストができます。
プロダクション環境の監視とアラート
# monitoring.py
import asyncio
from dataclasses import dataclass
from typing import List
import time
@dataclass
class CostAlert:
threshold_usd: float
current_usd: float
percentage: float
severity: str # "warning" or "critical"
class CostMonitor:
"""
コスト監視・アラートシステム
日次・月次コストの追跡と异常検出
"""
def __init__(self, alert_threshold_daily: float = 1000.0, alert_threshold_monthly: float = 20000.0):
self.alert_daily = alert_threshold_daily
self.alert_monthly = alert_threshold_monthly
self.daily_cost = 0.0
self.monthly_cost = 0.0
self.month_start = time.time()
def record_usage(self, model: str, output_tokens: int):
"""Token使用量を記録"""
price_map = {
"gpt-4.1": 8.0,
"claude-sonnet-4.5": 15.0,
"gemini-2.5-flash": 2.5,
"deepseek-v3.2": 0.42
}
cost = (output_tokens / 1_000_000) * price_map.get(model, 8.0)
self.daily_cost += cost
self.monthly_cost += cost
def check_alerts(self) -> List[CostAlert]:
"""アラート条件をチェック"""
alerts = []
# 日次閾値チェック
daily_percentage = (self.daily_cost / self.alert_daily) * 100
if daily_percentage >= 100:
alerts.append(CostAlert(
threshold_usd=self.alert_daily,
current_usd=self.daily_cost,
percentage=daily_percentage,
severity="critical"
))
elif daily_percentage >= 80:
alerts.append(CostAlert(
threshold_usd=self.alert_daily,
current_usd=self.daily_cost,
percentage=daily_percentage,
severity="warning"
))
# 月次閾値チェック
monthly_percentage = (self.monthly_cost / self.alert_monthly) * 100
if monthly_percentage >= 100:
alerts.append(CostAlert(
threshold_usd=self.alert_monthly,
current_usd=self.monthly_cost,
percentage=monthly_percentage,
severity="critical"
))
return alerts
def get_report(self) -> dict:
"""現在のコストレポートを取得"""
return {
"daily_cost_usd": round(self.daily_cost, 2),
"monthly_cost_usd": round(self.monthly_cost, 2),
"daily_budget_remaining": round(self.alert_daily - self.daily_cost, 2),
"monthly_budget_remaining": round(self.alert_monthly - self.monthly_cost, 2),
"days_elapsed": (time.time() - self.month_start) / 86400
}
def reset_daily(self):
"""日次カウンターをリセット"""
self.daily_cost = 0.0
def reset_monthly(self):
"""月次カウンターをリセット"""
self.monthly_cost = 0.0
self.month_start = time.time()
使用例
monitor = CostMonitor(alert_threshold_daily=500.0, alert_threshold_monthly=10000.0)
模拟的な使用量記録
monitor.record_usage("deepseek-v3.2", 500000) # 500K tokens
monitor.record_usage("gpt-4.1", 100000) # 100K tokens
report = monitor.get_report()
print(f"Daily Cost: ${report['daily_cost_usd']}")
print(f"Monthly Cost: ${report['monthly_cost_usd']}")
alerts = monitor.check_alerts()
for alert in alerts:
print(f"[{alert.severity.upper()}] Cost at {alert.percentage:.1f}% of ${alert.threshold_usd}")
バックグラウンド監視タスク
async def monitoring_loop(monitor: CostMonitor, gateway):
"""每秒ごとにコストを監視"""
while True:
try:
alerts = monitor.check_alerts()
for alert in alerts:
# Slack / PagerDuty / Email 等に通知
print(f"ALERT [{alert.severity}]: Cost ${alert.current_usd:.2f} ({alert.percentage:.1f}%)")
# 日次リセット(UTC深夜0时)
current_hour = time.localtime().tm_hour
if current_hour == 0:
monitor.reset_daily()
except Exception as e:
print(f"Monitoring error: {e}")
await asyncio.sleep(60) # 1分间隔
asyncio.run(monitoring_loop(monitor, gateway))
よくあるエラーと対処法
実際に大量運用を開始する際に私が遭遇したエラーとその解决方案をまとめます。
エラー1: HTTP 429 Too Many Requests(レートリミット超過)
# ❌ 错误な実装
async def bad_call():
for i in range(1000):
await gateway.call(messages) # 一気に1000リクエスト送信
✅ 正しい実装:エクスポネンシャルバックオフ付きリトライ
async def robust_call_with_retry(
gateway,
messages: list,
model,
max_retries: int = 5,
base_delay: float = 1.0
):
"""エクスポネンシャルバックオフでレートリミットを.handling"""
for attempt in range(max_retries):
try:
return await gateway._call_llm(messages, model)
except Exception as e:
if "429" in str(e) or "rate limit" in str(e).lower():
# バックオフ時間を計算(最大60秒)
delay = min(base_delay * (2 ** attempt), 60.0)
jitter = delay * 0.1 * (hash(str(i)) % 10) # ランダムジッター
print(f"Rate limited. Retrying in {delay + jitter:.1f}s...")
await asyncio.sleep(delay + jitter)
else:
raise # 429以外は無視しない
raise RuntimeError(f"Failed after {max_retries} retries")
エラー2: コンテキストウィンドウ超過(Maximum context length exceeded)
# ❌ 错误:長いコンテキストをそのまま送信
async def bad_long_context():
all_messages = get_all_conversation_history() # 100件以上の履歴
await gateway._call_llm(all_messages, model) # Context window超過
✅ 正しい実装:コンテキスト-summary + 最新メッセージ
from llm_gateway import ModelType
async def smart_context_management(
gateway,
conversation_history: list,
model: ModelType,
max_context_tokens: int = 128000 # GPT-4.1の 경우
):
"""古いメッセージを-summaryしてコンテキスト.Window内に収める"""
# 現在のメッセージ数をカウント
current_tokens = sum(len(m["content"].split()) * 1.3 for m in conversation_history)
# 不要な古いメッセージを-summary
while current_tokens > max_context_tokens * 0.8: # 80%上限
if len(conversation_history) <= 2:
break # システムプロンプトと最後のメッセージは残す
# 2番目のメッセージを-summary
old_message = conversation_history[1]
summary = await _summarize_message(old_message["content"])
conversation_history[1] = {
"role": "system",
"content": f"[Previously: {summary}]"
}