BazaarLinkBazaarLink
ログイン
ドキュメントAPIリファレンスSDKリファレンスエージェント利用AIスキル

API リファレンス

BazaarLink API の概要

BazaarLink は、モデルやプロバイダーをまたいで統一された OpenAI 互換のリクエスト/レスポンス形式を提供します。一度統合すれば、アプリを書き直さずにモデルを切り替えられます。

OpenAPI 仕様

BazaarLink API 全体は OpenAPI 仕様で文書化され、YAML と JSON 形式で利用できます:

Swagger UI、Postman、または OpenAPI 対応のコードジェネレーターに読み込み、API の確認やクライアントライブラリの生成に利用できます。

リクエスト

チャット補完のリクエスト形式

チャット補完のリクエスト本文は、次のエンドポイントに送信します:

POST/api/v1/chat/completions

対応フィールドの完全な一覧は パラメータ

リクエストスキーマ
// 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>;
};

構造化出力

モデルにスキーマに一致する有効なJSONを返させます。モデル出力をプログラムで解析する信頼性の高いアプリケーション構築に不可欠です。

  • json_object基本 JSON モード。モデルは有効な JSON を返します。
  • json_schema厳密なスキーマモード。出力は指定した JSON Schema に一致する必要があります。

プラグイン

BazaarLink は plugins 配列を選択した上流ルートへ転送します。利用可否はモデルとプロバイダーに依存し、:online モデルでは web プラグインも有効になります。

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

オプションヘッダー

リクエストヘッダーでアプリケーションを識別して、使用量追跡、ダッシュボード表示、詳細な分析を有効にします。

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!" }]
  })
});

アシスタントプリフィル

メッセージ配列の最後に未完成の assistant メッセージを追加し、互換性のあるモデルルートに続きを生成するよう要求します。

仕組み
BazaarLink は最後の assistant メッセージを保持して転送します。続きの生成動作は選択したアップストリームモデルとプロバイダーが実装するため、すべてのルートで保証されるわけではありません。
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" }
  ]
});

レスポンス

BazaarLink はモデルやプロバイダーごとの完了レスポンスを、統一された OpenAI 互換形式に正規化します。

完了レスポンス形式

choices は常に配列です。ストリーミングでは delta、非ストリーミングでは message を使用し、利用可能な場合は使用量とコストも返します。

レスポンススキーマ
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[];
  };
};

終了理由

finish_reason は stop、length、tool_calls、content_filter、error などに正規化され、native_finish_reason はプロバイダーの元の値を保持します。

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

コストと統計の照会

generation ID による単一完了の詳細統計を取得(chat/completions レスポンスの id、またはストリームの x-bz-gen-id ヘッダから)。

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

チャットコンプリーション

主要エンドポイント。OpenAI Chat Completions APIと互換。

POST/api/v1/chat/completions

リクエストボディ

model必須
string
モデルID(例:"openai/gpt-4o" または "anthropic/claude-3.5-sonnet")
messages必須
Message[]
roleとcontentを持つメッセージオブジェクトの配列
stream
boolean
trueの場合、Server-Sent Eventsストリームを返す。デフォルト:false
temperature
number
サンプリング温度 0〜2。高いほどランダム。デフォルト:1
max_tokens
integer
生成する最大トークン数
max_completion_tokens
integer
max_tokensのエイリアス(OpenAI oシリーズ互換)。両方受け付けられ、指定されたほうが有効
top_p
number
Nucleusサンプリングの確率質量。デフォルト:1
top_k
integer
トークン選択をトップKに制限。0 = 無効(すべて考慮)。デフォルト:0
frequency_penalty
number
繰り返しトークンにペナルティ。範囲:[-2, 2]。デフォルト:0
presence_penalty
number
トークンの出現に基づくペナルティ。範囲:[-2, 2]。デフォルト:0
repetition_penalty
number
入力からのトークン繰り返しを削減。範囲:(0, 2]。デフォルト:1
min_p
number
トップトークンに対する最小確率。範囲:[0, 1]。デフォルト:0
top_a
number
最高確率トークンに基づく動的top-P。範囲:[0, 1]。デフォルト:0
seed
integer
決定論的サンプリング用の整数シード。すべてのモデルで保証されるわけではない
n
integer
生成するコンプリーション数。デフォルト:1
user
string
モニタリングと不正検出用のエンドユーザー識別子。課金には影響なし。OpenAI系モデルのみ対応 — 下記の注記を参照。
stop
string | string[]
停止シーケンス — 検出時に生成が停止
logit_bias
object
サンプリング前に追加されるトークンIDからバイアス値[-100, 100]へのマップ。OpenAI系モデルのみ対応 — 下記の注記を参照。
logprobs
boolean
各出力トークンのログ確率を返す。OpenAI系モデルのみ対応 — 下記の注記を参照。
top_logprobs
integer
位置ごとに返す最も可能性の高いトークン数(logprobs: trueが必要)。範囲:0〜20。OpenAI系モデルのみ対応 — 下記の注記を参照。
tools
Tool[]
モデルが呼び出せるツール(関数)のリスト
tool_choice
string | object
ツール使用の制御:"auto"、"none"、または特定のツール
parallel_tool_calls
boolean
ツール提供時の並列ファンクションコールを有効化。デフォルト:true。OpenAI系モデルのみ対応 — 下記の注記を参照。
response_format
object
構造化JSON出力を強制。構造化出力セクションを参照
structured_outputs
boolean
対応プロバイダーで厳密なJSONスキーマ準拠の出力をリクエスト。そのまま転送
reasoning
object
プロバイダー固有のreasoning/thinking設定。そのまま転送
reasoning_effort
string
OpenAI oシリーズ形式のreasoning強度:"low"、"medium"、または"high"。そのまま転送
transforms
string[]
適用するメッセージ変換(例:["middle-out"])。省略すると≤8kコンテキストモデルに自動適用
models
string[]
フォールバックモデルリスト — BazaarLinkはプライマリが失敗した場合、順番に試行
route
string
高度なルーティング互換フィールド——ほとんどのユーザーには不要です。フォールバックには "models" を使用してください。
provider
object
高度なルーティング設定——ほとんどのユーザーには不要です。
user、logprobs、top_logprobs、logit_bias、parallel_tool_callsはOpenAI系モデルにのみ届きます
解決されたモデルがOpenAI自身のものと認識されない場合、この5つのパラメータはアップストリームリクエストから除去されます — anthropic/claude-*、google/gemini-*、その他のOpenAI以外のターゲットに送信すると、エラーではなくパラメータが黙って無視された200が返されます。これらのいずれかを設定していて効果が現れない場合は、対象モデルがOpenAIのものかどうかを確認してください。

