BazaarLinkBazaarLink
Đăng nhập
Tài liệuTham chiếu APITham chiếu SDKSử dụng AgentKỹ năng AI

Tham chiếu API

Tổng quan về API BazaarLink

BazaarLink cung cấp định dạng yêu cầu và phản hồi thống nhất, tương thích OpenAI trên nhiều mô hình và nhà cung cấp. Bạn chỉ cần tích hợp một lần rồi chuyển đổi mô hình mà không phải viết lại ứng dụng.

Đặc tả OpenAPI

Toàn bộ API BazaarLink được mô tả bằng đặc tả OpenAPI và có sẵn ở định dạng YAML và JSON:

Sử dụng các đặc tả này với Swagger UI, Postman hoặc trình tạo mã tương thích OpenAPI để khám phá API hay tạo thư viện máy khách.

Yêu cầu

Định dạng yêu cầu Chat Completions

Nội dung yêu cầu Chat Completions được gửi đến endpoint sau:

POST/api/v1/chat/completions

Để xem danh sách đầy đủ các trường được hỗ trợ, hãy xem Tham số

Schema yêu cầu
// Definitions of subtypes are below
type Request = {
  // Required by BazaarLink Chat Completions
  model: string;                    // Use a provider-qualified catalog ID
  messages: Message[];             // Must contain at least one message

  // Generation
  stream?: boolean;
  temperature?: number;            // Range: [0, 2]
  max_tokens?: number;             // Positive integer
  max_completion_tokens?: number;  // Alias mapped to max_tokens upstream
  n?: number;
  seed?: number;
  stop?: string | string[];

  // Sampling
  top_p?: number;
  top_k?: number;
  frequency_penalty?: number;      // Range: [-2, 2]
  presence_penalty?: number;       // Range: [-2, 2]
  repetition_penalty?: number;     // Range: (0, 2]
  min_p?: number;                  // Range: [0, 1]
  top_a?: number;                  // Range: [0, 1]

  // Token probabilities
  logit_bias?: Record<number, number>;
  logprobs?: boolean;
  top_logprobs?: number;

  // Stable end-user identifier for abuse prevention
  user?: string;

  // Tool calling
  tools?: Tool[];
  tool_choice?: ToolChoice;
  parallel_tool_calls?: boolean;

  // Structured output
  response_format?: ResponseFormat;
  structured_outputs?: boolean;

  // Plugin configuration — forwarded to upstreams that support plugins.
  plugins?: Plugin[];

  // Multimodal and image-generation options
  modalities?: Array<"text" | "image">;
  image_config?: Record<string, unknown>;
  input_audio?: InputAudio;

  // Provider-specific reasoning controls
  reasoning_effort?: "low" | "medium" | "high";
  reasoning?: ReasoningConfig;
  thinking?: ThinkingConfig;
  enable_thinking?: boolean;

  // BazaarLink message transforms and fallback routing
  transforms?: Array<"middle-out">;
  models?: string[];             // Fallback list — this drives waterfall routing, not route
  route?: "fallback";            // Passthrough only; forwarded as-is, no local effect
  provider?: ProviderPreferences;
};

// Message types
type Message =
  | SystemMessage
  | UserMessage
  | AssistantMessage
  | ToolMessage;

type SystemMessage = {
  role: "system";
  content: string | ContentPart[];
  name?: string;
};

type UserMessage = {
  role: "user";
  content: string | ContentPart[];
  name?: string;
};

type AssistantMessage = {
  role: "assistant";
  content?: string | ContentPart[] | null;
  name?: string;
  tool_calls?: ToolCall[];
};

type ToolMessage = {
  role: "tool";
  content: string;
  tool_call_id: string;
  name?: string;
};

// Multimodal content parts
type ContentPart =
  | TextContentPart
  | ImageContentPart
  | FileContentPart
  | AudioContentPart
  | VideoContentPart;

type TextContentPart = {
  type: "text";
  text: string;
};

type ImageContentPart = {
  type: "image_url";
  image_url: {
    url: string;                    // Remote URL or base64 data URI
    detail?: string;
  };
};

type FileContentPart = {
  type: "file";
  file: {
    filename?: string;
    file_data: string;              // Base64 data URI
  };
};

type AudioContentPart = {
  type: "input_audio";
  input_audio: InputAudio;
};

type InputAudio = {
  data: string;                     // Raw base64 without a data URI prefix
  format: string;                   // For example "wav" or "mp3"
};

type VideoContentPart = {
  type: "video_url";
  video_url: {
    url: string;                    // Remote URL or base64 data URI
  };
};

// Tool calling subtypes
type FunctionDescription = {
  name: string;
  description?: string;
  parameters: object;               // JSON Schema object
};

type Tool = {
  type: "function";
  function: FunctionDescription;
};

type ToolChoice =
  | "none"
  | "auto"
  | "required"
  | {
      type: "function";
      function: {
        name: string;
      };
    };

type ToolCall = {
  id: string;
  type: "function";
  function: {
    name: string;
    arguments: string;
  };
};

// Structured output
type ResponseFormat =
  | {
      type: "json_object";
    }
  | {
      type: "json_schema";
      json_schema: {
        name: string;
        strict?: boolean;
        schema: object;
      };
    };

// Upstream plugin configuration
type Plugin = {
  id: string;
  enabled?: boolean;
  [key: string]: unknown;
};

// Reasoning controls vary by model family
type ReasoningConfig = {
  effort?: "low" | "medium" | "high";
  max_tokens?: number;
  exclude?: boolean;
};

type ThinkingConfig = {
  type?: "enabled" | "disabled";
  budget_tokens?: number;
};

// Provider routing preferences
type ProviderPreferences = {
  order?: string[];
  only?: string[];
  ignore?: string[];
  allow_fallbacks?: boolean;
  sort?:
    | "price"
    | "latency"
    | "throughput"
    | {
        by: string;
        partition?: string;
      };
  require_parameters?: boolean;
  data_collection?: "allow" | "deny";
  quantizations?: string[];
  max_price?: Record<string, number>;
};

Đầu ra có cấu trúc

Buộc mô hình trả về JSON hợp lệ khớp với schema. Điều này thiết yếu để xây dựng ứng dụng đáng tin cậy phân tích đầu ra mô hình theo chương trình.

  • json_objectchế độ JSON cơ bản; mô hình trả về JSON hợp lệ.
  • json_schemachế độ schema nghiêm ngặt; đầu ra phải khớp với JSON Schema được cung cấp.

Plugin

BazaarLink chuyển tiếp mảng plugins đến tuyến upstream đã chọn. Khả năng hỗ trợ phụ thuộc vào mô hình và nhà cung cấp; biến thể mô hình :online cũng bật plugin web.

JSON
{
  "model": "openai/gpt-4.1",
  "messages": [
    { "role": "user", "content": "What happened today?" }
  ],
  "plugins": [
    { "id": "web" }
  ]
}

Header tùy chọn

Xác định ứng dụng trong header yêu cầu.

TypeScript
await fetch("https://bazaarlink.ai/api/v1/chat/completions", {
  method: "POST",
  headers: {
    "Authorization": "Bearer <BAZAARLINK_API_KEY>",
    "Content-Type": "application/json",
    "HTTP-Referer": "https://your-app.example",
    "X-Title": "Your App"
  },
  body: JSON.stringify({
    model: "openai/gpt-4.1",
    messages: [{ role: "user", content: "Hello!" }]
  })
});

AHỗ trợ điền trước

Thêm một tin nhắn assistant chưa hoàn chỉnh làm mục cuối để yêu cầu tiếp tục trên các tuyến mô hình tương thích.

Cách hoạt động
BazaarLink giữ nguyên và chuyển tiếp tin nhắn assistant cuối cùng. Hành vi tiếp tục do mô hình và nhà cung cấp upstream được chọn triển khai, vì vậy không được bảo đảm trên mọi tuyến.
TypeScript
const response = await client.chat.completions.create({
  model: "anthropic/claude-sonnet-4.6",
  messages: [
    { role: "user", content: "What is the meaning of life?" },
    // Intentional partial response; compatible routes continue from here.
    { role: "assistant", content: "My best answer is" }
  ]
});

Phản hồi

BazaarLink chuẩn hóa phản hồi completion từ nhiều mô hình và nhà cung cấp thành một định dạng tương thích OpenAI thống nhất.

Định dạng phản hồi Completion

choices luôn là một mảng. Phản hồi streaming dùng delta, phản hồi không streaming dùng message; thông tin sử dụng và chi phí được trả về khi có.

Schema phản hồi
type Response = {
  id: string;
  object: "chat.completion" | "chat.completion.chunk";
  created: number;
  model: string;
  choices: Array<NonStreamingChoice | StreamingChoice>;
  usage?: {
    prompt_tokens: number;
    completion_tokens: number;
    total_tokens: number;
    cost?: number;
    prompt_tokens_details?: {
      cached_tokens: number;
      cache_write_tokens?: number;
      audio_tokens?: number;
    };
    completion_tokens_details?: {
      reasoning_tokens?: number;
      image_tokens?: number;
    };
  };
};

type NonStreamingChoice = {
  index: number;
  finish_reason: string | null;
  native_finish_reason: string | null;
  message: {
    role: "assistant";
    content: string | null;
    tool_calls?: ToolCall[];
  };
};

type StreamingChoice = {
  index: number;
  finish_reason: string | null;
  native_finish_reason: string | null;
  delta: {
    role?: string;
    content?: string | null;
    tool_calls?: ToolCall[];
  };
};

Lý do kết thúc

finish_reason dùng các giá trị chuẩn hóa như stop, length, tool_calls, content_filter và error; native_finish_reason giữ nguyên giá trị gốc của nhà cung cấp.

JSON
{
  "finish_reason": "stop",
  "native_finish_reason": "stop"
}

Truy vấn chi phí và thống kê

Truy xuất số liệu thống kê chi tiết cho một lần hoàn thành theo ID thế hệ (từ id phản hồi chat/completions hoặc tiêu đề x-bz-gen-id phát trực tuyến).

TypeScript
const generation = await fetch(
  "https://bazaarlink.ai/api/v1/generation?id=<GENERATION_ID>",
  {
    headers: {
      Authorization: "Bearer <BAZAARLINK_API_KEY>"
    }
  }
).then((response) => response.json());

Chat Completions

Endpoint chính. Tương thích với API Chat Completions của OpenAI.

POST/api/v1/chat/completions

Nội dung yêu cầu

modelbắt buộc
string
ID mô hình, ví dụ "openai/gpt-4o" hoặc "anthropic/claude-3.5-sonnet"
messagesbắt buộc
Message[]
Mảng đối tượng tin nhắn với role và content
stream
boolean
Nếu true, trả về luồng Server-Sent Events. Mặc định: false
temperature
number
Nhiệt độ lấy mẫu 0–2. Cao hơn = ngẫu nhiên hơn. Mặc định: 1
max_tokens
integer
Số token tối đa để tạo
max_completion_tokens
integer
Bí danh cho max_tokens (tương thích OpenAI o-series). Cả hai đều được chấp nhận
top_p
number
Xác suất lấy mẫu nucleus. Mặc định: 1
top_k
integer
Giới hạn lựa chọn token cho top-K. 0 = tắt (xem xét tất cả). Mặc định: 0
frequency_penalty
number
Phạt token lặp lại. Phạm vi: [-2, 2]. Mặc định: 0
presence_penalty
number
Phạt token dựa trên sự hiện diện. Phạm vi: [-2, 2]. Mặc định: 0
repetition_penalty
number
Giảm lặp lại token từ đầu vào. Phạm vi: (0, 2]. Mặc định: 1
min_p
number
Xác suất tối thiểu tương đối với token hàng đầu. Phạm vi: [0, 1]. Mặc định: 0
top_a
number
Top-P động dựa trên token có xác suất cao nhất. Phạm vi: [0, 1]. Mặc định: 0
seed
integer
Seed số nguyên cho lấy mẫu xác định. Không đảm bảo cho tất cả mô hình
n
integer
Số lượng hoàn thành để tạo. Mặc định: 1
user
string
Định danh người dùng cuối cho giám sát và phát hiện lạm dụng. Không ảnh hưởng thanh toán. Chỉ áp dụng cho mô hình họ OpenAI — xem ghi chú bên dưới.
stop
string | string[]
Chuỗi dừng — tạo văn bản dừng khi gặp
logit_bias
object
Ánh xạ ID token đến giá trị thiên lệch [-100, 100] được thêm trước lấy mẫu. Chỉ áp dụng cho mô hình họ OpenAI — xem ghi chú bên dưới.
logprobs
boolean
Trả về log xác suất của mỗi token đầu ra. Chỉ áp dụng cho mô hình họ OpenAI — xem ghi chú bên dưới.
top_logprobs
integer
Số token có khả năng nhất trả về cho mỗi vị trí (cần logprobs: true). Phạm vi: 0–20. Chỉ áp dụng cho mô hình họ OpenAI — xem ghi chú bên dưới.
tools
Tool[]
Danh sách công cụ (hàm) mô hình có thể gọi
tool_choice
string | object
Điều khiển sử dụng công cụ: "auto", "none", hoặc công cụ cụ thể
parallel_tool_calls
boolean
Bật gọi hàm song song khi cung cấp công cụ. Mặc định: true. Chỉ áp dụng cho mô hình họ OpenAI — xem ghi chú bên dưới.
response_format
object
Buộc đầu ra JSON có cấu trúc. Xem phần Đầu ra có cấu trúc
structured_outputs
boolean
Yêu cầu đầu ra tuân thủ nghiêm ngặt JSON schema trên các nhà cung cấp hỗ trợ. Chuyển tiếp nguyên trạng
reasoning
object
Cấu hình reasoning/thinking riêng của nhà cung cấp. Chuyển tiếp nguyên trạng
reasoning_effort
string
Mức độ reasoning kiểu OpenAI dòng o: "low", "medium", hoặc "high". Chuyển tiếp nguyên trạng
transforms
string[]
Chuyển đổi tin nhắn để áp dụng, ví dụ ["middle-out"]. Bỏ qua để tự động áp dụng trên mô hình ≤8k context
models
string[]
Danh sách mô hình dự phòng — BazaarLink thử từng cái theo thứ tự nếu chính thất bại
route
string
Trường tương thích định tuyến nâng cao — hầu hết người dùng không cần. Dùng "models" cho fallback.
provider
object
Tùy chọn định tuyến nâng cao — hầu hết người dùng không cần.
user, logprobs, top_logprobs, logit_bias, và parallel_tool_calls chỉ đến được các mô hình họ OpenAI
Năm tham số này bị loại khỏi yêu cầu upstream bất cứ khi nào mô hình được xác định không phải của chính OpenAI — gửi chúng đến anthropic/claude-*, google/gemini-*, hoặc bất kỳ đích không phải OpenAI nào khác sẽ trả về 200 với tham số bị âm thầm bỏ qua, không phải lỗi. Nếu bạn đặt một trong các tham số này mà không thấy hiệu lực, hãy kiểm tra xem mô hình đích có phải của OpenAI hay không.

