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

Tổng quan

Agent-First API của LemonData làm phong phú các phản hồi lỗi bằng các gợi ý có cấu trúc mà AI agent có thể phân tích và xử lý ngay lập tức — không cần tìm kiếm web, không cần tra cứu tài liệu, không cần phỏng đoán. Mỗi phản hồi lỗi bao gồm các trường tùy chọn như did_you_mean, suggestions, hint, retryable, và retry_after bên trong đối tượng error tiêu chuẩn. Các trường này tương thích ngược — các client không sử dụng chúng sẽ không thấy sự khác biệt.

Các trường gợi ý lỗi

Tất cả các trường gợi ý là các phần mở rộng tùy chọn bên trong đối tượng error:
TrườngKiểuMô tả
did_you_meanstringTên model khớp nhất
suggestionsarrayCác model được đề xuất kèm theo metadata
alternativesarrayCác model thay thế hiện có sẵn
hintstringHướng dẫn bước tiếp theo dễ đọc cho người/agent
retryablebooleanLiệu việc thử lại cùng một yêu cầu có thể thành công hay không
retry_afternumberSố giây cần chờ trước khi thử lại
balance_usdnumberSố dư tài khoản hiện tại tính bằng USD
estimated_cost_usdnumberChi phí ước tính của yêu cầu bị lỗi

Các ví dụ về mã lỗi

model_not_found (400)

Khi tên model không khớp với bất kỳ model nào đang hoạt động:
{
  "error": {
    "message": "Model 'gpt5' not found",
    "type": "invalid_request_error",
    "param": "model",
    "code": "model_not_found",
    "did_you_mean": "gpt-4o",
    "suggestions": [
      {"id": "gpt-4o"},
      {"id": "gpt-4o-mini"},
      {"id": "claude-sonnet-4-5"}
    ],
    "hint": "Did you mean 'gpt-4o'? Use GET /v1/models to list all available models."
  }
}
Việc giải quyết did_you_mean sử dụng:
  1. Ánh xạ alias tĩnh (từ dữ liệu lỗi thực tế)
  2. Khớp chuỗi chuẩn hóa (loại bỏ dấu gạch ngang, không phân biệt chữ hoa chữ thường)
  3. Khớp khoảng cách chỉnh sửa (ngưỡng ≤ 3)

insufficient_balance (402)

Khi số dư tài khoản quá thấp so với chi phí ước tính:
{
  "error": {
    "message": "Insufficient balance: need ~$0.3500 for claude-sonnet-4-5, but balance is $0.1200.",
    "type": "insufficient_balance",
    "code": "insufficient_balance",
    "balance_usd": 0.12,
    "estimated_cost_usd": 0.35,
    "suggestions": [
      {"id": "gpt-4o-mini"},
      {"id": "deepseek-chat"}
    ],
    "hint": "Insufficient balance: need ~$0.3500 for claude-sonnet-4-5, but balance is $0.1200. Try a cheaper model, or top up at https://lemondata.cc/dashboard/billing."
  }
}
suggestions chứa các model rẻ hơn chi phí ước tính mà agent có thể chuyển sang.

all_channels_failed (503)

Khi tất cả các kênh upstream cho một model không khả dụng:
{
  "error": {
    "message": "Model claude-opus-4-6 temporarily unavailable",
    "code": "all_channels_failed",
    "retryable": true,
    "retry_after": 30,
    "alternatives": [
      {"id": "claude-sonnet-4-5", "status": "available", "tags": []},
      {"id": "gpt-4o", "status": "available", "tags": []}
    ],
    "hint": "All channels for 'claude-opus-4-6' are temporarily unavailable. Retry in 30s or try an alternative model."
  }
}
retryablefalse khi lý do là no_channels (không có kênh nào được cấu hình cho model này). Nó chỉ là true đối với các lỗi tạm thời như ngắt mạch (circuit breaker trips) hoặc hết hạn mức (quota exhaustion).

rate_limit_exceeded (429)

{
  "error": {
    "message": "Rate limit: 60 rpm exceeded",
    "type": "rate_limit_error",
    "code": "rate_limit_exceeded",
    "retryable": true,
    "retry_after": 8,
    "hint": "Rate limited. Retry after 8s. Current limit: 60/min for user role."
  }
}
Giá trị retry_after được tính toán từ thời gian reset thực tế của cửa sổ rate limit.

context_length_exceeded (400)