リクエストスキーマ(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>;
};

リクエスト例

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
  }'

レスポンス

{
  "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
    }
  }
}

レスポンススキーマ(TypeScript)

BazaarLinkが正規化するのはmodelとproviderフィールドの削除の2点のみで、それ以外のアップストリームレスポンスはそのまま転送されます。native_finish_reason、system_fingerprint、reasoningなどのフィールドは、該当するアップストリームプロバイダーがそれを設定している場合にのみ存在します — すべてのモデルで存在することを前提にしないでください。usage.costは例外で、常にBazaarLink自身が確定・請求した金額であり、アップストリームから転送された値ではありません。

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 };
};

画像生成

DALL·EやGPT-4oなどのモデルを使用してテキストプロンプトから画像を生成。チャットコンプリーションエンドポイントの`modalities`パラメータを使用して画像出力をリクエスト。 画像編集(既存の画像を修正)は POST /v1/images/edits を使用します —— OpenAI images.edit 互換で、multipart/form-data でソース画像を送信します。編集対応モデルは modality が text+image->image です(例: qwen/qwen-image-edit)。純粋な生成モデルは text->image です —— 各モデルの modality は GET /v1/models で確認してください。

Response format

/api/v1/images/generations はデフォルトで OpenAI 互換の同期 JSON を返します(2026-07-25 以降)——client.images.generate() はラッパーなしで動作します。stream: true を渡すと SSE イベントストリームに切り替わり、生成時間の長いモデルで進捗を受け取れます。

A. /v1/chat/completions(ネイティブ、推奨)

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):content 配列に image_url パートを含めます。データURIまたは https 画像URL(http:// は拒否されます)をサポートし、最大8枚、データURIあたり約10MBです。画像を含むメッセージには text パート(編集指示)も必要です。一部のモデルは image_config(例:{"strength": 0.7}、0〜1 — 低いほど元画像に近い)を追加でサポートし、そのままアップストリームに渡されます。

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
  }'

画像編集(OpenAI互換)

POST/api/v1/images/edits

OpenAI SDK の client.images.edit() がそのまま動作します(multipart アップロード、data: [{ url }] を返す同期JSONレスポンス)。制限は image-to-image と同じ:最大8枚、各10MB。mask と response_format=b64_json は未対応です。

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(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"
  }'