Schema yêu cầu (TypeScript)

// Definitions of subtypes are below
type Request = {
  // Required by BazaarLink Chat Completions
  model: string;                    // Use a provider-qualified catalog ID
  messages: Message[];             // Must contain at least one message

  // Generation
  stream?: boolean;
  temperature?: number;            // Range: [0, 2]
  max_tokens?: number;             // Positive integer
  max_completion_tokens?: number;  // Alias mapped to max_tokens upstream
  n?: number;
  seed?: number;
  stop?: string | string[];

  // Sampling
  top_p?: number;
  top_k?: number;
  frequency_penalty?: number;      // Range: [-2, 2]
  presence_penalty?: number;       // Range: [-2, 2]
  repetition_penalty?: number;     // Range: (0, 2]
  min_p?: number;                  // Range: [0, 1]
  top_a?: number;                  // Range: [0, 1]

  // Token probabilities
  logit_bias?: Record<number, number>;
  logprobs?: boolean;
  top_logprobs?: number;

  // Stable end-user identifier for abuse prevention
  user?: string;

  // Tool calling
  tools?: Tool[];
  tool_choice?: ToolChoice;
  parallel_tool_calls?: boolean;

  // Structured output
  response_format?: ResponseFormat;
  structured_outputs?: boolean;

  // Plugin configuration — forwarded to upstreams that support plugins.
  plugins?: Plugin[];

  // Multimodal and image-generation options
  modalities?: Array<"text" | "image">;
  image_config?: Record<string, unknown>;
  input_audio?: InputAudio;

  // Provider-specific reasoning controls
  reasoning_effort?: "low" | "medium" | "high";
  reasoning?: ReasoningConfig;
  thinking?: ThinkingConfig;
  enable_thinking?: boolean;

  // BazaarLink message transforms and fallback routing
  transforms?: Array<"middle-out">;
  models?: string[];             // Fallback list — this drives waterfall routing, not route
  route?: "fallback";            // Passthrough only; forwarded as-is, no local effect
  provider?: ProviderPreferences;
};

// Message types
type Message =
  | SystemMessage
  | UserMessage
  | AssistantMessage
  | ToolMessage;

type SystemMessage = {
  role: "system";
  content: string | ContentPart[];
  name?: string;
};

type UserMessage = {
  role: "user";
  content: string | ContentPart[];
  name?: string;
};

type AssistantMessage = {
  role: "assistant";
  content?: string | ContentPart[] | null;
  name?: string;
  tool_calls?: ToolCall[];
};

type ToolMessage = {
  role: "tool";
  content: string;
  tool_call_id: string;
  name?: string;
};

// Multimodal content parts
type ContentPart =
  | TextContentPart
  | ImageContentPart
  | FileContentPart
  | AudioContentPart
  | VideoContentPart;

type TextContentPart = {
  type: "text";
  text: string;
};

type ImageContentPart = {
  type: "image_url";
  image_url: {
    url: string;                    // Remote URL or base64 data URI
    detail?: string;
  };
};

type FileContentPart = {
  type: "file";
  file: {
    filename?: string;
    file_data: string;              // Base64 data URI
  };
};

type AudioContentPart = {
  type: "input_audio";
  input_audio: InputAudio;
};

type InputAudio = {
  data: string;                     // Raw base64 without a data URI prefix
  format: string;                   // For example "wav" or "mp3"
};

type VideoContentPart = {
  type: "video_url";
  video_url: {
    url: string;                    // Remote URL or base64 data URI
  };
};

// Tool calling subtypes
type FunctionDescription = {
  name: string;
  description?: string;
  parameters: object;               // JSON Schema object
};

type Tool = {
  type: "function";
  function: FunctionDescription;
};

type ToolChoice =
  | "none"
  | "auto"
  | "required"
  | {
      type: "function";
      function: {
        name: string;
      };
    };

type ToolCall = {
  id: string;
  type: "function";
  function: {
    name: string;
    arguments: string;
  };
};

// Structured output
type ResponseFormat =
  | {
      type: "json_object";
    }
  | {
      type: "json_schema";
      json_schema: {
        name: string;
        strict?: boolean;
        schema: object;
      };
    };

// Upstream plugin configuration
type Plugin = {
  id: string;
  enabled?: boolean;
  [key: string]: unknown;
};

// Reasoning controls vary by model family
type ReasoningConfig = {
  effort?: "low" | "medium" | "high";
  max_tokens?: number;
  exclude?: boolean;
};

type ThinkingConfig = {
  type?: "enabled" | "disabled";
  budget_tokens?: number;
};

// Provider routing preferences
type ProviderPreferences = {
  order?: string[];
  only?: string[];
  ignore?: string[];
  allow_fallbacks?: boolean;
  sort?:
    | "price"
    | "latency"
    | "throughput"
    | {
        by: string;
        partition?: string;
      };
  require_parameters?: boolean;
  data_collection?: "allow" | "deny";
  quantizations?: string[];
  max_price?: Record<string, number>;
};

Yêu cầu mẫu

curl https://bazaarlink.ai/api/v1/chat/completions \
  -H "Authorization: Bearer $BAZAARLINK_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-4.1",
    "messages": [
      {"role": "system", "content": "You are a helpful assistant."},
      {"role": "user", "content": "Explain quantum computing in one paragraph."}
    ],
    "temperature": 0.7,
    "max_tokens": 512
  }'

Phản hồi

{
  "id": "chatcmpl-abc123",
  "object": "chat.completion",
  "created": 1740000000,
  "model": "openai/gpt-4.1",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Quantum computing leverages quantum mechanics..."
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 28,
    "completion_tokens": 74,
    "total_tokens": 102,
    "cost": 0.0006480,
    "prompt_tokens_details": {
      "cached_tokens": 0
    },
    "completion_tokens_details": {
      "reasoning_tokens": 0
    }
  }
}

Schema phản hồi (TypeScript)

BazaarLink chỉ chuẩn hóa đúng hai trường — model và việc loại bỏ trường provider — rồi chuyển tiếp phần còn lại của phản hồi upstream nguyên trạng. Các trường như native_finish_reason, system_fingerprint, và reasoning chỉ tồn tại khi nhà cung cấp upstream cụ thể điền vào — đừng cho rằng chúng luôn xuất hiện ở mọi mô hình. usage.cost là ngoại lệ — luôn là số tiền BazaarLink tự quyết toán/tính phí, không phải giá trị chuyển tiếp từ upstream.

type Response = {
  id: string;
  object: "chat.completion" | "chat.completion.chunk";
  created: number;                 // Unix timestamp
  model: string;
  choices: (NonStreamingChoice | StreamingChoice)[];
  usage?: ResponseUsage;
  cost?: number;                   // Total cost in USD
};

type NonStreamingChoice = {
  index: number;
  finish_reason: "stop" | "length" | "tool_calls" | "content_filter" | null;
  native_finish_reason: string | null;  // Provider's original finish reason
  message: {
    role: "assistant";
    content: string | null;
    tool_calls?: ToolCall[];
  };
};

type StreamingChoice = {
  index: number;
  finish_reason: string | null;
  native_finish_reason: string | null;  // Provider's original finish reason
  delta: {
    role?: string;
    content?: string | null;
    tool_calls?: ToolCall[];
  };
};

type ResponseUsage = {
  prompt_tokens: number;
  completion_tokens: number;
  total_tokens: number;
  cost: number;                      // Total cost for this request in USD
  prompt_tokens_details?: {
    cached_tokens: number;           // Tokens served from prompt cache (reduced cost)
    cache_write_tokens?: number;     // Tokens written to cache in this request
    audio_tokens?: number;
  };
  completion_tokens_details?: {
    reasoning_tokens?: number;       // Thinking/reasoning tokens (e.g. o3, Qwen3, DeepSeek R1)
    image_tokens?: number;
  };
};

type ToolCall = {
  id: string;
  type: "function";
  function: { name: string; arguments: string };
};

Tạo hình ảnh

Tạo hình ảnh từ prompt văn bản sử dụng các mô hình như DALL·E và GPT-4o. Chỉnh sửa hình ảnh (sửa đổi một hình ảnh có sẵn) dùng POST /v1/images/edits —— tương thích OpenAI images.edit, multipart/form-data với (các) hình ảnh nguồn của bạn. Các model hỗ trợ chỉnh sửa có modality là text+image->image (ví dụ qwen/qwen-image-edit); model chỉ tạo mới là text->image —— kiểm tra modality của từng model trong GET /v1/models.

Response format

/api/v1/images/generations mặc định trả về JSON đồng bộ tương thích OpenAI (từ 2026-07-25) — client.images.generate() hoạt động không cần wrapper. Truyền stream: true để chuyển sang luồng sự kiện SSE, cung cấp tiến độ cho các model có thời gian tạo dài.

A. /v1/chat/completions (native, khuyến nghị)

POST/api/v1/chat/completions

The canonical streaming path. Recommended for any new integration.

curl -N https://bazaarlink.ai/api/v1/chat/completions \
  -H "Authorization: Bearer $BL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-5.4-image-2",
    "messages": [{"role":"user","content":"a red cat on a sofa"}],
    "modalities": ["image","text"],
    "stream": true
  }'

Image-to-image: thêm phần image_url vào mảng content. Hỗ trợ data URI hoặc URL hình ảnh https (http:// bị từ chối), tối đa 8 hình, mỗi data URI khoảng 10MB. Tin nhắn mang hình ảnh cũng phải chứa phần text (chỉ dẫn chỉnh sửa). Một số mô hình còn hỗ trợ image_config (ví dụ {"strength": 0.7}, 0–1 — giá trị thấp hơn giữ gần với hình gốc hơn), được truyền nguyên vẹn lên upstream.

curl -N https://bazaarlink.ai/api/v1/chat/completions \
  -H "Authorization: Bearer $BL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-5.4-image-2",
    "messages": [{"role":"user","content":[
      {"type":"image_url","image_url":{"url":"data:image/png;base64,..."}},
      {"type":"text","text":"change the background to a night city"}
    ]}],
    "modalities": ["image"],
    "stream": true
  }'

Chỉnh sửa hình ảnh (tương thích OpenAI)

POST/api/v1/images/edits

client.images.edit() của OpenAI SDK hoạt động trực tiếp (upload multipart, phản hồi JSON đồng bộ trả về data: [{ url }]). Giới hạn giống image-to-image: tối đa 8 hình, mỗi hình 10MB; mask và response_format=b64_json chưa được hỗ trợ.

curl https://bazaarlink.ai/api/v1/images/edits \
  -H "Authorization: Bearer $BL_API_KEY" \
  -F model="openai/gpt-5.4-image-2" \
  -F image=@cat.png \
  -F prompt="change the background to a night city"

B. /v1/images/generations (tương thích DALL·E)

POST/api/v1/images/generations

OpenAI DALL-E request shape. Sync JSON ({ created, data: [{ url }] }) is the default and works with client.images.generate() out of the box; pass stream: true to get the SSE event stream documented below instead.

curl https://bazaarlink.ai/api/v1/images/generations \
  -H "Authorization: Bearer $BL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-image-2",
    "prompt": "a red cat on a sofa",
    "size": "1024x1024"
  }'
