メインコンテンツへスキップ

モデルの選択

適切なモデルを選択することは、コストと品質に大きな影響を与えます。

タスク別の推奨事項

タスク推奨モデル理由
シンプルな Q&Agpt-4o-mini, gemini-2.5-flash高速、低コスト、十分な品質
複雑な推論o3, claude-opus-4-5, deepseek-r1より優れた論理と計画
コーディングclaude-sonnet-4-5, gpt-4o, deepseek-v3.2コードに最適化
クリエイティブライティングclaude-sonnet-4-5, gpt-4oより優れた文章品質
ビジョン/画像gpt-4o, claude-sonnet-4-5, gemini-2.5-flashネイティブのビジョンサポート
長いコンテキストgemini-2.5-pro, claude-sonnet-4-5100万以上のトークンウィンドウ
コスト重視gpt-4o-mini, gemini-2.5-flash, deepseek-v3.2最高のコスパ

コスト階層

$$$$ Premium: o3, claude-opus-4-5, gpt-4o
$$$  Standard: claude-sonnet-4-5, gpt-4o
$$   Budget:   gpt-4o-mini, gemini-2.5-flash
$    Economy:  deepseek-v3.2, deepseek-r1

コストの最適化

1. 最初に小規模なモデルを使用する

def smart_query(question: str, complexity: str = "auto"):
    """Use cheaper models for simple tasks."""

    if complexity == "simple":
        model = "gpt-4o-mini"
    elif complexity == "complex":
        model = "gpt-4o"
    else:
        # Start cheap, escalate if needed
        model = "gpt-4o-mini"

    response = client.chat.completions.create(
        model=model,
        messages=[{"role": "user", "content": question}]
    )
    return response

2. max_tokens を設定する

常に適切な max_tokens 制限を設定してください:
# ❌ Bad: No limit, could generate thousands of tokens
response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "Summarize this article"}]
)

# ✅ Good: Limit response length
response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "Summarize this article"}],
    max_tokens=500  # Reasonable limit for a summary
)

3. プロンプトを最適化する

# ❌ Verbose prompt (more input tokens)
prompt = """
I would like you to please help me by analyzing the following text
and providing a comprehensive summary of the main points. Please be
thorough but also concise in your response. The text is as follows:
{text}
"""

# ✅ Concise prompt (fewer tokens)
prompt = "Summarize the key points:\n{text}"

4. キャッシュを有効にする

セマンティックキャッシュを活用してください:
# For repeated similar queries, caching provides major savings
response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "What is machine learning?"}],
    temperature=0  # Deterministic = better cache hits
)

5. 同様のリクエストをバッチ処理する

# ❌ Many small requests
for question in questions:
    response = client.chat.completions.create(
        model="gpt-4o",
        messages=[{"role": "user", "content": question}]
    )

# ✅ Fewer larger requests
combined_prompt = "\n".join([f"{i+1}. {q}" for i, q in enumerate(questions)])
response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": f"Answer each question:\n{combined_prompt}"}]
)

パフォーマンスの最適化

1. UX のためにストリーミングを使用する

ストリーミングは体感パフォーマンスを向上させます:
stream = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "Write a long essay"}],
    stream=True
)

for chunk in stream:
    if chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)

2. インタラクティブな用途には高速なモデルを選択する

ユースケース推奨レイテンシ
チャット UIgpt-4o-mini, gemini-2.5-flash最初のトークンまで約200ms
タブ補完claude-haiku-4-5最初のトークンまで約150ms
バックグラウンド処理gpt-4o, claude-sonnet-4-5最初のトークンまで約500ms

3. タイムアウトを設定する

client = OpenAI(
    api_key="sk-your-key",
    base_url="https://api.lemondata.cc/v1",
    timeout=60.0  # 60 second timeout
)

信頼性

1. リトライを実装する

import time
from openai import RateLimitError, APIError

def chat_with_retry(messages, max_retries=3):
    for attempt in range(max_retries):
        try:
            return client.chat.completions.create(
                model="gpt-4o",
                messages=messages
            )
        except RateLimitError:
            wait = 2 ** attempt
            print(f"Rate limited, waiting {wait}s...")
            time.sleep(wait)
        except APIError as e:
            if attempt == max_retries - 1:
                raise
            time.sleep(1)
    raise Exception("Max retries exceeded")

2. エラーを適切に処理する

from openai import APIError, AuthenticationError, RateLimitError

try:
    response = client.chat.completions.create(...)
except AuthenticationError:
    # Check API key
    notify_admin("Invalid API key")
except RateLimitError:
    # Queue for later or use backup
    add_to_queue(request)
except APIError as e:
    if e.status_code == 402:
        notify_admin("Balance low")
    elif e.status_code >= 500:
        # Server error, retry later
        schedule_retry(request)

3. フォールバックモデルを使用する

FALLBACK_CHAIN = ["gpt-4o", "claude-sonnet-4-5", "gemini-2.5-flash"]

def chat_with_fallback(messages):
    for model in FALLBACK_CHAIN:
        try:
            return client.chat.completions.create(
                model=model,
                messages=messages
            )
        except APIError:
            continue
    raise Exception("All models failed")

セキュリティ

1. API キーを保護する

# ❌ Never hardcode keys
client = OpenAI(api_key="sk-abc123...")

# ✅ Use environment variables
import os
client = OpenAI(api_key=os.environ["LEMONDATA_API_KEY"])

2. ユーザー入力を検証する

def validate_message(content: str) -> bool:
    """Validate user input before sending to API."""
    if len(content) > 100000:
        raise ValueError("Message too long")
    # Add other validation as needed
    return True

3. API キーの制限を設定する

以下の用途ごとに、支出制限を設定した個別の API キーを作成してください:
  • 開発/テスト
  • 本番
  • 異なるアプリケーション

モニタリング

1. 使用状況を追跡する

ダッシュボードを定期的にチェックして、以下を確認してください:
  • モデル別のトークン使用量
  • コストの内訳
  • キャッシュヒット率
  • エラー率

2. 重要なメトリクスをログに記録する

import logging

response = client.chat.completions.create(...)

logging.info({
    "model": response.model,
    "prompt_tokens": response.usage.prompt_tokens,
    "completion_tokens": response.usage.completion_tokens,
    "total_tokens": response.usage.total_tokens,
})

3. アラートを設定する

サービスの停止を避けるために、ダッシュボードで残高不足のアラートを設定してください。

チェックリスト

  • 各タスクに適切なモデルを使用している
  • max_tokens 制限を設定している
  • プロンプトが簡潔である
  • 適切な場所でキャッシュが有効になっている
  • 同様のリクエストをバッチ処理している
  • インタラクティブな UX のためのストリーミング
  • リアルタイム用途の高速モデル
  • タイムアウトが設定されている
  • リトライロジックが実装されている
  • エラー処理が整っている
  • フォールバックモデルが設定されている
  • API キーが環境変数にある
  • 入力検証
  • 開発/本番用の個別のキー
  • 支出制限が設定されている