model必須
string
モデル ID。例:google/gemini-2.5-flash-image
prompt必須
string
テキストプロンプト
size
string
出力サイズ(自動マッピング)
n
integer
生成枚数(デフォルト 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: {}

対応する画像モデル

Model IDModalityi2i (edits)

動画生成

非同期の 3 ステップフロー(submit → poll → content)。動画生成には 30 秒〜5 分かかり、chat-completions の同期リクエスト/レスポンス方式には適合しません — そのため BazaarLink は動画を専用の /api/v1/videos パスに分離し、job-id パターンを採用しています:submit で vjob_* ID を取得 → ステータスを poll → 完了後に bytes を fetch。video model を /chat/completions や /images/generations 経由で呼び出すと 400(code: wrong_endpoint_for_video)が返ります。費用は completed 時に実際の usage.cost で精算されます。

動画タスクの種類

1 つのエンドポイントで複数のタスクを扱います。実際にどのタスクが実行されるかは送信するフィールドで決まります —— 同一モデルで画像から動画、キーフレーム、継続生成が可能です。すべてのモデルがすべてのタスクに対応するわけではなく、非対応の場合は 400 を返します。

テキストから動画
prompt
テキストプロンプトだけから生成します。入力メディアは不要です。
画像から動画
frame_images: [ 先頭フレーム ]
画像そのものが映像になります。先頭フレームとしてアニメーション化され、元画像に忠実です。例:猫の写真 → 同じ猫が同じシーンで首を振る。
キーフレーム(先頭+末尾)
frame_images: [ 先頭, 末尾 ]
開始画像と終了画像を与えると、モデルがその間の動きを補間します。
継続生成
input_video
既存のクリップを延長します。指定する duration はソース動画の長さより大きくする必要があります。
参照から動画
input_references: [ 画像 ]
画像はフレームではなく「参照」です。モデルは被写体/スタイルを保ちつつ、まったく新しいシーンを生成します。例:猫の写真 +「森の中で踊る」→ 猫の見た目は保たれるがシーンと動きは新しい映像(参照は 1〜9 枚)。画像から動画との違い:i2v は元画像そのものに忠実、r2v は被写体を新しい映像に作り直します。
動画編集
input_video + prompt
既存の動画を編集します——シーン、スタイル、動きを変更。入力動画の秒数 + 出力秒数で課金されます。

1. ジョブを送信(即座に vjob_xxx を返す)

POST/api/v1/videos
model必須
string
モデル ID。例:alibaba/wan2.7-t2v
prompt必須
string
テキストプロンプト
duration
integer
秒数(モデルの制限による)
resolution
string
解像度:480p / 720p / 1080p など
generate_audio
boolean
音声トラックを生成するか(true/false)
frame_images
array
先頭/末尾フレーム画像(画像から動画、キーフレーム)。オブジェクト { type: "image_url", image_url: { url }, frame_type: "first_frame" | "last_frame" } または純粋な URL 文字列。
input_references
array
参照から動画で使う参照画像 —— 被写体/スタイルの誘導であり、厳密なフレームではありません。
input_video
string|object
継続生成と動画編集のソース動画 URL。アップストリームから公開でアクセス可能である必要があります。
aspect_ratio
string
アスペクト比。例:16:9 または 9:16。入力画像が比率を決める場合は無視されます。
watermark
boolean
ウォーターマークを追加します。デフォルトは false。
callback_url
string
ジョブが終了状態に達したときに呼び出される webhook URL——HTTPS のみ、SSRF チェックあり。v1 に署名はなく、ヒントとして扱い 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
Submit 時に最悪ケース × duration × multiplier で仮押さえし、completed 時にアップストリームが返す usage.cost で差額を精算/返金します。

2. ステータスをポーリング

GET/api/v1/videos/{id}
curl -H "Authorization: Bearer $BL_API_KEY" \
  https://bazaarlink.ai/api/v1/videos/vjob_xxx
Note
各 GET は 8 秒以上の間隔を空けないと実際にアップストリームへ到達しません(レートリミット回避)
Note
status=failed の場合、reserve 金額は全額ユーザーに返金されます。

3. 動画コンテンツを取得 (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

知っておくべきこと

  • 許可される解像度はモデルごとに異なります —— 非対応の値を送ると、対応値を列挙した 400 が返ります。
  • 入力の画像/動画は公開 URL からアクセス可能である必要があります。ホットリンク保護されたホスト(一部の wiki など)は失敗します。
  • 入力メディアはアップストリームのコンテンツモデレーションを通過し、まれに拒否されることがあります。
  • 継続生成では、指定する duration がソース動画長を超える必要があります。
  • 出力アスペクト比は入力画像に従います —— 正方形の画像は正方形の動画になります。
  • 動画編集は入力動画の秒数と生成された出力の秒数で課金されます。
  • 編集/継続生成の input_video は公開 URL である必要があります。ここで生成した動画は API キーの背後で配信されるためアップストリームが取得できません —— ソース動画は公開アクセス可能な URL にホストしてください。
  • Webhook には署名がありません——実行前に GET /videos/{id} でステータスと金額を確認してください。そこでの unsigned_urls は絶対 URL です(ポーリング応答の相対パスとは異なります)。

対応する動画モデル

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

動画入力

動画入力に対応するモデルに動画ファイルを送信し、分析、キャプション生成、シーンやイベントに関する質問への回答をさせます。直接URLまたはbase64データURIが使えます — URLは公開アクセス可能な動画に効率的、base64はローカルファイルや非公開動画向けです。

対応フォーマット

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?"},
        ],
    }],
)

完全なAPIリファレンス →

PDF入力

PDFをネイティブサポートするモデル(Claude、Geminiなど)に、メッセージで直接PDF文書を送信できます。BazaarLinkはファイルをそのままモデルに転送します — 通常のinput tokensとして課金、追加料金や追加処理はありません。

対応フォーマット

  • PDFドキュメント(テキスト、画像、表、スキャン)
  • Base64エンコードされたデータURL(`data:application/pdf;base64,...`)
  • 複数ページドキュメント
  • パスワードなしPDFのみ
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