modelbắt buộc
string
ID mô hình, ví dụ google/gemini-2.5-flash-image
promptbắt buộc
string
Prompt văn bản
size
string
Kích thước đầu ra (tự động ánh xạ)
n
integer
Số lượng hình (mặc định 1)
# Streaming variant — progressive delivery for long generations
curl -N https://bazaarlink.ai/api/v1/images/generations \
  -H "Authorization: Bearer $BL_API_KEY" \
  -H "Accept: text/event-stream" \
  -H "Content-Type: application/json" \
  -d '{"model":"openai/gpt-5.4-image-2","prompt":"a red cat on a sofa","stream":true}'

SSE event protocol

Both endpoints emit the same event types:

event: heartbeat        # every 60 s, keeps Cloudflare happy
data: {}

event: image            # upstream URL, fastest path
data: {"index": 0, "url": "https://upstream/a.png"}

event: image-cached     # bazaarlink Redis-backed proxy URL (1 hr TTL)
data: {"index": 0, "url": "https://bazaarlink.ai/api/v1/images/proxy/<token>"}

event: usage            # final cost / token count
data: {"promptTokens": 12, "completionTokens": 7080, "cost": 0.226, "durationMs": 163400, "imageCount": 1}

event: done
data: {}

Mô hình hình ảnh được hỗ trợ

Model IDModalityi2i (edits)

Tạo video

Quy trình bất đồng bộ ba bước (submit → poll → content). Tạo video mất 30 giây–5 phút nên không phù hợp với ngữ nghĩa yêu cầu/phản hồi đồng bộ của chat-completions — vì vậy BazaarLink tách video sang endpoint riêng /api/v1/videos theo mẫu job-id: submit trả về ID vjob_* → poll trạng thái → hoàn tất thì fetch bytes. Gọi mô hình video qua /chat/completions hoặc /images/generations sẽ trả về 400 (code: wrong_endpoint_for_video). Chi phí được quyết toán theo usage.cost thực tế khi completed.

Các loại tác vụ video

Một endpoint bao gồm nhiều tác vụ. Tác vụ nào chạy phụ thuộc vào các trường bạn gửi —— một model duy nhất có thể làm image-to-video, keyframe và nối tiếp. Không phải model nào cũng hỗ trợ mọi tác vụ; yêu cầu không được hỗ trợ trả về 400.

Văn bản thành video
prompt
Tạo chỉ từ một prompt văn bản — không cần phương tiện đầu vào.
Ảnh thành video
frame_images: [ first frame ]
Ảnh của bạn CHÍNH LÀ hình ảnh: nó trở thành khung đầu tiên và được làm động, giữ trung thực với bản gốc. Ví dụ: ảnh một con mèo → chính con mèo đó quay đầu trong cùng bối cảnh.
Keyframe (đầu + cuối)
frame_images: [ first, last ]
Cung cấp một ảnh đầu và một ảnh cuối; mô hình nội suy chuyển động ở giữa.
Nối tiếp
input_video
Kéo dài một clip có sẵn. Thời lượng yêu cầu phải lớn hơn độ dài của video nguồn.
Tham chiếu thành video
input_references: [ images ]
Ảnh của bạn là THAM CHIẾU, không phải khung hình: mô hình giữ chủ thể/phong cách và tạo ra một bối cảnh hoàn toàn mới. Ví dụ: ảnh con mèo + "nhảy múa trong rừng" → một video mới trong đó diện mạo con mèo được giữ nguyên nhưng bối cảnh và chuyển động là mới (1–9 ảnh tham chiếu). Khác với ảnh thành video: i2v trung thực với đúng bức ảnh; r2v đưa chủ thể vào cảnh quay mới.
Chỉnh sửa video
input_video + prompt
Chỉnh sửa một video có sẵn — thay đổi bối cảnh, phong cách hoặc chuyển động. Tính phí theo giây video đầu vào + giây đầu ra.

1. Gửi tác vụ (trả về vjob_xxx ngay lập tức)

POST/api/v1/videos
modelbắt buộc
string
ID mô hình, ví dụ alibaba/wan2.7-t2v
promptbắt buộc
string
Prompt văn bản
duration
integer
Thời lượng tính bằng giây (tùy mô hình)
resolution
string
Độ phân giải — 480p / 720p / 1080p v.v.
generate_audio
boolean
Tạo âm thanh (true/false)
frame_images
array
Ảnh khung đầu/cuối (image-to-video, keyframe). Đối tượng { type: "image_url", image_url: { url }, frame_type: "first_frame" | "last_frame" } hoặc chuỗi URL thuần.
input_references
array
Ảnh tham chiếu cho reference-to-video —— định hướng chủ thể/phong cách, không phải khung chính xác.
input_video
string|object
URL video nguồn cho nối tiếp và chỉnh sửa video. Phải truy cập công khai được từ upstream.
aspect_ratio
string
Tỉ lệ khung hình, ví dụ 16:9 hoặc 9:16. Bị bỏ qua khi ảnh đầu vào quyết định tỉ lệ.
watermark
boolean
Thêm watermark. Mặc định false.
callback_url
string
URL webhook được gọi khi job đạt trạng thái cuối — chỉ HTTPS, có kiểm tra SSRF. Không có chữ ký trong v1; coi là gợi ý và xác nhận qua GET /videos/{id}.
curl https://bazaarlink.ai/api/v1/videos \
  -H "Authorization: Bearer $BL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "alibaba/wan2.7-t2v",
    "prompt": "a bird flying over mountains",
    "duration": 3,
    "resolution": "720p",
    "generate_audio": false
  }'
# → 202 { "id": "vjob_xxx", "status": "pending" }
Note
Khi submit sẽ tạm giữ theo trường hợp xấu nhất × thời lượng × hệ số; khi completed, usage.cost thực tế từ upstream sẽ quyết toán phần chênh lệch.

2. Poll trạng thái

GET/api/v1/videos/{id}
curl -H "Authorization: Bearer $BL_API_KEY" \
  https://bazaarlink.ai/api/v1/videos/vjob_xxx
Note
Mỗi GET phải cách nhau ≥ 8 giây mới thực sự gọi lên upstream (tránh rate limit).
Note
Khi status=failed, toàn bộ số tiền tạm giữ được hoàn lại cho người dùng.

3. Lấy nội dung video (MP4)

GET/api/v1/videos/{id}/content
curl -H "Authorization: Bearer $BL_API_KEY" \
  -o output.mp4 \
  https://bazaarlink.ai/api/v1/videos/vjob_xxx/content

Cần biết

  • Độ phân giải cho phép khác nhau theo từng model —— giá trị không được hỗ trợ trả về 400 kèm danh sách được hỗ trợ.
  • Ảnh/video đầu vào phải truy cập được từ URL công khai. Các host chống hotlink (ví dụ một số wiki) sẽ thất bại.
  • Media đầu vào đi qua kiểm duyệt nội dung của upstream và đôi khi có thể bị từ chối.
  • Với nối tiếp, thời lượng yêu cầu phải vượt quá độ dài video nguồn.
  • Tỉ lệ khung hình đầu ra theo ảnh đầu vào —— ảnh vuông cho video vuông.
  • Chỉnh sửa video được tính phí theo số giây của video đầu vào cộng số giây của đầu ra được tạo.
  • input_video (chỉnh sửa / nối tiếp) phải là URL CÔNG KHAI. Video bạn tạo ở đây được phục vụ sau API key của bạn, nên upstream không thể tải về —— hãy host video nguồn của bạn trên một URL truy cập công khai được.
  • Payload webhook không có chữ ký — xác nhận trạng thái/số tiền qua GET /videos/{id} trước khi hành động, và lưu ý unsigned_urls ở đó là tuyệt đối (khác với đường dẫn tương đối trong phản hồi poll).

Mô hình video được hỗ trợ

Model IDModalityTasks
bytedance/seedance-2.0text+image+audio+video->videot2v, i2v
bytedance/seedance-2.0-fasttext+image+audio+video->videot2v, i2v
google/veo-3.1text+image->videot2v, i2v
openai/sora-2-protext+image->videot2v, i2v
bytedance/seedance-1-5-protext+image->videot2v, i2v
alibaba/happyhorse-1.0text->videot2v
alibaba/wan2.6-r2v-flashtext+image+video->videor2v
alibaba/wan2.5-i2v-previewtext+image->videoi2v
alibaba/happyhorse-1.1text->videot2v
alibaba/wan2.7-t2vtext->videot2v
alibaba/wan2.7-i2vtext+image+video->videoi2v, kf2v, continuation
alibaba/wan2.6-t2vtext->videot2v
alibaba/wan2.5-t2v-previewtext->videot2v
alibaba/wan2.2-t2v-plustext->videot2v
alibaba/wan2.7-r2vtext+image+video->videor2v
alibaba/wan2.1-t2v-plustext->videot2v
alibaba/wan2.1-t2v-turbotext->videot2v
alibaba/wan2.6-i2v-flashtext+image->videoi2v
alibaba/wan2.2-i2v-flashtext+image->videoi2v
alibaba/wan2.7-videoedittext+image+video->videovideoedit
alibaba/wan2.6-i2vtext+image->videoi2v
alibaba/wan2.2-i2v-plustext+image->videoi2v
alibaba/wan2.6-r2vtext+image+video->videor2v

Đầu vào video

Gửi tệp video đến các mô hình hỗ trợ đầu vào video để phân tích, tạo chú thích, hoặc trả lời câu hỏi về cảnh và sự kiện. Dùng được URL trực tiếp hoặc base64 data URI — URL hiệu quả hơn cho video công khai; base64 dành cho tệp cục bộ hoặc video riêng tư.

Định dạng được hỗ trợ

MP4 (H.264)MPEGMOVWebM
response = client.chat.completions.create(
    model="google/gemini-2.5-flash",
    messages=[{
        "role": "user",
        "content": [
            {
                "type": "video_url",
                "video_url": {"url": "https://example.com/video.mp4"},
            },
            {"type": "text", "text": "What is happening in this video?"},
        ],
    }],
)

Tài liệu tham khảo API đầy đủ →

Đầu vào PDF

Gửi tài liệu PDF trực tiếp trong tin nhắn đến các mô hình hỗ trợ đầu vào PDF gốc (ví dụ: Claude, Gemini). BazaarLink chuyển tệp thẳng đến mô hình — tính phí như input token thông thường, không phụ phí hay bước xử lý thêm.

Định dạng được hỗ trợ

  • Tài liệu PDF (văn bản, hình ảnh, bảng, quét)
  • URL dữ liệu base64
  • Tài liệu nhiều trang
  • Chỉ PDF không có mật khẩu
import base64

with open("document.pdf", "rb") as f:
    pdf_data = base64.b64encode(f.read()).decode()

response = client.chat.completions.create(
    model="anthropic/claude-sonnet-4.6",
    messages=[{
        "role": "user",
        "content": [
            {
                "type": "file",
                "file": {
                    "filename": "document.pdf",
                    "file_data": f"data:application/pdf;base64,{pdf_data}",
                },
            },
            {"type": "text", "text": "Summarize this document."},
        ],
    }],
)

Responses API

Endpoint tương thích OpenAI Responses API cho hội thoại đa lượt không trạng thái, gọi công cụ và đầu vào đa phương thức. Lý tưởng cho agent và framework sử dụng OpenAI Python SDK ≥ 1.x với client.responses.create().

POST/api/v1/responses
Note
Chấp nhận cùng xác thực và định tuyến mô hình như Chat Completions.

Nội dung yêu cầu

modelbắt buộc
string
ID mô hình, ví dụ "openai/gpt-4o" hoặc "anthropic/claude-3.5-sonnet"
inputbắt buộc
string | Item[]
Đầu vào người dùng — chuỗi văn bản (tin nhắn đơn) hoặc mảng mục đầu vào cho hội thoại đa lượt / đa phương thức.
instructions
string
Hướng dẫn cấp hệ thống, tương đương tin nhắn system. Phải gửi lại mỗi yêu cầu.
stream
boolean
Nếu true, trả về sự kiện SSE Responses API. Loại sự kiện: response.created, response.output_text.delta, response.completed.
max_output_tokens
integer
Số token đầu ra tối đa để tạo (bao gồm token suy luận cho mô hình o-series).
temperature
number
Nhiệt độ lấy mẫu 0–2. Cao hơn = ngẫu nhiên hơn. Mặc định: 1
top_p
number
Xác suất lấy mẫu nucleus. Mặc định: 1
tools
Tool[]
Định nghĩa công cụ (hàm) — cùng định dạng JSON Schema như Chat Completions (chấp nhận cả dạng phẳng của Responses và dạng lồng). Các công cụ tích hợp sẵn của riêng OpenAI (web_search_preview, file_search, computer_use_preview) không được hỗ trợ; tìm kiếm web khả dụng qua plugins: [{id:"web"}] — chỉ hỗ trợ trên một số tuyến model.
tool_choice
string | object
Điều khiển sử dụng công cụ: "auto", "none", hoặc công cụ cụ thể
parallel_tool_calls
boolean
Bật gọi hàm song song khi cung cấp công cụ. Mặc định: true. Chỉ áp dụng cho mô hình họ OpenAI — xem ghi chú bên dưới.
response_format
object
Buộc đầu ra JSON có cấu trúc. Xem phần Đầu ra có cấu trúc
models
string[]
Danh sách mô hình dự phòng — BazaarLink thử từng cái theo thứ tự nếu chính thất bại
transforms
string[]
Chuyển đổi tin nhắn để áp dụng, ví dụ ["middle-out"]. Bỏ qua để tự động áp dụng trên mô hình ≤8k context
previous_response_id
string
Endpoint này không trạng thái — truyền giá trị khác null sẽ trả về 400 (invalid_prompt) ngay lập tức, không bao giờ được chấp nhận rồi bỏ qua. Hãy dùng chế độ không trạng thái: truyền toàn bộ lịch sử hội thoại trong mảng input.
provider
object
Tùy chọn định tuyến nâng cao — hầu hết người dùng không cần.