Khi đầu vào vượt quá cửa sổ ngữ cảnh của model (lỗi upstream, được bổ sung các gợi ý):
{
  "error": {
    "message": "This model's maximum context length is 128000 tokens...",
    "type": "invalid_request_error",
    "code": "context_length_exceeded",
    "retryable": false,
    "suggestions": [
      {"id": "gemini-2.5-pro"},
      {"id": "claude-sonnet-4-5"}
    ],
    "hint": "Reduce your input or switch to a model with a larger context window."
  }
}

Các Header Native Endpoint

Khi bạn gọi /v1/chat/completions với một model có native endpoint (Anthropic hoặc Gemini), phản hồi thành công sẽ bao gồm các header tối ưu hóa:
X-LemonData-Hint: This model supports native Anthropic format. Use POST /v1/messages for better performance (no format conversion).
X-LemonData-Native-Endpoint: /v1/messages
Nhà cung cấp ModelEndpoint được đề xuấtLợi ích
Anthropic (Claude)/v1/messagesKhông chuyển đổi định dạng, tư duy mở rộng (extended thinking), prompt caching
Google (Gemini)/v1beta/geminiKhông chuyển đổi định dạng, grounding, các thiết lập an toàn
OpenAIChat completions đã là định dạng native
Các header này xuất hiện trên cả phản hồi streaming và non-streaming.

Các cải tiến cho /v1/models

Ba trường mới trong phần mở rộng lemondata của mỗi đối tượng model:
{
  "id": "gpt-4o",
  "lemondata": {
    "category": "chat",
    "pricing_unit": "per_token",
    "cache_pricing": {
      "cache_read_per_1m": "1.25",
      "cache_write_per_1m": "2.50",
      "platform_cache_discount": 0.9
    }
  }
}
TrườngGiá trịMô tả
categorychat, image, video, audio, tts, stt, 3d, embedding, rerankLoại model
pricing_unitper_token, per_image, per_second, per_requestCách tính phí model
cache_pricingđối tượng hoặc nullGiá prompt cache upstream + chiết khấu semantic cache của nền tảng

Lọc theo Category

GET /v1/models?category=chat          # Chỉ các model Chat
GET /v1/models?category=image         # Các model tạo hình ảnh
GET /v1/models?tag=coding&category=chat  # Các model chat tối ưu cho coding

llms.txt

Bản tóm tắt API có thể đọc được bằng máy có sẵn tại:
GET https://api.lemondata.cc/llms.txt
Nó bao gồm:
  • Template cho lần gọi đầu tiên với ví dụ thực tế
  • Các tên model phổ biến (được tạo động từ dữ liệu sử dụng)
  • Tất cả 12 API endpoint
  • Các tham số lọc để khám phá model
  • Hướng dẫn xử lý lỗi
Các AI agent đọc llms.txt trước khi thực hiện cuộc gọi API đầu tiên thường có thể thành công ngay trong lần thử đầu tiên.

Sử dụng trong mã nguồn Agent

Python (OpenAI SDK)

from openai import OpenAI, BadRequestError

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

def smart_chat(messages, model="gpt-4o"):
    try:
        return client.chat.completions.create(
            model=model, messages=messages
        )
    except BadRequestError as e:
        error = e.body.get("error", {}) if isinstance(e.body, dict) else {}
        # Sử dụng did_you_mean để tự động sửa lỗi
        if error.get("code") == "model_not_found" and error.get("did_you_mean"):
            return client.chat.completions.create(
                model=error["did_you_mean"], messages=messages
            )
        raise

JavaScript (OpenAI SDK)

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'sk-your-key',
  baseURL: 'https://api.lemondata.cc/v1'
});

async function smartChat(messages, model = 'gpt-4o') {
  try {
    return await client.chat.completions.create({ model, messages });
  } catch (error) {
    const err = error?.error;
    if (err?.code === 'model_not_found' && err?.did_you_mean) {
      return client.chat.completions.create({
        model: err.did_you_mean, messages
      });
    }
    throw error;
  }
}

Nguyên tắc thiết kế

Thất bại sớm, thông báo chi tiết

Lỗi trả về ngay lập tức với tất cả dữ liệu mà agent cần để tự sửa lỗi.

Không tự động điều hướng

API không bao giờ âm thầm thay thế bằng một model khác. Agent sẽ quyết định.

Đề xuất dựa trên dữ liệu

Tất cả các đề xuất đều đến từ dữ liệu thực tế, không phải danh sách được mã hóa cứng.

Tương thích ngược

Tất cả các trường gợi ý đều là tùy chọn. Các client hiện tại sẽ không thấy sự khác biệt.