ステートレスなマルチターン会話、ツールコール、マルチモーダル入力に対応するOpenAI Responses API互換エンドポイント。OpenAI Python SDK ≥ 1.xのclient.responses.create()を使用するエージェントやフレームワークに最適。

POST/api/v1/responses
Note
Chat Completionsと同じ認証とモデルルーティングを使用。

リクエストボディ

model必須
string
モデルID(例:"openai/gpt-4o" または "anthropic/claude-3.5-sonnet")
input必須
string | Item[]
ユーザー入力 — プレーンな文字列(単一メッセージ)またはマルチターン/マルチモーダル会話用の入力アイテムの配列。
instructions
string
システムレベルの指示、システムメッセージに相当。リクエストごとに再送信が必要。
stream
boolean
trueの場合、Responses API SSEストリームイベントを返す。イベントタイプ:response.created、response.output_text.delta、response.completed。
max_output_tokens
integer
生成する最大出力トークン数(oシリーズモデルの推論トークンを含む)。
temperature
number
サンプリング温度 0〜2。高いほどランダム。デフォルト:1
top_p
number
Nucleusサンプリングの確率質量。デフォルト:1
tools
Tool[]
ツール(関数)定義 — Chat Completions と同じ JSON Schema 形式(フラットな Responses 形式とネスト形式の両方を受け付けます)。OpenAI 独自の組み込み型ホスト済みツール(web_search_preview、file_search、computer_use_preview)は非対応です。Web 検索は plugins: [{id:"web"}] で利用できます——一部のモデルルートのみ対応。
tool_choice
string | object
ツール使用の制御:"auto"、"none"、または特定のツール
parallel_tool_calls
boolean
ツール提供時の並列ファンクションコールを有効化。デフォルト:true。OpenAI系モデルのみ対応 — 下記の注記を参照。
response_format
object
構造化JSON出力を強制。構造化出力セクションを参照
models
string[]
フォールバックモデルリスト — BazaarLinkはプライマリが失敗した場合、順番に試行
transforms
string[]
適用するメッセージ変換(例:["middle-out"])。省略すると≤8kコンテキストモデルに自動適用
previous_response_id
string
このエンドポイントはステートレスです——非 null の値を渡すと即座に 400(invalid_prompt)を返します。受け付けられて無視されることはありません。代わりにステートレスモードを使用してください:input 配列に完全な会話履歴を渡します。
provider
object
高度なルーティング設定——ほとんどのユーザーには不要です。

リクエストスキーマ(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" };

リクエスト例

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?"
  }'

レスポンス形式

// 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" };

Chat Completionsからの移行

messagesをinput(文字列または配列)に置き換え、システムロールメッセージの代わりにinstructionsを使用し、choices[0].message.contentの代わりにoutput[0].content[0].textを読み取ります。

# 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

制限事項

  • previous_response_id または store: true を渡すと 400(エラーコード invalid_prompt)を返します——受け付けられて無視されるわけではありません。常にステートレスモードを使用し、input 配列に完全な会話履歴を渡してください。
  • OpenAI 独自の組み込み型ホスト済みツール(web_search_preview、file_search、computer_use_preview)は非対応です。Web 検索は plugins: [{id:"web"}] で利用できます——一部のモデルルートのみ対応。
  • background: true は受け付けられますが無視されます——すべてのリクエストは完了まで同期的に実行されます。

Messages(Anthropic 互換)

Anthropic Claude SDK 互換の Messages API。Anthropic の公式 API と同じ方法で使用でき、base URL と auth header を変更するだけです。

POST/api/v1/messages
Note
Bearer token または x-api-key header をサポート(Anthropic SDK 互換)。最大ボディサイズ:10 MB。

リクエストボディ

model必須
string
モデルID(例:"openai/gpt-4o" または "anthropic/claude-3.5-sonnet")
max_tokens必須
integer
生成する最大トークン数(正の整数)。
messages必須
Message[]
会話メッセージの配列(空不可)。
system
string
任意の system prompt。
stream
boolean
trueの場合、Server-Sent Eventsストリームを返す。デフォルト:false
temperature
number
サンプリング温度 0〜2。高いほどランダム。デフォルト:1
top_p
number
Nucleusサンプリングの確率質量。デフォルト:1
top_k
integer
トークン選択をトップKに制限。0 = 無効(すべて考慮)。デフォルト:0
stop_sequences
string[]
カスタム停止シーケンス文字列の配列。
tools
Tool[]
モデルが呼び出せるツール(関数)のリスト
tool_choice
string | object
ツール使用の制御:"auto"、"none"、または特定のツール

リクエスト例

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)

レスポンス

{
  "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
  }
}

エラー:400(検証失敗)、402(クレジット不足)、429(rate limit)、502(アップストリームエラー/キー欠如)、503(サーバー再起動中)。

モデル

料金と機能情報を含む、利用可能な全モデルの一覧を取得。 このエンドポイントには認証は不要です。

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"

レスポンス

