Chuyển đến nội dung chính

Lựa chọn Mô hình

Việc chọn đúng mô hình có thể ảnh hưởng đáng kể đến chi phí và chất lượng.

Khuyến nghị theo Nhiệm vụ

Nhiệm vụMô hình khuyến nghịLý do
Hỏi đáp đơn giảngpt-4o-mini, gemini-2.5-flashNhanh, rẻ, đủ tốt
Suy luận phức tạpo3, claude-opus-4-5, deepseek-r1Logic và lập kế hoạch tốt hơn
Lập trìnhclaude-sonnet-4-5, gpt-4o, deepseek-v3.2Được tối ưu hóa cho mã nguồn
Viết lách sáng tạoclaude-sonnet-4-5, gpt-4oChất lượng văn phong tốt hơn
Thị giác/Hình ảnhgpt-4o, claude-sonnet-4-5, gemini-2.5-flashHỗ trợ thị giác gốc
Ngữ cảnh dàigemini-2.5-pro, claude-sonnet-4-5Cửa sổ ngữ cảnh trên 1M token
Nhạy cảm về chi phígpt-4o-mini, gemini-2.5-flash, deepseek-v3.2Giá trị tốt nhất

Các mức Chi phí

$$$$ 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

Tối ưu hóa Chi phí

1. Sử dụng các mô hình nhỏ hơn trước

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. Thiết lập max_tokens

Luôn thiết lập một giới hạn max_tokens hợp lý:
# ❌ 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. Tối ưu hóa Prompt

# ❌ 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. Bật Caching

Tận dụng semantic caching:
# 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. Gộp các yêu cầu tương tự (Batching)

# ❌ 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}"}]
)

Tối ưu hóa Hiệu suất

1. Sử dụng Streaming cho UX

Streaming cải thiện hiệu suất cảm nhận:
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. Chọn các mô hình nhanh cho mục đích tương tác

Trường hợp sử dụngKhuyến nghịĐộ trễ
Giao diện Chatgpt-4o-mini, gemini-2.5-flash~200ms cho token đầu tiên
Tự động hoàn thành (Tab completion)claude-haiku-4-5~150ms cho token đầu tiên
Xử lý nềngpt-4o, claude-sonnet-4-5~500ms cho token đầu tiên

3. Thiết lập Timeouts

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

Độ tin cậy

1. Triển khai cơ chế thử lại (Retries)

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. Xử lý lỗi một cách khéo léo

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. Sử dụng các mô hình dự phòng (Fallback)

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")

Bảo mật

1. Bảo vệ API Key

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

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

2. Xác thực đầu vào của người dùng

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. Thiết lập giới hạn cho API Key

Tạo các API key riêng biệt với giới hạn chi tiêu cho:
  • Phát triển/thử nghiệm
  • Sản xuất (Production)
  • Các ứng dụng khác nhau

Giám sát

1. Theo dõi mức độ sử dụng

Kiểm tra dashboard của bạn thường xuyên để biết:
  • Mức sử dụng token theo mô hình
  • Phân bổ chi phí
  • Tỷ lệ khớp cache
  • Tỷ lệ lỗi

2. Ghi nhật ký (Log) các chỉ số quan trọng

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. Thiết lập cảnh báo

Cấu hình cảnh báo số dư thấp trong dashboard của bạn để tránh gián đoạn dịch vụ.

Danh sách kiểm tra

  • Sử dụng mô hình phù hợp cho từng nhiệm vụ
  • Thiết lập giới hạn max_tokens
  • Prompt ngắn gọn
  • Bật caching ở những nơi phù hợp
  • Gộp các yêu cầu tương tự
  • Streaming cho UX tương tác
  • Các mô hình nhanh cho việc sử dụng thời gian thực
  • Đã cấu hình timeouts
  • Đã triển khai logic thử lại
  • Đã thiết lập xử lý lỗi
  • Đã cấu hình các mô hình dự phòng
  • API key nằm trong biến môi trường
  • Xác thực đầu vào
  • Các key riêng biệt cho dev/prod
  • Đã thiết lập giới hạn chi tiêu