Schema yêu cầu (TypeScript)

type ResponsesRequest = {
  model: string;                    // "provider/model-name"
  input: string | InputItem[];      // string or multi-turn array

  // Optional
  instructions?: string;            // System-level message
  stream?: boolean;                 // Default: false
  max_output_tokens?: number;
  temperature?: number;             // Range: [0, 2], default: 0.7
  top_p?: number;
  tools?: Tool[];
  tool_choice?: "auto" | "none" | "required" | object;
  parallel_tool_calls?: boolean;    // Default: true
  previous_response_id?: string;    // Not supported — use full input array
  provider?: ProviderPreferences;   // Same as Chat Completions
};

type InputItem =
  | { type?: "message"; role: "user" | "assistant" | "system" | "developer"; content: string | ContentBlock[] }
  | { type: "function_call_output"; call_id: string; output: string }   // tool result
  | { type: "function_call"; call_id: string; name: string; arguments: string };

type ContentBlock =
  | { type: "input_text"; text: string }
  | { type: "input_image"; image_url: string; detail?: "auto" | "low" | "high" };

Yêu cầu mẫu

curl https://bazaarlink.ai/api/v1/responses \
  -H "Authorization: Bearer $BAZAARLINK_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-4o-mini",
    "instructions": "You are a helpful assistant.",
    "input": "What is the capital of Taiwan?"
  }'

Định dạng phản hồi

// Non-streaming response object
type ResponsesResponse = {
  id: string;             // "resp_..."
  object: "response";
  created_at: number;
  completed_at: number;
  status: "completed" | "failed" | "incomplete";
  model: string;
  output: OutputItem[];
  usage: {
    input_tokens: number;   // equivalent to prompt_tokens
    output_tokens: number;  // equivalent to completion_tokens
    total_tokens: number;
    cost?: number;          // actual cost in credits
  } | null;
  error: null | { code: string; message: string };
};

type OutputItem =
  | {
      type: "message";
      id: string;
      role: "assistant";
      status: "completed";
      content: Array<{ type: "output_text"; text: string; annotations: [] }>;
    }
  | { type: "function_call"; id: string; call_id: string; name: string; arguments: string; status: "completed" };

Di chuyển từ Chat Completions

Thay messages bằng input (chuỗi hoặc mảng), dùng instructions thay cho tin nhắn system-role, và đọc output[0].content[0].text thay vì choices[0].message.content.

# Chat Completions (before)
response = client.chat.completions.create(
    model="openai/gpt-4o-mini",
    messages=[
        {"role": "system", "content": "You are helpful."},
        {"role": "user",   "content": "Hello"},
    ]
)
text = response.choices[0].message.content

# Responses API (after)
response = client.responses.create(
    model="openai/gpt-4o-mini",
    instructions="You are helpful.",
    input="Hello"
)
text = response.output[0].content[0].text

Hạn chế

  • previous_response_id hoặc store: true bị từ chối với 400 (mã lỗi invalid_prompt) — không phải chấp nhận rồi bỏ qua. Luôn dùng chế độ không trạng thái: truyền toàn bộ lịch sử hội thoại trong mảng input.
  • Các công cụ tích hợp sẵn của riêng OpenAI (web_search_preview, file_search, computer_use_preview) không được hỗ trợ. Tìm kiếm web khả dụng qua plugins: [{id:"web"}] — chỉ hỗ trợ trên một số tuyến model.
  • background: true được chấp nhận nhưng bị bỏ qua — mọi yêu cầu đều chạy đồng bộ đến khi hoàn tất.

Messages (Anthropic)

Anthropic API dành cho Claude SDK. Sử dụng chính xác như bạn muốn với API của Anthropic - chỉ cần thay đổi tiêu đề cơ sở URL và auth.

POST/api/v1/messages
Note
AChấp nhận mã thông báo mang hoặc tiêu đề x-api-key (khả năng tương thích Anthropic SDK). Kích thước cơ thể tối đa: 10 MB.

Nội dung yêu cầu

modelbắt buộc
string
ID mô hình, ví dụ "openai/gpt-4o" hoặc "anthropic/claude-3.5-sonnet"
max_tokensbắt buộc
integer
Số lượng mã thông báo tối đa cần tạo (số nguyên dương).
messagesbắt buộc
Message[]
Mảng tin nhắn hội thoại (không trống).
system
string
Lời nhắc hệ thống tùy chọn.
stream
boolean
Nếu true, trả về luồng Server-Sent Events. Mặc định: false
temperature
number
Nhiệt độ lấy mẫu 0–2. Cao hơn = ngẫu nhiên hơn. Mặc định: 1
top_p
number
Xác suất lấy mẫu nucleus. Mặc định: 1
top_k
integer
Giới hạn lựa chọn token cho top-K. 0 = tắt (xem xét tất cả). Mặc định: 0
stop_sequences
string[]
Chuỗi trình tự dừng tùy chỉnh.
tools
Tool[]
Danh sách công cụ (hàm) mô hình có thể gọi
tool_choice
string | object
Điều khiển sử dụng công cụ: "auto", "none", hoặc công cụ cụ thể

Yêu cầu mẫu

from anthropic import Anthropic

client = Anthropic(
    base_url="https://bazaarlink.ai/api/v1",
    api_key="sk-bl-YOUR_KEY"
)

response = client.messages.create(
    model="anthropic/claude-opus-4",
    max_tokens=1024,
    messages=[{"role": "user", "content": "Hello"}]
)
print(response.content[0].text)

Phản hồi

{
  "id": "msg_...",
  "type": "message",
  "role": "assistant",
  "model": "anthropic/claude-opus-4",
  "content": [
    { "type": "text", "text": "Hello! How can I help you today?" }
  ],
  "stop_reason": "end_turn",
  "usage": {
    "input_tokens": 10,
    "output_tokens": 12,
    "cache_read_input_tokens": 0,
    "cache_creation_input_tokens": 0,
    "bz_cost": 0.00042
  }
}

Errors: 400 (xác thực), 402 (không đủ tín dụng), 429 (giới hạn tốc độ), 502 (lỗi ngược dòng / thiếu khóa), 503 (khởi động lại máy chủ).

Mô hình

Liệt kê tất cả mô hình khả dụng với thông tin giá và khả năng. Không cần xác thực cho endpoint này.

GET/api/v1/models
# Text models (default)
curl https://bazaarlink.ai/api/v1/models

# Complete catalog
curl "https://bazaarlink.ai/api/v1/models?output_modalities=all"

Phản hồi

{
  "data": [
    {
      "id": "openai/gpt-4.1",
      "name": "GPT 4.1",
      "context_length": 1047576,
      "modality": "text+image+file->text",
      "pricing": {
        "prompt": "2.00",
        "completion": "8.00"
      }
    }
  ]
}
// /v1/models — Response Schema
type ModelsResponse = {
  data: Model[];
};

type Model = {
  id: string;                    // Model ID (e.g. "openai/gpt-4.1")
  name: string;                  // Human-readable name
  context_length: number | null; // Max context window in tokens
  modality: string | null;       // e.g. "text->text", "text+image->text"
  architecture?: {
    input_modalities?: string[];
    output_modalities?: Array<
      "text" | "image" | "embeddings" | "audio" |
      "video" | "rerank" | "speech" | "transcription"
    >;
  };
  pricing: {
    prompt: string;              // Input price per 1M tokens (USD)
    completion: string;          // Output price per 1M tokens (USD)
  };
  description?: string | null;   // Model description
  top_provider?: {
    max_completion_tokens?: number;
  };
  supported_parameters?: string[]; // e.g. ["tools", "response_format", "reasoning"]
  pricing_tiers?: {               // Present only for models with input-length tiers
    above_prompt_tokens: number;  // Ascending; strict "greater than" threshold
    prompt: string;                // USD per token, override tier
    completion: string;            // USD per token, override tier
  }[];
};

Giá theo bậc dựa trên độ dài đầu vào

Một số mô hình chuyển sang bảng giá khác khi prompt vượt ngưỡng token — toàn bộ bảng giá thay đổi, không chỉ phần token vượt ngưỡng. Ngưỡng là bất đẳng thức nghiêm ngặt: prompt có đúng N token vẫn tính theo bậc dưới N; bậc cao hơn chỉ áp dụng khi số token đầu vào lớn hơn N.

pricing_tiers là trường ngang cấp với pricing, chỉ xuất hiện khi mô hình có các bậc ghi đè vượt quá giá cơ bản. Các mục được sắp xếp theo above_prompt_tokens tăng dần; prompt/completion là USD trên mỗi token (cùng đơn vị với pricing.prompt/pricing.completion). pricing.prompt và pricing.completion luôn là bậc cơ bản (thấp nhất).

Hầu hết các mô hình không có bậc giá — với những mô hình đó, khóa pricing_tiers hoàn toàn không có trong phản hồi.

{
  "id": "openai/gpt-4.1",
  "name": "GPT 4.1",
  "pricing": {
    "prompt": "2.00",
    "completion": "8.00"
  },
  "pricing_tiers": [
    {
      "above_prompt_tokens": 128000,
      "prompt": "4.00",
      "completion": "16.00"
    }
  ]
}

Mô hình khả dụng (257)

Đây là các mô hình hiện có trên BazaarLink, tải động từ cơ sở dữ liệu:

