跳轉到主要內容

模型選擇

選擇合適的模型會顯著影響成本與品質。

基於任務的建議

任務推薦模型原因
簡單問答gpt-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-51M+ token 視窗
成本敏感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 限制:
# ❌ 錯誤:未設限制,可能會產生數千個 token
response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "Summarize this article"}]
)

# ✅ 正確:限制回應長度
response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "Summarize this article"}],
    max_tokens=500  # 摘要的合理限制
)

3. 優化 Prompt

# ❌ 冗長的 prompt (消耗更多 input token)
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}
"""

# ✅ 簡潔的 prompt (消耗較少 token)
prompt = "Summarize the key points:\n{text}"

4. 啟用快取

善用 語義快取
# 對於重複的相似查詢,快取可大幅節省成本
response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "What is machine learning?"}],
    temperature=0  # 確定性 = 更好的快取命中率
)

5. 批次處理相似請求

# ❌ 許多小型請求
for question in questions:
    response = client.chat.completions.create(
        model="gpt-4o",
        messages=[{"role": "user", "content": question}]
    )

# ✅ 較少的大型請求
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. 使用串流 (Streaming) 提升使用者體驗

串流可以提升感知的效能:
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. 為互動式用途選擇快速模型

使用場景推薦模型延遲
聊天介面gpt-4o-mini, gemini-2.5-flash首個 token 約 200ms
自動補全claude-haiku-4-5首個 token 約 150ms
背景處理gpt-4o, claude-sonnet-4-5首個 token 約 500ms

3. 設定逾時 (Timeouts)

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

可靠性

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:
    # 檢查 API key
    notify_admin("Invalid API key")
except RateLimitError:
    # 加入隊列稍後處理或使用備援
    add_to_queue(request)
except APIError as e:
    if e.status_code == 402:
        notify_admin("Balance low")
    elif e.status_code >= 500:
        # 伺服器錯誤,稍後重試
        schedule_retry(request)

3. 使用備援模型 (Fallback Models)

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 Key

# ❌ 切勿將金鑰寫死在程式碼中
client = OpenAI(api_key="sk-abc123...")

# ✅ 使用環境變數
import os
client = OpenAI(api_key=os.environ["LEMONDATA_API_KEY"])

2. 驗證使用者輸入

def validate_message(content: str) -> bool:
    """在發送到 API 之前驗證使用者輸入。"""
    if len(content) > 100000:
        raise ValueError("Message too long")
    # 根據需要添加其他驗證
    return True

3. 設定 API Key 限制

為以下用途建立具備支出限制的獨立 API Key:
  • 開發/測試
  • 正式環境
  • 不同的應用程式

監控

1. 追蹤使用量

定期檢查您的控制面板以了解:
  • 各模型的 token 使用量
  • 費用明細
  • 快取命中率
  • 錯誤率

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 限制
  • Prompt 保持簡潔
  • 在適當的地方啟用快取
  • 批次處理相似請求
  • 為互動式體驗使用串流
  • 為即時用途使用快速模型
  • 已配置逾時設定
  • 已實作重試邏輯
  • 錯誤處理已就緒
  • 已配置備援模型
  • API Key 儲存於環境變數中
  • 輸入驗證
  • 開發/正式環境使用獨立金鑰
  • 已設定支出限制