{
  "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
  }[];
};

入力長に応じた段階制価格

一部のモデルは、プロンプトが token 閾値を超えると価格表全体が切り替わります(閾値を超えた分だけではありません)。閾値は厳密な不等式です:入力 token 数がちょうど N の場合は N 以下の階層が適用され、N を超えた場合にのみ上位の階層が適用されます。

pricing_tiers は pricing と同階層のフィールドで、基本価格を超える上書き階層があるモデルにのみ存在します。項目は above_prompt_tokens の昇順で並び、prompt/completion は token あたりの USD 価格です(pricing.prompt/pricing.completion と同じ単位)。pricing.prompt と pricing.completion は常に基本(最低)階層です。

ほとんどのモデルには階層がありません — その場合、レスポンスに pricing_tiers キー自体が存在しません。

{
  "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"
    }
  ]
}

利用可能なモデル (257)

BazaarLinkで現在利用可能なモデルです。データベースから動的に読み込まれます:

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

すべてのモデルは モデルページで閲覧できます。

ストリーミング

設定: stream: true でServer-Sent Events(SSE)ストリームを受信します。各イベントにはレスポンスのチャンクが含まれます。

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)

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]
ストリーミングでの使用量
ストリーミング時、使用量データは[DONE]メッセージの前の最終チャンクに、空のdeltaとfinish_reason: "stop"を持つchoices配列とともに返されます。

Keep-alive と最終チャンク

ストリームにはキープアライブとしてSSEコメント行(コロンで始まる)やハートビートイベントが含まれることがあります — 生ストリームをそのままJSON.parseせず、data: 以外の行はスキップしてください。最後のdataチャンクは data: [DONE] の前に usage(トークン数とコスト)を含みます。成功したレスポンスには X-Request-Id ヘッダーが含まれます — 問題を報告する際に添えてください。

: 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]

ストリームのキャンセル

クライアント接続を閉じることでストリーミングリクエストをキャンセルできます — 例えば AbortController.abort() を呼ぶ、または stream オブジェクトを閉じるなど。BazaarLink はキャンセルを受け取り次第、以降のチャンク転送を停止し、プロバイダーへのアウトバウンドリクエストを中止します。

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();
中断されたストリームには課金されません
最後の usage チャンクが届く前にストリームが終了した場合 — クライアント側でのキャンセルを含む — そのリクエストには信頼できるトークン数の根拠がないため、BazaarLink は予約分を全額返金します。キャンセル前にすでにクライアントへ届いたコンテンツについて課金されることはありません。
プロバイダー側の即時停止は保証されません
接続を閉じると BazaarLink は以降のトークンの転送と課金を直ちに停止しますが、接続が切れた瞬間にアップストリームのプロバイダーが自社サーバー上で生成を停止するかどうかはそのプロバイダー次第です — 切断後もしばらく処理を続けるプロバイダーもあります。

ストリーム途中でのエラー

エラーフレームには choices フィールドがありません
ストリーミング開始後に失敗が発生した場合(例:アップストリーム接続の切断)、通常の {choices:[...]} ではなく {error:{message,type,code}} 形式の SSE データフレームが返されます — ヘッダーはすでに送信済みのため、HTTP ステータスの変化はありません。choices[0].delta を読む前に error キーの有無を確認してください。課金はそれまでにストリーミングされたトークン分のみです(部分課金が適用されます)。
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)は意味を捉えた数値表現で、テキストをベクトル(数値の配列)に変換し、さまざまな機械学習タスクに利用できます。BazaarLinkはOpenAI Embeddings API互換の統一エンドポイントを提供し、単一のインターフェースで複数プロバイダーのエンベディングモデルを呼び出せます。

エンベディングとは?

エンベディングはテキストを高次元ベクトルに変換し、意味的に近いテキストはベクトル空間上でも近い距離に位置します——例えば「猫」と「子猫」のエンベディングは似ていますが、「猫」と「飛行機」は大きく離れています。このベクトル表現により、機械はテキスト間の関係を理解できるようになり、多くのAIアプリケーションの基盤となっています。

一般的なユースケース

ユースケース
説明
RAG(検索拡張生成)回答を生成する前にナレッジベースから関連コンテキストを検索するシステムを構築——エンベディングはLLMのコンテキストに含めるべき最も関連性の高いドキュメントを見つけます。
セマンティック検索ドキュメントとクエリをエンベディングに変換し、ベクトル類似度で最も関連性の高いドキュメントを見つけます——キーワード一致だけでなく意味を理解するため、キーワード検索より優れた結果が得られます。
レコメンデーションシステム商品、記事、動画などのアイテムとユーザーの好みのエンベディングを生成し、類似アイテムを推薦——共通のキーワードがなくても、ベクトル比較で意味的に関連するアイテムを見つけられます。
クラスタリングと分類エンベディングのパターンを分析して、類似したドキュメントをグループ化または分類——エンベディングが似ているドキュメントは通常、同じトピックやカテゴリに属します。
重複検出エンベディングの類似度を比較して重複または近似重複コンテンツを検出——言い換えられたコンテンツでも検出できます。
異常検知データセットの典型的なパターンから大きく外れたエンベディングを特定し、異常や外れ値のコンテンツを検出します。
POST/api/v1/embeddings
Note
すべてのアップストリームプロバイダーがエンベディングをサポートしているわけではありません。設定されたプロバイダーがリクエストされたモデルをサポートしていない場合、BazaarLinkは自動的に次の利用可能なプロバイダーにフェイルオーバーします。