OpenAI
openai/gpt-5.3-codex400K ctx · $1.75/$14.00text+image+file->text
openai/gpt-3.5-turbo-instruct4K ctx · $1.50/$2.00text->text
openai/gpt-5.4-nano400K ctx · $0.20/$1.25text+image+file->text
openai/gpt-5-codex400K ctx · $1.25/$10.00text+image->text
openai/text-embedding-ada-0028K ctx · $0.10/$0.00text->embeddings
openai/gpt-5.2-codex400K ctx · $1.75/$14.00text+image->text
openai/gpt-4-turbo-preview128K ctx · $10.00/$30.00text->text
openai/o4-mini200K ctx · $1.10/$4.40text+image+file->text
openai/o1-pro200K ctx · $150.00/$600.00text+image+file->text
openai/gpt-5.4-mini400K ctx · $0.75/$4.50text+image+file->text
openai/gpt-5.1400K ctx · $1.25/$10.00text+image+file->text
openai/o3-pro200K ctx · $20.00/$80.00text+image+file->text
openai/gpt-5.6-luna-pro1050K ctx · $1.00/$6.00text+image+file->text
openai/gpt-48K ctx · $30.00/$60.00text->text
openai/gpt-5.6-sol1050K ctx · $5.00/$30.00text+image+file->text
openai/gpt-4o-mini-2024-07-18128K ctx · $0.15/$0.60text+image+file->text
openai/gpt-5-mini400K ctx · $0.25/$2.00text+image+file->text
openai/gpt-5.6-luna1050K ctx · $1.00/$6.00text+image+file->text
openai/gpt-4o-2024-08-06128K ctx · $2.50/$10.00text+image+file->text
openai/o3-deep-research200K ctx · $10.00/$40.00text+image+file->text
openai/gpt-5.2-chat128K ctx · $1.75/$14.00text+image+file->text
openai/gpt-5.2400K ctx · $1.75/$14.00text+image+file->text
openai/gpt-5.1-chat128K ctx · $1.25/$10.00text+image+file->text
openai/o4-mini-deep-research200K ctx · $2.00/$8.00text+image+file->text
openai/text-embedding-3-small8K ctx · $0.02/$0.00text->embeddings
openai/gpt-4.1-nano1048K ctx · $0.10/$0.40text+image+file->text
openai/o3200K ctx · $2.00/$8.00text+image+file->text
openai/gpt-3.5-turbo16K ctx · $0.50/$1.50text->text
openai/gpt-5.51050K ctx · $5.00/$30.00text+image+file->text
openai/gpt-3.5-turbo-06134K ctx · $1.00/$2.00text->text
openai/gpt-4.11048K ctx · $2.00/$8.00text+image+file->text
openai/gpt-5-pro400K ctx · $15.00/$120.00text+image+file->text
openai/gpt-4.1-mini1048K ctx · $0.40/$1.60text+image+file->text
openai/gpt-oss-20b131K ctx · $0.03/$0.13text->text
openai/gpt-5.2-pro400K ctx · $21.00/$168.00text+image+file->text
openai/o4-mini-high200K ctx · $1.10/$4.40text+image+file->text
openai/gpt-3.5-turbo-16k16K ctx · $3.00/$4.00text->text
openai/gpt-4o-mini128K ctx · $0.15/$0.60text+image+file->text
openai/gpt-5.3-chat128K ctx · $1.75/$14.00text+image+file->text
openai/gpt-4o-2024-05-13128K ctx · $5.00/$15.00text+image+file->text
openai/gpt-oss-120b131K ctx · $0.15/$0.60text->text
openai/o3-mini200K ctx · $1.10/$4.40text+file->text
openai/gpt-4-turbo128K ctx · $10.00/$30.00text+image->text
openai/gpt-5.4-pro1050K ctx · $30.00/$180.00text+image+file->text
openai/text-embedding-3-large8K ctx · $0.13/$0.00text->embeddings
openai/gpt-5.41050K ctx · $2.50/$15.00text+image+file->text
openai/gpt-5.1-codex-max400K ctx · $1.25/$10.00text+image->text
openai/gpt-5-nano400K ctx · $0.05/$0.40text+image+file->text
openai/o1200K ctx · $15.00/$60.00text+image+file->text
openai/gpt-5.1-codex-mini400K ctx · $0.25/$2.00text+image->text
openai/gpt-5.6-terra-pro1050K ctx · $2.50/$15.00text+image+file->text
openai/gpt-5.6-terra1050K ctx · $2.50/$15.00text+image+file->text
openai/gpt-5400K ctx · $1.25/$10.00text+image+file->text
openai/gpt-5.6-sol-pro1050K ctx · $5.00/$30.00text+image+file->text
openai/gpt-5.1-codex400K ctx · $1.25/$10.00text+image->text
openai/o3-mini-high200K ctx · $1.10/$4.40text+file->text
openai/gpt-4o-2024-11-20128K ctx · $2.50/$10.00text+image+file->text
openai/sora-2-pro · $0.00/$0.00text+image->video
openai/gpt-4o128K ctx · $2.50/$10.00text+image+file->text
openai/gpt-oss-safeguard-20b131K ctx · $0.07/$0.30text->text
openai/gpt-5.4-image-2272K ctx · $8.00/$15.00text+image+file->text+image
openai/gpt-image-1400K ctx · $10.00/$10.00text+image->image
openai/gpt-image-2400K ctx · $8.00/$8.00text+image->image
openai/gpt-image-1-mini400K ctx · $2.50/$2.50text+image->image
Qwen
qwen/qwen3.7-plus1000K ctx · $0.32/$1.28text+image->text
qwen/qwen3.7-max1000K ctx · $1.48/$4.42text->text
qwen/qwen3.5-plus-02-151000K ctx · $0.26/$1.56text+image+video->text
qwen/qwen3-coder-flash1000K ctx · $0.20/$0.97text->text
qwen/qwen-2.5-coder-32b-instruct33K ctx · $0.66/$1.00text->text
qwen/qwen-plus1000K ctx · $0.26/$0.78text->text
qwen/qwen3.6-35b-a3b262K ctx · $0.14/$1.00text+image+video->text
qwen/qwen3-coder262K ctx · $0.30/$1.00text->text
qwen/qwen-plus-2025-07-281000K ctx · $0.26/$0.78text->text
qwen/qwen3-235b-a22b-2507262K ctx · $0.09/$0.55text->text
qwen/qwen3.5-plus-202604201000K ctx · $0.30/$1.80text+image+video->text
qwen/qwen3-embedding-4b33K ctx · $0.02/$0.00text->embeddings
qwen/qwen3-coder-30b-a3b-instruct262K ctx · $0.07/$0.27text->text
qwen/qwen-2.5-7b-instruct33K ctx · $0.04/$0.10text->text
qwen/qwen3-coder-plus1000K ctx · $0.65/$3.25text->text
qwen/qwen3-next-80b-a3b-instruct262K ctx · $0.10/$1.10text->text
qwen/qwen-2.5-72b-instruct33K ctx · $0.36/$0.40text->text
qwen/qwen-plus-2025-07-28:thinking1000K ctx · $0.40/$1.20text->text
qwen/qwen3-vl-235b-a22b-thinking131K ctx · $0.40/$4.00text+image->text
qwen/qwen3-vl-8b-thinking131K ctx · $0.18/$2.10text+image->text
qwen/qwen3-30b-a3b-instruct-2507262K ctx · $0.05/$0.19text->text
qwen/qwen3.5-flash-02-231000K ctx · $0.07/$0.26text+image+video->text
qwen/qwen3-vl-235b-a22b-instruct262K ctx · $0.21/$1.90text+image->text
qwen/qwen3.5-27b262K ctx · $0.20/$1.56text+image+video->text
qwen/qwen3-235b-a22b131K ctx · $0.46/$1.82text->text
qwen/qwen3.5-9b262K ctx · $0.10/$0.15text+image+video->text
qwen/qwen3-32b131K ctx · $0.08/$0.28text->text
qwen/qwen3-30b-a3b131K ctx · $0.13/$0.52text->text
qwen/qwen3-8b131K ctx · $0.12/$0.46text->text
qwen/qwen3-max-thinking262K ctx · $0.78/$3.90text->text
qwen/qwen3-vl-8b-instruct262K ctx · $0.12/$0.46text+image->text
qwen/qwen3.5-122b-a10b262K ctx · $0.26/$2.08text+image+video->text
qwen/qwen3-next-80b-a3b-thinking262K ctx · $0.15/$1.20text->text
qwen/qwen3-vl-30b-a3b-thinking262K ctx · $0.20/$2.40text+image->text
qwen/qwen2.5-vl-72b-instruct128K ctx · $0.80/$1.00text+image->text
qwen/qwen3-235b-a22b-thinking-2507262K ctx · $0.30/$3.00text->text
qwen/qwen3.5-35b-a3b262K ctx · $0.14/$1.00text+image+video->text
qwen/qwen3-coder-next262K ctx · $0.12/$0.80text->text
qwen/qwen3-max262K ctx · $0.78/$3.90text->text
qwen/qwen3-30b-a3b-thinking-250782K ctx · $0.20/$2.40text->text
qwen/qwen3-vl-30b-a3b-instruct262K ctx · $0.13/$0.52text+image->text
qwen/qwen3-vl-32b-instruct131K ctx · $0.10/$0.42text+image->text
qwen/qwen3-14b131K ctx · $0.23/$0.91text->text
qwen/qwen3.5-397b-a17b262K ctx · $0.39/$2.34text+image+video->text
qwen/qwen3.6-27b262K ctx · $0.29/$2.40text+image+video->text
qwen/qwen3.6-plus1000K ctx · $0.33/$1.95text+image+video->text
qwen/qwen3-embedding-8b33K ctx · $0.01/$0.00text->embeddings
qwen/qwen-image-maxtext->image
qwen/qwen-image-plustext->image
qwen/qwen-image-edittext+image->image
qwen/qwen-image-2.0-protext->image
qwen/qwen-image-edit-plustext+image->image
qwen/qwen-image-2.0text->image
qwen/qwen-imagetext->image
qwen/qwen-image-edit-maxtext+image->image
Alibaba
alibaba/wan2.7-image-protext->image
alibaba/happyhorse-1.0 · $0.00/$0.00text->video
alibaba/wan2.6-r2v-flash · $0.00/$0.00text+image+video->video
alibaba/wan2.2-t2i-flashtext->image
alibaba/wan2.1-t2i-plustext->image
alibaba/wan2.1-t2i-turbotext->image
alibaba/z-image-turbotext->image
alibaba/wan2.2-t2i-plustext->image
alibaba/wan2.6-imagetext->image
alibaba/wan2.5-i2v-preview · $0.00/$0.00text+image->video
alibaba/happyhorse-1.1 · $0.00/$0.00text->video
alibaba/wan2.7-t2v · $0.00/$0.00text->video
alibaba/wan2.7-i2v · $0.00/$0.00text+image+video->video
alibaba/wan2.6-t2v · $0.00/$0.00text->video
alibaba/wan2.5-t2v-preview · $0.00/$0.00text->video
alibaba/wan2.2-t2v-plus · $0.00/$0.00text->video
alibaba/wan2.7-r2v · $0.00/$0.00text+image+video->video
alibaba/wan2.1-t2v-plus · $0.00/$0.00text->video
alibaba/wan2.1-t2v-turbo · $0.00/$0.00text->video
alibaba/wan2.6-i2v-flash · $0.00/$0.00text+image->video
alibaba/wan2.2-i2v-flash · $0.00/$0.00text+image->video
alibaba/wan2.5-t2i-previewtext->image
alibaba/wan2.7-videoedit · $0.00/$0.00text+image+video->video
alibaba/wan2.6-i2v · $0.00/$0.00text+image->video
alibaba/wan2.5-i2i-previewtext+image->image
alibaba/wan2.2-i2v-plus · $0.00/$0.00text+image->video
alibaba/wan2.6-r2v · $0.00/$0.00text+image+video->video
alibaba/wan2.6-t2itext->image
alibaba/wan2.7-imagetext->image
Google
google/gemini-3.1-pro-preview1049K ctx · $2.00/$12.00text+image+file+audio+video->text
google/gemini-3.1-flash-lite-preview1049K ctx · $0.25/$1.50text+image+file+audio+video->text
google/gemini-2.5-flash-lite1049K ctx · $0.10/$0.40text+image+file+audio+video->text
google/gemma-3-4b-it131K ctx · $0.05/$0.10text+image->text
google/gemini-embedding-2-preview8K ctx · $0.20/$0.00text+image+file+audio+video->embeddings
google/gemini-2.5-flash-image33K ctx · $0.30/$2.50text+image->text+image
google/gemini-3.5-flash1049K ctx · $1.50/$9.00text+image+file+audio+video->text
google/gemini-2.5-pro-preview1049K ctx · $1.25/$10.00text+image+file+audio->text
google/gemma-3n-e4b-it33K ctx · $0.06/$0.12text->text
google/gemini-3.1-flash-image131K ctx · $0.50/$3.00text+image->text+image
google/gemini-2.5-flash1049K ctx · $0.30/$2.50text+image+file+audio+video->text
google/gemini-3-flash-preview1049K ctx · $0.50/$3.00text+image+file+audio+video->text
google/gemma-3-12b-it131K ctx · $0.05/$0.15text+image->text
google/gemma-2-27b-it8K ctx · $0.65/$0.65text->text
google/gemini-2.5-pro1049K ctx · $1.25/$10.00text+image+file+audio+video->text
google/gemma-4-31b-it262K ctx · $0.14/$0.40text+image+video->text
google/gemini-embedding-00120K ctx · $0.15/$0.00text->embeddings
google/gemini-2.5-pro-preview-05-061049K ctx · $1.25/$10.00text+image+file+audio+video->text
google/gemini-3.5-flash-lite1049K ctx · $0.30/$2.50text+image+file+audio+video->text
google/gemma-3-27b-it262K ctx · $0.08/$0.45text+image->text
google/veo-3.1 · $0.00/$0.00text+image->video
google/gemini-3-pro-image131K ctx · $2.00/$12.00text+image->text+image
google/gemini-3.1-pro-preview-customtools1049K ctx · $2.00/$12.00text+image+file+audio+video->text
google/gemma-4-26b-a4b-it262K ctx · $0.07/$0.34text+image+video->text
google/gemini-3.6-flash1049K ctx · $1.50/$7.50text+image+file+audio+video->text
google/gemini-3.1-flash-image-preview66K ctx · $0.50/$3.00text+image->text+image
Anthropic
anthropic/claude-opus-4.61000K ctx · $5.00/$25.00text+image+file->text
anthropic/claude-sonnet-4.61000K ctx · $3.00/$15.00text+image+file->text
anthropic/claude-sonnet-41000K ctx · $3.00/$15.00text+image+file->text
anthropic/claude-sonnet-51000K ctx · $2.00/$10.00text+image+file->text
anthropic/claude-haiku-4.5200K ctx · $1.00/$5.00text+image+file->text
anthropic/claude-sonnet-4.51000K ctx · $3.00/$15.00text+image+file->text
anthropic/claude-opus-4.71000K ctx · $5.00/$25.00text+image+file->text
anthropic/claude-fable-51000K ctx · $10.00/$50.00text+image+file->text
anthropic/claude-opus-4.81000K ctx · $5.00/$25.00text+image+file->text
anthropic/claude-3-haiku200K ctx · $0.25/$1.25text+image->text
anthropic/claude-opus-4.5200K ctx · $5.00/$25.00text+image+file->text
anthropic/claude-opus-4200K ctx · $15.00/$75.00text+image+file->text
anthropic/claude-opus-4.1200K ctx · $15.00/$75.00text+image+file->text
anthropic/claude-opus-51000K ctx · $5.00/$25.00text+image+file->text
Zhipu AI
z-ai/glm-4.7205K ctx · $0.40/$1.75text->text
z-ai/glm-5205K ctx · $1.00/$3.20text->text
z-ai/glm-5.1205K ctx · $1.40/$4.40text->text
z-ai/glm-5.21049K ctx · $1.40/$4.40text->text
z-ai/glm-5v-turbo203K ctx · $1.20/$4.00text+image+video->text
z-ai/glm-5-turbo203K ctx · $1.20/$4.00text->text
z-ai/glm-4.6v131K ctx · $0.30/$0.90text+image+video->text
z-ai/glm-4.6205K ctx · $0.50/$2.00text->text
z-ai/glm-4.7-flash203K ctx · $0.06/$0.40text->text
z-ai/glm-4.5-air131K ctx · $0.13/$0.85text->text
z-ai/glm-4.5131K ctx · $0.60/$2.20text->text
z-ai/glm-4.5v66K ctx · $0.60/$1.80text+image->text
DeepSeek
deepseek/deepseek-v3.2164K ctx · $0.28/$0.42text->text
deepseek/deepseek-v4-pro1049K ctx · $2.40/$4.80text->text
deepseek/deepseek-v4-flash1049K ctx · $0.20/$0.40text->text
deepseek/deepseek-v3.2-exp164K ctx · $0.27/$0.41text->text
deepseek/deepseek-r1164K ctx · $0.70/$2.50text->text
deepseek/deepseek-v3.1-terminus164K ctx · $0.27/$1.00text->text
deepseek/deepseek-chat-v3-0324164K ctx · $0.27/$1.12text->text
deepseek/deepseek-r1-0528164K ctx · $0.50/$2.15text->text
deepseek/deepseek-r1-distill-llama-70b8K ctx · $0.80/$0.80text->text
deepseek/deepseek-chat-v3.1164K ctx · $0.25/$0.95text->text
deepseek/deepseek-chat164K ctx · $0.40/$1.30text->text
Moonshot AI
moonshotai/kimi-k31049K ctx · $3.00/$15.00text+image->text
moonshotai/kimi-k2.7-code-highspeed · $1.90/$8.00
moonshotai/kimi-k2.7-code262K ctx · $0.95/$4.00text+image->text
moonshotai/kimi-k2.5262K ctx · $0.60/$3.00text+image->text
moonshotai/kimi-k2.6262K ctx · $0.86/$3.57text+image->text
moonshotai/kimi-k2131K ctx · $0.57/$2.30text->text
moonshotai/kimi-k2-0905262K ctx · $0.60/$2.50text->text
moonshotai/kimi-k2-thinking262K ctx · $0.60/$2.50text->text
xAI
x-ai/grok-4.202000K ctx · $1.25/$2.50text+image+file->text
x-ai/grok-4.20-multi-agent2000K ctx · $1.25/$2.50text+image+file->text
x-ai/grok-4.31000K ctx · $1.25/$2.50text+image+file->text
x-ai/grok-4.5500K ctx · $2.00/$6.00text+image+file->text
x-ai/grok-build-0.1256K ctx · $1.00/$2.00text+image+file->text
Perplexity
perplexity/sonar-pro200K ctx · $3.00/$15.00text+image->text
perplexity/sonar-reasoning-pro128K ctx · $2.00/$8.00text+image->text
perplexity/sonar127K ctx · $1.00/$1.00text+image->text
perplexity/sonar-deep-research128K ctx · $2.00/$8.00text->text
perplexity/sonar-pro-search200K ctx · $3.00/$15.00text+image->text
MiniMax
minimax/minimax-m2.7205K ctx · $0.30/$1.20text->text
minimax/minimax-m2.5205K ctx · $0.30/$1.20text->text
minimax/minimax-m31049K ctx · $0.30/$1.20text+image+video->text
minimax/minimax-m2.1205K ctx · $0.30/$1.20text->text
Tencent
tencent/kinfra-text-embedding-4b · $0.08/$0.00
tencent/hy3 · $0.13/$0.53
tencent/hy-mt2-plus · $0.10/$0.40
tencent/kinfra-text-embedding-0.6b · $0.07/$0.00
bytedance-seed
bytedance-seed/seed-2.0-mini262K ctx · $0.10/$0.40text+image+video->text
bytedance-seed/seed-1.6-flash262K ctx · $0.07/$0.30text+image+video->text
bytedance-seed/seed-1.6262K ctx · $0.25/$2.00text+image+video->text
bytedance-seed/seed-2.0-lite262K ctx · $0.25/$2.00text+image+video->text
Nous
nousresearch/hermes-3-llama-3.1-70b131K ctx · $0.70/$0.70text->text
nousresearch/hermes-3-llama-3.1-405b131K ctx · $1.00/$1.00text->text
nousresearch/hermes-4-70b131K ctx · $0.13/$0.40text->text
nousresearch/hermes-4-405b131K ctx · $1.00/$3.00text->text
ByteDance
bytedance/seedance-2.0 · $0.00/$0.00text+image+audio+video->video
bytedance/seedance-2.0-fast · $0.00/$0.00text+image+audio+video->video
bytedance/seedance-1-5-pro · $0.00/$0.00text+image->video
Mistral
mistralai/mistral-large128K ctx · $2.00/$6.00text+file->text
mistralai/mixtral-8x22b-instruct66K ctx · $2.00/$6.00text+file->text
NVIDIA
nvidia/nemotron-3-super-120b-a12b1000K ctx · $0.30/$0.90text->text
nvidia/nemotron-3-nano-30b-a3b262K ctx · $0.05/$0.20text->text
xiaomi
xiaomi/mimo-v2.51050K ctx · $0.14/$0.28text+image+audio+video->text
xiaomi/mimo-v2.5-pro1050K ctx · $0.43/$0.87text->text
ibm-granite
ibm-granite/granite-4.0-h-micro131K ctx · $0.02/$0.11text->text
Meta
meta-llama/llama-3.2-1b-instruct60K ctx · $0.03/$0.20text->text
Tongyi-MAI
Tongyi-MAI/Z-Image-Turbotext->image