パラメータ

model必須
string
使用するエンベディングモデル。例:"openai/text-embedding-3-small"。
input必須
string | string[] | ContentItem[]
エンベディング対象のテキスト — 単一の文字列、1回のバッチ呼び出し用の文字列配列、または(対応モデルの場合)text パートと image_url パートを混在させた {content:[...]} 形式の配列。
dimensions
integer
リクエストする出力ベクトルの次元数。可変次元をサポートするモデル(例:OpenAI text-embedding-3 系)でのみ有効です。アップストリームプロバイダーにそのまま転送され、対応していないモデルでは無視されます。
encoding_format
string
リクエストするエンベディングのエンコード形式。例:"float" または "base64"。アップストリームプロバイダーにそのまま転送されます — 対応状況はモデルによって異なります。
provider
object
プロバイダールーティング設定 — order、allow_fallbacks、data_collection、その他 Provider Selection で説明されているフィールド。

基本リクエスト

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

バッチ処理

文字列の配列を送信すると、1回のリクエストで複数のテキストをまとめてエンベディングできます — テキストごとに呼び出すより安く速くなります。

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

マルチモーダル入力(画像+テキスト)

画像入力に対応したモデル(output_modalities に "embeddings"、inputModalities に "image" を含む)は、{content:[{type:"text",...}, {type:"image_url",...}]} 形式の入力アイテムを受け付け、画像単体、またはテキストと組み合わせてエンベディングできます。

モデル依存
画像入力を受け付けるのは一部のエンベディングモデルのみです。image_url コンテンツを送信する前に、Models ページでそのモデルの対応モダリティを確認してください。テキスト専用モデルはこの形式を拒否します。
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)}")

プロバイダールーティング

チャット補完と同様に、どのアップストリームがエンベディングリクエストを処理するかを制御できます — フィールドの完全なリファレンスは Provider Selection を参照してください。

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

エンベディングモデルの探し方

エンベディング専用のモデル一覧エンドポイントはありません。GET /api/v1/models を呼び出し、output_modalities に "embeddings" を含むエントリをクライアント側でフィルタするか、Models ページを参照してください。

制限事項

  • ストリーミング非対応 — チャット補完と異なり、エンベディングは常に完全なレスポンスとして返されます。
  • 各モデルには最大入力長があります。それを超えるテキストはアップストリーム側で切り詰められるか拒否されます。
  • 同一の入力に対するエンベディングは決定論的です — temperature やランダム性はありません。

ベストプラクティス

  • 速度・品質・コストのトレードオフに応じてモデルを選びましょう — 小型モデル(例:qwen/qwen3-embedding-4b)は安価で高速、大型モデル(例:openai/text-embedding-3-large)は一般的により高精度にエンベディングします。
  • テキストごとに呼び出すのではなく、複数のテキストを1回のリクエストにまとめましょう — ラウンドトリップが減り、オーバーヘッドも下がります。
  • 結果をキャッシュしましょう — 同じ入力のエンベディングは変化しないため、再生成せず保存しておくべきです。
  • 比較にはユークリッド距離ではなくコサイン類似度を使いましょう — スケール不変で高次元ベクトルに向いています。
  • 各モデルのコンテキスト長に注意しましょう — 長い文書はエンベディング前にチャンク分割が必要な場合があります。

パラメータ

サンプリングパラメータはトークン生成プロセスを制御します。BazaarLinkはサポートされているパラメータをアップストリームプロバイダーに渡し、サポートされていないパラメータは黙って無視されます。

サンプリングパラメータ

純粋なパススルー — ローカルデフォルトなし
これらは送信された内容そのままアップストリームプロバイダーに転送されます — BazaarLinkがデフォルト値を注入したり強制することはありません。以下の「デフォルト」は、フィールドが省略された場合のプロバイダー自身の挙動を説明するものであり、BazaarLinkによる保証ではありません。
temperature
number
サンプリング温度 0〜2。高いほどランダム。デフォルト:1
top_p
number
Nucleusサンプリングの確率質量。デフォルト:1
top_k
integer
トークン選択をトップKに制限。0 = 無効(すべて考慮)。デフォルト:0
frequency_penalty
number
繰り返しトークンにペナルティ。範囲:[-2, 2]。デフォルト:0
presence_penalty
number
トークンの出現に基づくペナルティ。範囲:[-2, 2]。デフォルト:0
repetition_penalty
number
入力からのトークン繰り返しを削減。範囲:(0, 2]。デフォルト:1
min_p
number
トップトークンに対する最小確率。範囲:[0, 1]。デフォルト:0
top_a
number
最高確率トークンに基づく動的top-P。範囲:[0, 1]。デフォルト:0
seed
integer
決定論的サンプリング用の整数シード。すべてのモデルで保証されるわけではない
max_tokens
integer
生成する最大トークン数
n
integer
生成するコンプリーション数。デフォルト:1
logit_bias
object
サンプリング前に追加されるトークンIDからバイアス値[-100, 100]へのマップ。OpenAI系モデルのみ対応 — 下記の注記を参照。
logprobs
boolean
各出力トークンのログ確率を返す。OpenAI系モデルのみ対応 — 下記の注記を参照。
top_logprobs
integer
位置ごとに返す最も可能性の高いトークン数(logprobs: trueが必要)。範囲:0〜20。OpenAI系モデルのみ対応 — 下記の注記を参照。
response_format
object
構造化JSON出力を強制。構造化出力セクションを参照
structured_outputs
boolean
対応プロバイダーで厳密なJSONスキーマ準拠の出力をリクエスト。そのまま転送
reasoning
object
プロバイダー固有のreasoning/thinking設定。そのまま転送
reasoning_effort
string
OpenAI oシリーズ形式のreasoning強度:"low"、"medium"、または"high"。そのまま転送
stop
string | string[]
停止シーケンス — 検出時に生成が停止
tools
Tool[]
モデルが呼び出せるツール(関数)のリスト
tool_choice
string | object
ツール使用の制御:"auto"、"none"、または特定のツール
parallel_tool_calls
boolean
ツール提供時の並列ファンクションコールを有効化。デフォルト:true。OpenAI系モデルのみ対応 — 下記の注記を参照。

BazaarLink専用パラメータ

transforms
string[]
適用するメッセージ変換(例:["middle-out"])。省略すると≤8kコンテキストモデルに自動適用
models
string[]
フォールバックモデルリスト — BazaarLinkはプライマリが失敗した場合、順番に試行
route
string
高度なルーティング互換フィールド——ほとんどのユーザーには不要です。フォールバックには "models" を使用してください。
provider
object
高度なルーティング設定——ほとんどのユーザーには不要です。

クレジット

現在のクレジット残高と累計 API 使用量を照会。

GET/api/v1/credits
Auth
Bearer token(標準 API キー sk-bl-...)が必要です。

リクエスト例

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

レスポンス

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

エラー:401(キー無効/欠落)、403(停止中のユーザー)。

生成詳細

generation ID による単一完了の詳細統計を取得(chat/completions レスポンスの id、またはストリームの x-bz-gen-id ヘッダから)。

GET/api/v1/generation?id=<generation-id>
Auth
Bearer token(標準 API キー)が必要です。必須 query パラメータ:id。

リクエスト例

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

レスポンス

{
  "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
    }
  }
}

エラー:400(id 欠落)、401(auth)、404(generation が見つかりません)。

API キー情報

現在の API キーの rate limit 階層と集計使用量カウンタを照会(レスポンス形式は業界標準のキー情報 API に準拠)。

GET/api/v1/key
Auth
Bearer token(標準 API キー)が必要です。

レスポンス