Xem tất cả mô hình trên trang Mô hình.

Streaming

Đặt stream: true để nhận luồng Server-Sent Events (SSE). Mỗi sự kiện chứa một phần của phản hồi.

from openai import OpenAI

client = OpenAI(
    base_url="https://bazaarlink.ai/api/v1",
    api_key="sk-bl-YOUR_API_KEY",
)

stream = client.chat.completions.create(
    model="anthropic/claude-sonnet-4.6",
    messages=[{"role": "user", "content": "Count to 10 slowly."}],
    stream=True,
)

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

Định dạng SSE

data: {"id":"chatcmpl-abc","choices":[{"delta":{"content":"Hello"},"index":0}]}

data: {"id":"chatcmpl-abc","choices":[{"delta":{"content":" world"},"index":0}]}

data: {"id":"chatcmpl-abc","choices":[{"delta":{},"finish_reason":"stop","index":0}],"usage":{"prompt_tokens":10,"completion_tokens":4,"total_tokens":14}}

data: [DONE]
Sử dụng trong streaming
Khi streaming, dữ liệu sử dụng được trả về trong phần cuối cùng trước tin nhắn [DONE], cùng với mảng choices có delta rỗng và finish_reason: "stop".

Keep-alive & chunk cuối

Stream có thể chứa các dòng chú thích SSE (bắt đầu bằng dấu hai chấm) hoặc sự kiện heartbeat làm keep-alive — hãy bỏ qua các dòng không phải data: thay vì JSON.parse trực tiếp trên stream thô. Chunk data cuối cùng mang usage (số token và chi phí) trước data: [DONE]. Phản hồi thành công sẽ kèm header X-Request-Id — hãy đính kèm khi báo cáo sự cố.

: keepalive          <- SSE comment line — ignore, do NOT JSON.parse

data: {"id":"chatcmpl-abc","choices":[{"delta":{"content":"Hi"},"index":0}]}

data: {"id":"chatcmpl-abc","choices":[{"delta":{},"finish_reason":"stop","index":0}],"usage":{...}}

data: [DONE]

Hủy Stream

Yêu cầu streaming có thể bị hủy bằng cách đóng kết nối phía client — ví dụ gọi AbortController.abort() hoặc đóng đối tượng stream. BazaarLink sẽ ngừng chuyển tiếp các chunk tiếp theo và hủy yêu cầu gửi đến nhà cung cấp ngay khi nhận được lệnh hủy.

import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://bazaarlink.ai/api/v1",
  apiKey: "sk-bl-YOUR_API_KEY",
});

const controller = new AbortController();

const stream = await client.chat.completions.create(
  {
    model: "anthropic/claude-sonnet-4.6",
    messages: [{ role: "user", content: "Write a long story." }],
    stream: true,
  },
  { signal: controller.signal }
);

for await (const chunk of stream) {
  const content = chunk.choices[0]?.delta?.content;
  if (content) process.stdout.write(content);
}

// e.g. on a "Stop" button click:
controller.abort();
Không tính phí cho stream bị gián đoạn
Nếu stream kết thúc trước khi chunk usage cuối cùng đến — kể cả khi client chủ động hủy — sẽ không có căn cứ số token đáng tin cậy cho yêu cầu đó, vì vậy BazaarLink hoàn lại toàn bộ khoản đã giữ trước. Bạn không bị tính phí cho nội dung đã gửi tới client trước khi hủy.
Không đảm bảo dừng ngay lập tức ở phía nhà cung cấp
Đóng kết nối khiến BazaarLink ngừng chuyển tiếp và tính phí token ngay lập tức, nhưng việc nhà cung cấp upstream có dừng sinh nội dung trên máy chủ của họ ngay khi kết nối bị ngắt hay không tùy thuộc vào nhà cung cấp đó — một số có thể vẫn xử lý thêm một chút sau khi ngắt kết nối.

Lỗi Giữa Luồng

Khung lỗi không có trường choices
Nếu lỗi xảy ra sau khi streaming đã bắt đầu (ví dụ kết nối upstream bị ngắt), bạn sẽ nhận được một SSE data frame dạng {error:{message,type,code}} thay vì {choices:[...]} thông thường — không có thay đổi trạng thái HTTP vì header đã được gửi. Hãy kiểm tra trường error trước khi đọc choices[0].delta, và chỉ các token đã stream mới bị tính phí (áp dụng tính phí một phần).
data: {"id":"chatcmpl-abc","choices":[{"delta":{"content":"The capital of "},"index":0}]}

data: {"error":{"message":"Upstream connection lost.","type":"upstream_error","code":502}}

data: [DONE]

Embeddings

Embeddings là biểu diễn số học của văn bản nắm bắt ý nghĩa ngữ nghĩa — chuyển văn bản thành vector (dãy số) có thể dùng cho nhiều tác vụ machine learning. BazaarLink cung cấp một endpoint thống nhất, tương thích với OpenAI Embeddings API, để bạn gọi các mô hình embedding từ nhiều nhà cung cấp qua một giao diện duy nhất.

Embeddings là gì?

Embeddings biến văn bản thành vector nhiều chiều, trong đó các văn bản có ý nghĩa tương tự nằm gần nhau hơn trong không gian vector — ví dụ, "cat" và "kitten" sẽ có embedding tương tự nhau, còn "cat" và "airplane" sẽ cách xa nhau. Các biểu diễn vector này giúp máy hiểu được mối quan hệ giữa các đoạn văn bản, là nền tảng của nhiều ứng dụng AI.

Các trường hợp sử dụng phổ biến

Trường hợp sử dụng
Mô tả
RAG (Thế hệ tăng cường truy xuất)Xây dựng hệ thống truy xuất ngữ cảnh liên quan từ cơ sở tri thức trước khi tạo câu trả lời — embeddings tìm ra các tài liệu liên quan nhất để đưa vào ngữ cảnh của LLM.
Tìm kiếm ngữ nghĩaChuyển tài liệu và truy vấn thành embeddings, sau đó tìm tài liệu liên quan nhất bằng độ tương đồng vector — hiểu ý nghĩa thay vì chỉ khớp từ khóa, cho kết quả tốt hơn tìm kiếm từ khóa.
Hệ thống đề xuấtTạo embeddings cho các mục (sản phẩm, bài viết, video) và sở thích người dùng để đề xuất các mục tương tự — so sánh vector tìm ra các mục liên quan về ngữ nghĩa ngay cả khi không có từ khóa chung.
Phân cụm & Phân loạiNhóm các tài liệu tương tự hoặc phân loại văn bản bằng cách phân tích các mẫu embedding — tài liệu có embedding tương tự thường thuộc cùng chủ đề hoặc danh mục.
Phát hiện trùng lặpTìm nội dung trùng lặp hoặc gần trùng lặp bằng cách so sánh độ tương đồng embedding — vẫn hoạt động ngay cả khi nội dung đã được diễn đạt lại.
Phát hiện bất thườngNhận diện nội dung bất thường hoặc ngoại lệ bằng cách xác định các embedding lệch đáng kể so với mẫu điển hình của tập dữ liệu.
POST/api/v1/embeddings
Note
Không phải tất cả nhà cung cấp upstream đều hỗ trợ embeddings. Nếu nhà cung cấp được cấu hình không hỗ trợ mô hình yêu cầu, BazaarLink sẽ tự động chuyển sang nhà cung cấp khả dụng tiếp theo.

Tham số

modelbắt buộc
string
Mô hình embedding sử dụng, ví dụ "openai/text-embedding-3-small".
inputbắt buộc
string | string[] | ContentItem[]
Văn bản cần embedding — một chuỗi đơn, mảng chuỗi cho một lệnh gọi hàng loạt, hoặc (với các mô hình hỗ trợ) mảng các mục {content:[...]} kết hợp phần text và image_url.
dimensions
integer
Kích thước vector đầu ra được yêu cầu. Chỉ được áp dụng bởi các mô hình hỗ trợ số chiều thay đổi (ví dụ dòng OpenAI text-embedding-3); được chuyển tiếp nguyên trạng đến nhà cung cấp upstream và bị bỏ qua với các mô hình không hỗ trợ.
encoding_format
string
Định dạng mã hóa embedding được yêu cầu, ví dụ "float" hoặc "base64". Được chuyển tiếp nguyên trạng đến nhà cung cấp upstream — mức hỗ trợ tùy thuộc vào mô hình.
provider
object
Tùy chọn định tuyến nhà cung cấp — order, allow_fallbacks, data_collection và các trường khác được mô tả trong Provider Selection.

Yêu Cầu Cơ Bản

from openai import OpenAI

client = OpenAI(
    base_url="https://bazaarlink.ai/api/v1",
    api_key="sk-bl-YOUR_API_KEY",
)

response = client.embeddings.create(
    model="openai/text-embedding-3-small",
    input="The quick brown fox jumps over the lazy dog",
)

print(response.data[0].embedding)  # 1536-dimensional vector

Xử Lý Hàng Loạt

Gửi một mảng chuỗi để embedding nhiều văn bản trong một yêu cầu duy nhất — rẻ hơn và nhanh hơn so với gọi riêng cho từng văn bản.

response = client.embeddings.create(
    model="openai/text-embedding-3-small",
    input=[
        "Machine learning is a subset of artificial intelligence",
        "Deep learning uses neural networks with multiple layers",
        "Natural language processing enables computers to understand text",
    ],
)

for i, item in enumerate(response.data):
    print(f"Embedding {i}: {len(item.embedding)} dimensions")

Đầu Vào Đa Phương Thức (Hình Ảnh + Văn Bản)

Các mô hình hỗ trợ đầu vào hình ảnh (output_modalities gồm "embeddings" và inputModalities gồm "image") chấp nhận các mục đầu vào có dạng {content:[{type:"text",...}, {type:"image_url",...}]}, cho phép bạn embedding riêng một hình ảnh hoặc kết hợp cùng văn bản.

Tùy thuộc mô hình
Chỉ một số mô hình embedding chấp nhận đầu vào hình ảnh — kiểm tra các phương thức mà mô hình hỗ trợ trên trang Models trước khi gửi nội dung image_url. Mô hình chỉ hỗ trợ văn bản sẽ từ chối dạng này.
import requests

response = requests.post(
    "https://bazaarlink.ai/api/v1/embeddings",
    headers={
        "Authorization": "Bearer sk-bl-YOUR_API_KEY",
        "Content-Type": "application/json",
    },
    json={
        "model": "google/gemini-embedding-2-preview",
        "input": [{
            "content": [
                {"type": "text", "text": "A scenic boardwalk through a green meadow"},
                {"type": "image_url", "image_url": {"url": "https://example.com/boardwalk.jpg"}},
            ]
        }],
        "encoding_format": "float",
    },
)

embedding = response.json()["data"][0]["embedding"]
print(f"Embedding dimension: {len(embedding)}")

Định Tuyến Nhà Cung Cấp

Kiểm soát upstream nào phục vụ yêu cầu embedding, tương tự như chat completions — xem Provider Selection để có tham chiếu đầy đủ các trường.

{
  "model": "openai/text-embedding-3-small",
  "input": "Your text here",
  "provider": {
    "order": ["openai"],
    "allow_fallbacks": true,
    "data_collection": "deny"
  }
}

Tìm Mô Hình Embedding

Không có endpoint riêng để liệt kê mô hình embedding — gọi GET /api/v1/models rồi lọc phía client các mục có output_modalities chứa "embeddings", hoặc duyệt trang Models.

Giới Hạn

  • Không hỗ trợ streaming — embeddings luôn được trả về dưới dạng phản hồi hoàn chỉnh, khác với chat completions.
  • Mỗi mô hình có độ dài đầu vào tối đa; văn bản vượt quá giới hạn đó sẽ bị cắt bớt hoặc từ chối ở upstream.
  • Embeddings cho cùng một đầu vào là tất định (deterministic) — không có temperature hay tính ngẫu nhiên.

Thực Hành Tốt Nhất

  • Chọn mô hình theo cân bằng tốc độ/chất lượng/chi phí — mô hình nhỏ hơn (ví dụ qwen/qwen3-embedding-4b) rẻ và nhanh hơn; mô hình lớn hơn (ví dụ openai/text-embedding-3-large) thường embedding với độ chính xác cao hơn.
  • Gộp nhiều văn bản vào một yêu cầu thay vì gọi riêng cho từng văn bản — giảm số lượt round trip và overhead.
  • Lưu cache kết quả — embedding của cùng một đầu vào không bao giờ thay đổi, nên lưu lại thay vì tạo lại.
  • So sánh bằng cosine similarity thay vì khoảng cách Euclidean — bất biến theo tỷ lệ và hoạt động tốt hơn với vector nhiều chiều.
  • Chú ý độ dài ngữ cảnh của từng mô hình — tài liệu dài có thể cần chia nhỏ (chunking) trước khi embedding.

Tham số

Tham số lấy mẫu định hình quá trình tạo token. BazaarLink chuyển các tham số được hỗ trợ đến nhà cung cấp upstream; tham số không được hỗ trợ bị bỏ qua im lặng.

Tham số lấy mẫu

Chuyển tiếp thuần túy — không có giá trị mặc định cục bộ
Các tham số này được chuyển tiếp đến nhà cung cấp upstream đúng như đã gửi — BazaarLink không bao giờ chèn hoặc áp đặt giá trị mặc định. "Mặc định" bên dưới mô tả hành vi riêng của nhà cung cấp khi bỏ qua trường đó, không phải cam kết từ BazaarLink.
temperature
number
Nhiệt độ lấy mẫu 0–2. Cao hơn = ngẫu nhiên hơn. Mặc định: 1
top_p
number
Xác suất lấy mẫu nucleus. Mặc định: 1
top_k
integer
Giới hạn lựa chọn token cho top-K. 0 = tắt (xem xét tất cả). Mặc định: 0
frequency_penalty
number
Phạt token lặp lại. Phạm vi: [-2, 2]. Mặc định: 0
presence_penalty
number
Phạt token dựa trên sự hiện diện. Phạm vi: [-2, 2]. Mặc định: 0
repetition_penalty
number
Giảm lặp lại token từ đầu vào. Phạm vi: (0, 2]. Mặc định: 1
min_p
number
Xác suất tối thiểu tương đối với token hàng đầu. Phạm vi: [0, 1]. Mặc định: 0
top_a
number
Top-P động dựa trên token có xác suất cao nhất. Phạm vi: [0, 1]. Mặc định: 0
seed
integer
Seed số nguyên cho lấy mẫu xác định. Không đảm bảo cho tất cả mô hình
max_tokens
integer
Số token tối đa để tạo
n
integer
Số lượng hoàn thành để tạo. Mặc định: 1
logit_bias
object
Ánh xạ ID token đến giá trị thiên lệch [-100, 100] được thêm trước lấy mẫu. Chỉ áp dụng cho mô hình họ OpenAI — xem ghi chú bên dưới.
logprobs
boolean
Trả về log xác suất của mỗi token đầu ra. Chỉ áp dụng cho mô hình họ OpenAI — xem ghi chú bên dưới.
top_logprobs
integer
Số token có khả năng nhất trả về cho mỗi vị trí (cần logprobs: true). Phạm vi: 0–20. Chỉ áp dụng cho mô hình họ OpenAI — xem ghi chú bên dưới.
response_format
object
Buộc đầu ra JSON có cấu trúc. Xem phần Đầu ra có cấu trúc
structured_outputs
boolean
Yêu cầu đầu ra tuân thủ nghiêm ngặt JSON schema trên các nhà cung cấp hỗ trợ. Chuyển tiếp nguyên trạng
reasoning
object
Cấu hình reasoning/thinking riêng của nhà cung cấp. Chuyển tiếp nguyên trạng
reasoning_effort
string
Mức độ reasoning kiểu OpenAI dòng o: "low", "medium", hoặc "high". Chuyển tiếp nguyên trạng
stop
string | string[]
Chuỗi dừng — tạo văn bản dừng khi gặp
tools
Tool[]
Danh sách công cụ (hàm) mô hình có thể gọi
tool_choice
string | object
Điều khiển sử dụng công cụ: "auto", "none", hoặc công cụ cụ thể
parallel_tool_calls
boolean
Bật gọi hàm song song khi cung cấp công cụ. Mặc định: true. Chỉ áp dụng cho mô hình họ OpenAI — xem ghi chú bên dưới.

Tham số riêng BazaarLink

transforms
string[]
Chuyển đổi tin nhắn để áp dụng, ví dụ ["middle-out"]. Bỏ qua để tự động áp dụng trên mô hình ≤8k context
models
string[]
Danh sách mô hình dự phòng — BazaarLink thử từng cái theo thứ tự nếu chính thất bại
route
string
Trường tương thích định tuyến nâng cao — hầu hết người dùng không cần. Dùng "models" cho fallback.
provider
object
Tùy chọn định tuyến nâng cao — hầu hết người dùng không cần.

Tín dụng Thông tin chính của

Truy vấn số dư tín dụng hiện tại và mức sử dụng API trọn đời.

GET/api/v1/credits
Auth
Yêu cầu mã thông báo mang (khóa API tiêu chuẩn sk-bl-...).

Yêu cầu mẫu

curl https://bazaarlink.ai/api/v1/credits \
  -H "Authorization: Bearer sk-bl-YOUR_KEY"

Phản hồi

{
  "data": {
    "total_credits": 100.00,
    "total_usage": 12.34
  }
}

Errors: 401 (khóa missing/invalid), 403 (người dùng bị treo).

Truy xuất số liệu thống kê chi tiết cho một lần hoàn thành theo ID thế hệ (từ id phản hồi chat/completions hoặc tiêu đề x-bz-gen-id phát trực tuyến).

GET/api/v1/generation?id=<generation-id>
Auth
Yêu cầu mã thông báo mang (khóa API tiêu chuẩn). Tham số truy vấn bắt buộc: id.

Yêu cầu mẫu

curl "https://bazaarlink.ai/api/v1/generation?id=gen_abc123" \
  -H "Authorization: Bearer sk-bl-YOUR_KEY"

Phản hồi

{
  "data": {
    "id": "gen_xyz...",
    "model": "openai/gpt-4.1",
    "provider": "openai",
    "created_at": "2026-04-20T10:00:00.000Z",
    "app_name": "MyApp",
    "finish_reason": "stop",
    "status": 200,
    "duration_ms": 1234,
    "first_token_ms": 234,
    "throughput": 45.6,
    "usage": {
      "prompt_tokens": 100,
      "completion_tokens": 200,
      "total_tokens": 300,
      "prompt_tokens_details": { "cached_tokens": 50 },
      "completion_tokens_details": { "reasoning_tokens": 30 },
      "cost": 0.00123
    },
    "cost_breakdown": {
      "subtotal": 0.00123,
      "cache_discount": 0.00015,
      "total": 0.00108
    }
  }
}

Lỗi: 400 (thiếu id), 401 (auth), 404 (không tìm thấy thế hệ).

API Chi tiết thế hệ

Query (định dạng phản hồi tuân theo các quy ước API thông tin khóa phổ biến của ngành).

GET/api/v1/key
Auth
Yêu cầu mã thông báo mang (khóa API tiêu chuẩn).

Phản hồi

{
  "data": {
    "label": "Production Key",
    "limit": null,
    "limit_remaining": 100.00,
    "limit_reset": null,
    "expires_at": null,
    "is_free_tier": false,
    "is_management_key": false,
    "is_provisioning_key": false,
    "usage": 12.34,
    "usage_daily": 0.12,
    "usage_weekly": 0.45,
    "usage_monthly": 1.23,
    "requests": 1234,
    "requests_daily": 10,
    "requests_weekly": 50,
    "requests_monthly": 200,
    "rate_limit": { "requests": 600, "interval": "1m", "note": "Paid-tier rate limit." }
  }
}
Note
is_free_tier = true khi số dư tín dụng < $10. Windows nằm trong UTC: hàng ngày = ngày hiện tại, hàng tuần = Thứ Hai–Chủ Nhật, hàng tháng = ngày 1–EOM. Khi khóa được đặt giới hạn chi tiêu cho mỗi khóa (thông qua thông số giới hạn trên khóa creation/update), limit / limit_remaining / limit_reset phản ánh giới hạn đó và mức sử dụng của khoảng thời gian phù hợp; nếu không thì giới hạn sẽ không có giá trị và limit_remaining sẽ quay trở lại số dư tín dụng tài khoản của bạn. hết hạn_at là thời gian hết hạn của khóa (null nếu không có). is_management_key và is_provisioning_key là bí danh của cùng một khái niệm — cả hai đều đúng đối với khóa quản lý.
BYOK
BazaarLink không cung cấp chương trình mang theo chìa khóa của riêng bạn (BYOK), vì vậy điểm cuối này không trả về bất kỳ trường byok_usage nào.