{
  "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
クレジット残高が $10 未満の場合、is_free_tier は true。ウィンドウは UTC:daily = 当日、weekly = 月曜〜日曜、monthly = 1 日〜月末。個別の利用上限が設定されている場合(キー作成・更新時の limit パラメータ)、limit / limit_remaining / limit_reset はその上限と該当期間の使用量を反映します。未設定の場合 limit は null、limit_remaining はアカウントのクレジット残高にフォールバックします。expires_at はキーの有効期限(未設定なら null)。is_management_key と is_provisioning_key は同じ概念の別名で、管理キーの場合どちらも true になります。
BYOK
BazaarLink は BYOK(自前キー持ち込み)プログラムを提供していないため、このエンドポイントは byok_usage 関連フィールドを返しません。

エラー:401(auth)、404(ユーザーなし — まれ)。

エージェント登録

AI エージェント(ボット、自律システム)のセルフサービス登録。試用クレジット付き API キーとアカウントアップグレード用の claim token を返します。

POST/api/v1/agents/register
Rate Limit
認証不要ですが、IP ごとに 24 時間に 1 回の登録に制限されています。

リクエストボディ

name必須
string
エージェント名(空不可、trim 後最大 100 文字)。
description
string
任意のエージェント説明。
referral_code
string
任意の紹介コード。

リクエスト例

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

レスポンス

{
  "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"
}

エラー:400(body 無効/name 欠落)、429(rate limit — 1/IP/24h)、500(内部エラー)。

エラーコード

Error response format

Model inference endpoints return an OpenAI-compatible error envelope. The type field can vary or be omitted; use the HTTP status and error.code instead of parsing the message.

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

HTTP status and 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.

コード
名前
説明
400Bad Request不正なリクエスト、空のmessages配列、または必須フィールドの欠落
401UnauthorizedAPIキーが欠落、無効、または無効化されている
402Payment Requiredアカウントクレジット不足、キーごとの支出制限到達、または月次/週次予算上限超過
403Forbiddenアカウントが停止されているか、権限がない
404Not FoundRequested model, generation, key, or other resource does not exist
409ConflictResource is not in the required state, such as an incomplete video job
410GoneRequested model has been retired and must be replaced
413Payload Too Largeリクエストボディが10MBを超えています。コンテンツサイズを縮小するかリクエストを分割してください
416Range Not SatisfiableRequested byte range is invalid for generated video content
429Too Many Requestsレート制限超過。リトライ前にRetry-Afterヘッダーを確認してください
500Server ErrorBazaarLink内部エラー
502Bad Gatewayすべてのアップストリームプロバイダーが失敗。フェイルオーバーが試行されました
503Service Unavailableこのモデルにアップストリームプロバイダーが設定されていません。管理者に連絡してください
504Gateway TimeoutUpstream connection or stream stalled and timed out

Machine-readable billing codes

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

コード
説明
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.

Model and endpoint
Model lookup, lifecycle, pricing, modality, and endpoint compatibility errors.
コード
HTTP status
unknown_model400
invalid_model_id400
model_not_found404
model_retired410
model_endpoint_mismatch400
embedding_on_chat_endpoint400
model_not_priced400
invalid_modality_for_model400
Request and safety
Invalid parameters, context, tools, schemas, and content-safety refusals.
コード
HTTP status
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
Image generation and editing
Image input, multipart editing, output, and image-pipeline errors.
コード
HTTP status
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
Upstream routing
Sanitized provider connectivity, authentication, throttling, and availability errors.
コード
HTTP status
upstream_unreachable502
upstream_auth_failed502
upstream_rate_limited429
upstream_unavailable502/503

Rate limits, budgets, and emergency brakes

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

Control
HTTP status
How to identify it
Request rate limit429Numeric code 429; use Retry-After and X-RateLimit-* headers.
Rate-limit penalty block429Numeric code 429 and a temporary restriction message; use Retry-After.
Global spend emergency brake503Numeric code 503, global spend-limit message, and Retry-After of 30 or 300 seconds.
Scoped spend brake429Numeric code 429 and a spend circuit-breaker message naming the scope.
Billing and budget controls402Use the stable billing string codes listed above.

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

Video and media resource state

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

Retry policy

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.

Retry with backoff
429, 502, 503, and 504. Check the original generation job before creating another after an ambiguous network failure.
Fix before retrying
400, 401, 402, 403, 404, 409, 410, 413, and 416. Fix the request, credentials, balance, permissions, resource state, or Range header first.

エラー処理

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)

ストリーミングエラー形式

トークンがストリーミングされる前に発生したエラーは、JSONボディを持つ標準のHTTPエラーレスポンスを返します。

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.

ストリームが途中で失敗した場合、BazaarLink はトップレベルの error オブジェクトを含む最後のSSEイベントを送信し、その後に data: [DONE] が続きます。一部のアップストリームからそのまま転送されるチャンクでは、エラーが choice 側に載ることがあります(choices[0].finish_reason === "error")— 両方に対応してください。

// 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.

バージョニング

BazaarLink は単一の安定した API パス /api/v1 を公開しています — 日付固定のバージョンやバージョンヘッダーを管理する必要はありません。API は番号付きリリースではなく、継続的に進化します。

非破壊的変更

以下は事前通知なしにリリースされます:

  • 新しいエンドポイント
  • カタログへの新しいモデルの追加
  • 新しい任意のリクエストパラメータ
  • 新しいレスポンスフィールド
  • 任意プロパティを持つ新しいスキーマ
  • 追加のレスポンスステータス/エラーコード
クライアントは防御的に実装してください
認識できないレスポンスフィールドは無視し、enum 的なフィールドの未知の値でも失敗しないようにしてください — カタログや機能の拡大に伴い新しい値が追加されます。

破壊的変更

これらは稀で、以下を含みます:

  • エンドポイント/パラメータ/レスポンスフィールドの削除や名称変更
  • フィールドの型変更
  • 任意パラメータの必須化

発生した場合も、破壊的変更は /api/v1 全体ではなく特定のエンドポイントに限定されます — すべての連携を一度に壊すような単一のバージョン切り替えはありません。Breaking タグ付きの正式な changelog はまだ公開していません(下記「最新情報の入手」参照)— 連携にとって重要な部分については、ドキュメント化されていない挙動に依存する前に Support までご連絡ください。

廃止ポリシー

想定しておくべき唯一の定常的な「破壊的」イベントは、アップストリームプロバイダーが廃止した個々のモデルが引退することです。モデルの現在のステータスは 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" } }

最新情報の入手

専用の API changelog や RSS フィードはまだ公開していません。現時点では、このページを直接ご確認いただくか、GET /api/v1/models でモデルのステータスを確認するか、重要な連携で事前通知が必要な場合は Support までご連絡ください。

サポート
サポート
こんにちは。どのようなご用件でしょうか?
メッセージをお送りください。担当者より返信します。