Errors: 401 (auth), 404 (thiếu người dùng - hiếm). Số dư điểm

AĐăng ký đại lý

Đăng ký tự phục vụ cho các tác nhân AI (bot, hệ thống tự động). Trả về khóa API với tín dụng dùng thử và mã thông báo xác nhận quyền sở hữu để nâng cấp tài khoản.

POST/api/v1/agents/register
Rate Limit
Không yêu cầu xác thực nhưng giới hạn IP ở 1 lần đăng ký mỗi 24 giờ. Tên tác nhân

Nội dung yêu cầu

namebắt buộc
string
A (không trống, được cắt bớt, tối đa 100 ký tự).
description
string
Mô tả tác nhân tùy chọn.
referral_code
string
Mã giới thiệu tùy chọn.

Yêu cầu mẫu

curl -X POST https://bazaarlink.ai/api/v1/agents/register \
  -H "content-type: application/json" \
  -d '{
    "name": "My Agent",
    "description": "Autonomous research bot"
  }'

Phản hồi

{
  "api_key": "sk-bl-xxxxx...",
  "credits": 0.10,
  "credits_usd": "$0.1000",
  "claim_token": "abc...xyz",
  "claim_expires": "2026-04-27T10:00:00.000Z",
  "upgrade_url": "https://bazaarlink.ai/claim?token=...",
  "referral_code": "aBcDeFgH",
  "free_model": "auto:free",
  "message": "Welcome to BazaarLink!...",
  "referral_message": "Share referral link:...",
  "base_url": "https://bazaarlink.ai/api/v1",
  "docs": "https://bazaarlink.ai/llms.txt"
}

Errors: 400 (nội dung không hợp lệ / tên bị thiếu), 429 (giới hạn tốc độ - 1/IP/24h), 500 (nội bộ).

Mã lỗi

Error Trạng thái

Các endpoint suy luận mô hình trả về một phong bì lỗi tương thích với OpenAI. Trường type có thể thay đổi hoặc bị lược bỏ; hãy dùng trạng thái HTTP và error.code cho logic chương trình thay vì phân tích thông báo.

{
  "error": {
    "message": "Insufficient credits. Please top up to continue.",
    "type": "invalid_request_error",
    "code": "insufficient_credits"
  }
}

HTTP và error.code

Before streaming, the HTTP status identifies the broad failure class. error.code is either that number or a stable string for a specific remedy. Prefer the string code when present, otherwise use the HTTP status.

Tên
Mô tả
400Yêu cầu xấuYêu cầu không hợp lệ, mảng messages rỗng, hoặc thiếu trường bắt buộc
401Không được phépKhóa API bị thiếu, không hợp lệ, hoặc bị vô hiệu hóa
402Yêu cầu thanh toánKhông đủ tín dụng tài khoản, đạt giới hạn chi tiêu theo khóa, hoặc vượt ngân sách hàng tháng/tuần
403Bị cấmTài khoản bị tạm ngưng hoặc không có quyền
404Không tìm thấyRequested model, generation, key, or other resource does not exist
409Xung độtResource is not in the required state, such as an incomplete video job
410Không còn nữaRequested model has been retired and must be replaced
413Tải trọng quá lớnBody yêu cầu vượt quá 10 MB; giảm kích thước nội dung hoặc chia yêu cầu
416Range không thỏa mãnRequested byte range is invalid for generated video content
429Quá nhiều yêu cầu Lỗi máy chủVượt giới hạn tốc độ; kiểm tra header Retry-After trước khi thử lại
500CổngLỗi nội bộ BazaarLink
502BadTất cả nhà cung cấp upstream thất bại; đã thử chuyển đổi dự phòng
503Dịch vụ không khả dụngKhông có nhà cung cấp upstream được cấu hình cho mô hình này; liên hệ admin
504Gateway Hết thời gian chờUpstream connection or stream stalled and timed out

Mã thanh toán có thể đọc được bằng máy

A 402 can represent different controls. Use these stable codes to choose the correct action.

Mô tả
budget_cap_reachedA weekly or monthly budget cap was reached; raise or reset the cap.
credit_limit_exceededA monthly-billing organization's credit line was exhausted; contact billing.
insufficient_creditsThe prepaid balance is insufficient; add credits.
spend_limit_exceededThe API key reached its daily, weekly, or monthly spend limit.

Stable error.code catalog

These string codes are emitted by public inference and media paths. Branch on the string code when present; the HTTP status remains the broad failure class.

Mô hình và điểm cuối Các lỗi tra cứu mô hình, vòng đời, giá cả, phương thức và điểm cuối của
.
HTTP
unknown_model400
invalid_model_id400
model_not_found404
model_retired410
model_endpoint_mismatch400
embedding_on_chat_endpoint400
model_not_priced400
invalid_modality_for_model400
Yêu cầu và an toàn
Các tham số, ngữ cảnh, công cụ, lược đồ và từ chối an toàn nội dung không hợp lệ.
HTTP
missing_required_field400
unsupported_param400
max_tokens_invalid400
context_too_long400
tool_use_unsupported400
malformed_tool_messages400
invalid_response_format_schema400
invalid_tools_definition400
content_moderation403
content_filter403
unknown_4xx400
Tạo và chỉnh sửa hình ảnh
Lỗi đầu vào hình ảnh, chỉnh sửa nhiều phần, đầu ra và đường dẫn hình ảnh.
HTTP
invalid_image_url400
input_images_not_supported400
invalid_content_type400
mask_not_supported400
unsupported_response_format400
missing_prompt400
missing_image400
too_many_images400
invalid_image_type400
image_too_large400
invalid_n400
pipeline_error502
no_images502
Định tuyến ngược dòng
Các lỗi kết nối, xác thực, điều chỉnh và tính khả dụng của nhà cung cấp đã được vệ sinh.
HTTP
upstream_unreachable502
upstream_auth_failed502
upstream_rate_limited429
upstream_unavailable502/503

Giới hạn tỷ lệ, ngân sách và phanh khẩn cấp

These controls can reject an otherwise valid request and require different recovery actions.

Điều khiển
HTTP
Làm thế nào để xác định nó Giới hạn tốc độ yêu cầu
429Mã số 429; sử dụng tiêu đề Retry-After và X-RateLimit-*.
Khối hình phạt giới hạn tỷ lệ429Mã số 429 và thông báo hạn chế tạm thời; sử dụng Thử lại sau. Phanh khẩn cấp
Global503Mã số 503, thông báo giới hạn chi tiêu toàn cầu và Thử lại sau 30 hoặc 300 giây.
Scoped spend brake429Numeric code 429 and a spend circuit-breaker message naming the scope.
Kiểm soát thanh toán và ngân sách402Sử dụng mã chuỗi thanh toán ổn định được liệt kê ở trên.

Compatibility note: rate-limit and emergency-brake paths currently emit numeric error.code values. Use HTTP status, Retry-After, and the documented response message.

Trạng thái tài nguyên video và phương tiện

Video validation commonly returns numeric code 400. Missing jobs return 404, retired models 410, unfinished video content 409, and invalid video byte ranges 416.

Chính sách thử lại

Retry only failures that may recover without changing the request. Honor Retry-After or use exponential backoff with jitter. Do not stack SDK and manual retries.

Thử lại với thời gian chờ
429, 502, 503, and 504. Check the original generation job before creating another after an ambiguous network failure.
Fix trước khi thử lại
400, 401, 402, 403, 404, 409, 410, 413, and 416. Fix the request, credentials, balance, permissions, resource state, or Range header first.

Xử lý lỗi

import random
import time
from openai import OpenAI, APIStatusError

client = OpenAI(
    base_url="https://bazaarlink.ai/api/v1",
    api_key="sk-bl-YOUR_API_KEY",
    max_retries=0,  # Avoid double retries; this example handles them.
)

RETRYABLE = {429, 502, 503, 504}

for attempt in range(5):
    try:
        response = client.chat.completions.create(
            model="openai/gpt-4.1",
            messages=[{"role": "user", "content": "Hello!"}],
        )
        break
    except APIStatusError as error:
        if error.status_code not in RETRYABLE or attempt == 4:
            raise
        retry_after = error.response.headers.get("Retry-After")
        delay = (
            float(retry_after)
            if retry_after
            else min(8, 0.5 * (2 ** attempt)) + random.uniform(0, 0.25)
        )
        time.sleep(delay)

Định dạng lỗi Streaming

Lỗi xảy ra trước khi stream token trả về phản hồi HTTP lỗi tiêu chuẩn với body JSON.

After a stream starts, the HTTP response is already 200. Parse each SSE data frame and treat a top-level error or choices[0].finish_reason === "error" as a failed, incomplete response.

Nếu stream thất bại giữa chừng, BazaarLink sẽ phát một sự kiện SSE cuối cùng chứa đối tượng error ở cấp cao nhất, theo sau là data: [DONE]. Các chunk được chuyển tiếp nguyên văn từ một số upstream có thể đặt lỗi trên choice (choices[0].finish_reason === "error") — hãy xử lý cả hai trường hợp.

// If the stream fails mid-flight, BazaarLink emits a final SSE event
// with a top-level "error" object, followed by data: [DONE]
data: {"error":{"message":"Upstream stream interrupted. The response is incomplete.","type":"upstream_error","code":502}}

data: [DONE]

// Chunks relayed verbatim from some upstreams may instead carry the error
// inline on the choice: choices[0].finish_reason === "error" with an
// "error" object ({ code, message }) on the choice — handle both shapes.
// Branch on error.code; error.type can vary by failure path.

Quản Lý Phiên Bản

BazaarLink cung cấp một đường dẫn API ổn định duy nhất, /api/v1 — không có phiên bản gắn theo ngày hay header phiên bản cần quản lý. API phát triển liên tục thay vì qua các bản phát hành đánh số.

Thay Đổi Không Phá Vỡ

Các thay đổi sau được triển khai mà không cần thông báo trước:

  • Endpoint mới
  • Mô hình mới được thêm vào danh mục
  • Tham số yêu cầu tùy chọn mới
  • Trường phản hồi mới
  • Schema mới với thuộc tính tùy chọn
  • Mã trạng thái/lỗi phản hồi bổ sung
Viết client theo hướng phòng thủ
Bỏ qua các trường phản hồi bạn không nhận ra, và đừng để lỗi khi gặp giá trị không xác định trong các trường dạng enum — giá trị mới được thêm khi danh mục và tính năng mở rộng.

Thay Đổi Phá Vỡ

Những thay đổi này hiếm khi xảy ra, bao gồm:

  • Xóa hoặc đổi tên endpoint, tham số, hoặc trường phản hồi
  • Thay đổi kiểu dữ liệu của một trường
  • Biến tham số tùy chọn thành bắt buộc

Khi xảy ra, một thay đổi phá vỡ chỉ áp dụng cho một endpoint cụ thể chứ không phải toàn bộ /api/v1 — không có việc nâng phiên bản đơn lẻ nào có thể làm hỏng mọi tích hợp cùng lúc. Chúng tôi chưa công bố changelog chính thức có gắn nhãn Breaking (xem "Cập Nhật Thông Tin" bên dưới) — với những gì quan trọng cho tích hợp của bạn, hãy liên hệ Support trước khi dựa vào hành vi chưa được ghi trong tài liệu.

Chính Sách Ngừng Hỗ Trợ

Sự kiện "phá vỡ" định kỳ duy nhất bạn nên lường trước: từng mô hình bị ngừng hỗ trợ khi nhà cung cấp upstream loại bỏ chúng. Kiểm tra trạng thái hiện tại của một mô hình qua GET /api/v1/models.

GET https://bazaarlink.ai/api/v1/models
Authorization: Bearer sk-bl-YOUR_API_KEY

# A model within 30 days of its deprecation date shows in the catalog
# with an "EOL" badge on the Models page. After the effective date it's
# dropped from the catalog and calls return:
# 410 { "error": { "type": "model_not_available", "code": "model_retired" } }

Cập Nhật Thông Tin

Chúng tôi chưa công bố changelog API riêng hay RSS feed. Hiện tại, hãy kiểm tra trực tiếp trang này, theo dõi trạng thái của mô hình qua GET /api/v1/models, hoặc liên hệ Support nếu bạn cần được thông báo trước cho một tích hợp quan trọng.

Support
Support
Hi! How can we help you?
Send a message and we'll get back to you soon.
Tài liệu tham chiếu API | Trò chuyện, embedding và định tuyến mô hình