BeeRoute logoBeeRoute.

Home / Docs / OpenAI Chat Format (Chat Completions)

OpenAI Chat Format (Chat Completions)

Official docs: OpenAI Chat Completions API reference

๐Ÿ“ Introduction

The Chat Completions endpoint takes a list of conversation messages and returns the model's next reply. It is the most widely supported OpenAI-compatible format: every text model on BeeRoute (GPT, Claude, Gemini, DeepSeek, Kimi, GLM, Qwen, and more) can be called through it, and the gateway handles format conversion automatically.

OpenAI recommends the Responses API for new projects; see OpenAI Response Format (Responses). Chat Completions remains supported by OpenAI.

Quick facts

  • Base URL: https://beeroute.ai/v1
  • Endpoint: POST https://beeroute.ai/v1/chat/completions
  • Authentication: request header Authorization: Bearer $API_KEY
  • API keys: create one on the console API Keys page; keys look like sk-xxx
  • Models and prices: https://beeroute.ai/modellist/, or call GET https://beeroute.ai/v1/models to list the models available to your key

The curl examples below read the key from an environment variable. Run this first:

export API_KEY=sk-xxx

๐Ÿ’ก Request Examples

Basic Text Chat โœ…

curl https://beeroute.ai/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $API_KEY" \
  -d '{
    "model": "gpt-5.6-terra",
    "messages": [
      {"role": "system", "content": "You are a helpful assistant."},
      {"role": "user", "content": "Hello! Please introduce yourself in one sentence."}
    ]
  }'

Response example:

{
  "id": "chatcmpl-Dk2v8Qx3NcR7uYbT5mWfL0aJsPe9H",
  "object": "chat.completion",
  "created": 1795740000,
  "model": "gpt-5.6-terra",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Hello! I am an AI assistant that can help you answer questions, write, translate, and code.",
        "refusal": null,
        "annotations": []
      },
      "logprobs": null,
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 28,
    "completion_tokens": 86,
    "total_tokens": 114,
    "prompt_tokens_details": {"cached_tokens": 0, "audio_tokens": 0},
    "completion_tokens_details": {"reasoning_tokens": 64, "audio_tokens": 0, "accepted_prediction_tokens": 0, "rejected_prediction_tokens": 0}
  },
  "service_tier": "default"
}

Replace model with another model ID such as claude-sonnet-5-5, gemini-4-hydrogen, deepseek-flash, kimi-k3.1-pro, glm-5.3, or qwen4-max to call other providers with exactly the same request format.

OpenAI recommends the developer role instead of system for newer models. If the same code also calls non-OpenAI models such as Claude or DeepSeek, keep using system for the best compatibility.

Image Input โœ…

Make content an array to send text and images in the same user message. An image can be a public URL or a base64 data URL (for example data:image/jpeg;base64,...).

curl https://beeroute.ai/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $API_KEY" \
  -d '{
    "model": "gpt-5.6-terra",
    "messages": [
      {
        "role": "user",
        "content": [
          {"type": "text", "text": "What is in this image?"},
          {
            "type": "image_url",
            "image_url": {
              "url": "https://api.nga.gov/iiif/a2e6da57-3cd1-4235-b20e-95dcaefed6c8/full/!800,800/0/default.jpg",
              "detail": "auto"
            }
          }
        ]
      }
    ],
    "max_completion_tokens": 1000
  }'

Response example:

{
  "id": "chatcmpl-Dk2wB7nTq0VhXe4sKp9LcR2mYa6Gu",
  "object": "chat.completion",
  "created": 1795740060,
  "model": "gpt-5.6-terra",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "This is an oil portrait of a young woman seated in a curved bentwood chair. She wears a red-and-blue striped jacket and a blue skirt with orange dots, holds a small sprig of flowers, and sits against a pale turquoise background. The bold brushwork and vivid colors are characteristic of Van Gogh.",
        "refusal": null,
        "annotations": []
      },
      "logprobs": null,
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 512,
    "completion_tokens": 168,
    "total_tokens": 680,
    "prompt_tokens_details": {"cached_tokens": 0, "audio_tokens": 0},
    "completion_tokens_details": {"reasoning_tokens": 96, "audio_tokens": 0, "accepted_prediction_tokens": 0, "rejected_prediction_tokens": 0}
  },
  "service_tier": "default"
}

Streaming Response โœ…

With "stream": true, the endpoint returns the reply in pieces as SSE (Server-Sent Events). Set stream_options.include_usage to receive one final chunk with the total usage for the request. Add -N to curl to disable output buffering so you see each chunk as it arrives.

curl -N https://beeroute.ai/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $API_KEY" \
  -d '{
    "model": "gpt-5.6-terra",
    "messages": [
      {"role": "user", "content": "Hello!"}
    ],
    "stream": true,
    "stream_options": {"include_usage": true}
  }'

Streaming response example:

data: {"id":"chatcmpl-Dk2xH4pWm8ZcQ1vN6tRb3LsJe0Kf","object":"chat.completion.chunk","created":1795740120,"model":"gpt-5.6-terra","choices":[{"index":0,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":null,"finish_reason":null}],"usage":null}

data: {"id":"chatcmpl-Dk2xH4pWm8ZcQ1vN6tRb3LsJe0Kf","object":"chat.completion.chunk","created":1795740120,"model":"gpt-5.6-terra","choices":[{"index":0,"delta":{"content":"Hello"},"logprobs":null,"finish_reason":null}],"usage":null}

data: {"id":"chatcmpl-Dk2xH4pWm8ZcQ1vN6tRb3LsJe0Kf","object":"chat.completion.chunk","created":1795740120,"model":"gpt-5.6-terra","choices":[{"index":0,"delta":{"content":"! How can I help you today?"},"logprobs":null,"finish_reason":null}],"usage":null}

data: {"id":"chatcmpl-Dk2xH4pWm8ZcQ1vN6tRb3LsJe0Kf","object":"chat.completion.chunk","created":1795740120,"model":"gpt-5.6-terra","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}],"usage":null}

data: {"id":"chatcmpl-Dk2xH4pWm8ZcQ1vN6tRb3LsJe0Kf","object":"chat.completion.chunk","created":1795740120,"model":"gpt-5.6-terra","choices":[],"usage":{"prompt_tokens":9,"completion_tokens":40,"total_tokens":49,"prompt_tokens_details":{"cached_tokens":0,"audio_tokens":0},"completion_tokens_details":{"reasoning_tokens":28,"audio_tokens":0,"accepted_prediction_tokens":0,"rejected_prediction_tokens":0}}}

data: [DONE]

Key points:

  • Each data: line carries one chat.completion.chunk object. The incremental text is in choices[0].delta.content; concatenate the pieces in order.
  • The stop reason appears in finish_reason of the last chunk that has choices.
  • With include_usage enabled, one extra chunk with an empty choices array arrives before [DONE]; its usage covers the whole request, and usage is null on every other chunk. If the stream is interrupted you may not receive this usage chunk.
  • The stream ends with data: [DONE], which is a plain-text marker, not JSON.
  • BeeRoute usually returns the usage chunk even when stream_options is omitted; set "include_usage": false explicitly if you do not want it.

Function Calling (Tool Calls) โœ…

Function calling takes two requests. First, send the available function definitions in tools; when the model decides to call one, it returns tool_calls. Run the function in your own code, then send the result back as a tool message so the model can write the final answer.

Step 1: send the question and the function definitions

curl https://beeroute.ai/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $API_KEY" \
  -d '{
    "model": "gpt-5.6-terra",
    "messages": [
      {"role": "user", "content": "What is the weather like in Boston today?"}
    ],
    "tools": [
      {
        "type": "function",
        "function": {
          "name": "get_weather",
          "description": "Get the current weather for a city",
          "parameters": {
            "type": "object",
            "properties": {
              "location": {
                "type": "string",
                "description": "City and state, for example: Boston, MA"
              },
              "unit": {
                "type": "string",
                "enum": ["celsius", "fahrenheit"]
              }
            },
            "required": ["location"]
          }
        }
      }
    ],
    "tool_choice": "auto"
  }'

Response example:

{
  "id": "chatcmpl-Dk2yR9cLx5TbW2nQ7vPe4KmZs1Hj",
  "object": "chat.completion",
  "created": 1795740180,
  "model": "gpt-5.6-terra",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": null,
        "tool_calls": [
          {
            "id": "call_Q8sV2nK7pL4mX1rT",
            "type": "function",
            "function": {
              "name": "get_weather",
              "arguments": "{\"location\":\"Boston, MA\",\"unit\":\"celsius\"}"
            }
          }
        ],
        "refusal": null,
        "annotations": []
      },
      "logprobs": null,
      "finish_reason": "tool_calls"
    }
  ],
  "usage": {
    "prompt_tokens": 86,
    "completion_tokens": 52,
    "total_tokens": 138,
    "prompt_tokens_details": {"cached_tokens": 0, "audio_tokens": 0},
    "completion_tokens_details": {"reasoning_tokens": 24, "audio_tokens": 0, "accepted_prediction_tokens": 0, "rejected_prediction_tokens": 0}
  },
  "service_tier": "default"
}

arguments is a JSON string generated by the model. The model does not guarantee that it is valid JSON or that it matches your schema, so parse and validate it before running the function.

Step 2: send the function result back to the model

Append to messages, in order: the assistant message the model returned (keep its tool_calls unchanged), then a message with role set to tool whose tool_call_id matches the id of the call. Keep sending tools as well.

curl https://beeroute.ai/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $API_KEY" \
  -d '{
    "model": "gpt-5.6-terra",
    "messages": [
      {"role": "user", "content": "What is the weather like in Boston today?"},
      {
        "role": "assistant",
        "content": null,
        "tool_calls": [
          {
            "id": "call_Q8sV2nK7pL4mX1rT",
            "type": "function",
            "function": {
              "name": "get_weather",
              "arguments": "{\"location\":\"Boston, MA\",\"unit\":\"celsius\"}"
            }
          }
        ]
      },
      {
        "role": "tool",
        "tool_call_id": "call_Q8sV2nK7pL4mX1rT",
        "content": "{\"location\":\"Boston, MA\",\"temperature\":6,\"unit\":\"celsius\",\"condition\":\"sunny\"}"
      }
    ],
    "tools": [
      {
        "type": "function",
        "function": {
          "name": "get_weather",
          "description": "Get the current weather for a city",
          "parameters": {
            "type": "object",
            "properties": {
              "location": {
                "type": "string",
                "description": "City and state, for example: Boston, MA"
              },
              "unit": {
                "type": "string",
                "enum": ["celsius", "fahrenheit"]
              }
            },
            "required": ["location"]
          }
        }
      }
    ]
  }'

Response example:

{
  "id": "chatcmpl-Dk2zT3vNq6WcY8mLp1RbX5KeJs0Fa",
  "object": "chat.completion",
  "created": 1795740185,
  "model": "gpt-5.6-terra",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "It is sunny in Boston today, at about 6ยฐC. Dress warmly if you go out.",
        "refusal": null,
        "annotations": []
      },
      "logprobs": null,
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 152,
    "completion_tokens": 30,
    "total_tokens": 182,
    "prompt_tokens_details": {"cached_tokens": 0, "audio_tokens": 0},
    "completion_tokens_details": {"reasoning_tokens": 0, "audio_tokens": 0, "accepted_prediction_tokens": 0, "rejected_prediction_tokens": 0}
  },
  "service_tier": "default"
}

The model may return several tool_calls in one reply (parallel calls). Append one tool message per call, directly after the assistant message that contains them.

According to OpenAI, GPT-6 Astra, GPT-6.1 Sol, and GPT-6.2 Astra / Sol do not support function calling in Chat Completions. Use the Responses API when these models need tools.

Structured Output (JSON Schema) โœ…

Pass a JSON Schema in response_format and set "strict": true; the model output will then follow that structure exactly.

curl https://beeroute.ai/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $API_KEY" \
  -d '{
    "model": "gpt-5.6-terra",
    "messages": [
      {"role": "system", "content": "Extract the event information from the user text."},
      {"role": "user", "content": "Alice and Bob are going to a science fair on Friday."}
    ],
    "response_format": {
      "type": "json_schema",
      "json_schema": {
        "name": "event_info",
        "strict": true,
        "schema": {
          "type": "object",
          "properties": {
            "name": {"type": "string"},
            "date": {"type": "string"},
            "participants": {
              "type": "array",
              "items": {"type": "string"}
            }
          },
          "required": ["name", "date", "participants"],
          "additionalProperties": false
        }
      }
    }
  }'

Response example:

{
  "id": "chatcmpl-Dk30Lm5Rq8ZtV2xNc7WbK4PeYs9Hd",
  "object": "chat.completion",
  "created": 1795740240,
  "model": "gpt-5.6-terra",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "{\"name\":\"Science fair\",\"date\":\"Friday\",\"participants\":[\"Alice\",\"Bob\"]}",
        "refusal": null,
        "annotations": []
      },
      "logprobs": null,
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 92,
    "completion_tokens": 58,
    "total_tokens": 150,
    "prompt_tokens_details": {"cached_tokens": 0, "audio_tokens": 0},
    "completion_tokens_details": {"reasoning_tokens": 32, "audio_tokens": 0, "accepted_prediction_tokens": 0, "rejected_prediction_tokens": 0}
  },
  "service_tier": "default"
}

message.content is a JSON string; parse it to get the structured data. If the model refuses for safety reasons, content is null and the reason is in message.refusal.

Reasoning Effort (reasoning_effort) โœ…

Reasoning models produce internal reasoning tokens before answering. reasoning_effort controls how deeply they reason: higher values think more thoroughly but take longer and use more reasoning tokens. Reasoning tokens do not appear in the reply, but they count toward completion_tokens and are billed as output.

curl https://beeroute.ai/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $API_KEY" \
  -d '{
    "model": "gpt-5.6-terra",
    "reasoning_effort": "high",
    "messages": [
      {"role": "user", "content": "A farmer has 17 sheep and all but 9 die. How many sheep are left? Explain briefly."}
    ],
    "max_completion_tokens": 4000
  }'

Response example:

{
  "id": "chatcmpl-Dk31Wq2Tn7KcX5vRb9LmZe3PsY0Gj",
  "object": "chat.completion",
  "created": 1795740300,
  "model": "gpt-5.6-terra",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "9 sheep are left. \"All but 9 die\" means every sheep except 9 died, so exactly 9 survive.",
        "refusal": null,
        "annotations": []
      },
      "logprobs": null,
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 45,
    "completion_tokens": 412,
    "total_tokens": 457,
    "prompt_tokens_details": {"cached_tokens": 0, "audio_tokens": 0},
    "completion_tokens_details": {"reasoning_tokens": 352, "audio_tokens": 0, "accepted_prediction_tokens": 0, "rejected_prediction_tokens": 0}
  },
  "service_tier": "default"
}

max_completion_tokens limits visible output and reasoning tokens together. Leave enough room at higher effort levels, or the reply may be cut off with finish_reason: "length" before the answer is written.

๐Ÿ“ฎ Request

Endpoint

POST https://beeroute.ai/v1/chat/completions

Authentication

Send your API key in the request header:

Authorization: Bearer $API_KEY

$API_KEY is the key you created on the BeeRoute console API Keys page. The request body is JSON, so also set Content-Type: application/json.

Request Body Parameters

The tables below list the main parameters from OpenAI's documentation. Parameter support varies by model, especially for reasoning models. The official API reference has the complete field descriptions. OpenAI's prompt_cache_options and moderation parameters are not currently forwarded by BeeRoute, so they are not listed.

Required Parameters

ParameterTypeDescription
modelstringModel ID, for example gpt-5.6-terra. See the pricing page or GET /v1/models for available models.
messagesarrayThe conversation so far, with at least 1 message. See "Message Types" below.

Generation Control

ParameterTypeDefaultDescription
max_completion_tokensinteger or null-Upper bound on tokens generated for the completion, including visible output and reasoning tokens.
reasoning_effortstring or nullmodel-dependentReasoning effort: none, minimal, low, medium, high, xhigh, or max. Supported values differ by model; for example, gpt-5.6-terra supports none, low, medium (default), high, xhigh, and max. See the official reasoning guide.
verbositystring or nullmediumHow detailed the reply should be: low, medium, or high. Lower values give more concise replies. Support varies by model.
stopstring, array, or nullnullUp to 4 stop sequences. Generation stops at these sequences, and the returned text does not include them. Not supported by some reasoning models.
ninteger or null1How many choices to generate for each input. Omit it to get one choice; newer models reject an explicit n (even n=1). Output tokens of all choices are billed.
modalitiesarray or null["text"]Output modalities you want. Models that support audio output accept ["text", "audio"].
audioobject or null-Audio output parameters, required when audio output is requested. See "audio Parameters" below.
predictionobject or null-Predicted Outputs configuration. When most of the reply is known in advance (for example, a small edit to a file), this can greatly speed up the response. Format: {"type": "content", "content": "..."}, where content is a string or an array of text parts.

Sampling Parameters

ParameterTypeDefaultDescription
temperaturenumber or null1Sampling temperature between 0 and 2. Higher values give more random output; lower values give more focused, deterministic output. Adjust this or top_p, not both.
top_pnumber or null1Nucleus sampling between 0 and 1. 0.1 means only the tokens in the top 10% probability mass are considered.
presence_penaltynumber or null0Between -2.0 and 2.0. Positive values penalize tokens that have already appeared, encouraging new topics.
frequency_penaltynumber or null0Between -2.0 and 2.0. Positive values penalize tokens by how often they have appeared, reducing verbatim repetition.
logit_biasobject or nullnullMaps token IDs to a bias from -100 to 100 to raise or lower the likelihood of specific tokens; -100 or 100 effectively bans or forces a token.
logprobsboolean or nullfalseWhether to return log probabilities of the output tokens.
top_logprobsinteger or null-Between 0 and 20: the number of most likely tokens to return at each position, with their log probabilities. Requires logprobs: true.

Reasoning models usually do not support some of these sampling parameters. For example, OpenAI says to omit temperature, top_p, logprobs, and top_logprobs when using GPT-6.2 Astra / Sol with Chat Completions, and BeeRoute usually ignores temperature, top_p, and logprobs for GPT-5 series models. Check each model's official documentation.

Streaming

ParameterTypeDefaultDescription
streamboolean or nullfalseWhen true, the response is streamed as SSE chat.completion.chunk events, ending with data: [DONE].
stream_optionsobject or nullnullStreaming options; set only when stream: true. include_usage (boolean): when true, one extra chunk with the total usage is sent before [DONE]. OpenAI also defines include_obfuscation, which BeeRoute usually does not forward.

Tool Calling

ParameterTypeDefaultDescription
toolsarray-Tools the model may call: function tools (function) and custom tools (custom). See "tools Definitions" below.
tool_choicestring or objectnone without tools, auto with toolsControls whether and which tool the model calls. See "tool_choice Values" below.
parallel_tool_callsbooleantrueWhether the model may call several functions in parallel in one reply.
web_search_optionsobject-Web search configuration, only for search models that support it. See "web_search_options" below.

Output Format

ParameterTypeDescription
response_formatobjectOutput format: {"type": "text"} (default), {"type": "json_schema", "json_schema": {...}} (Structured Outputs, recommended), or {"type": "json_object"} (older JSON mode). See "response_format" below.

Caching, Identifiers and Other

ParameterTypeDefaultDescription
prompt_cache_keystring or null-Key used to improve prompt cache hit rates; use the same value for similar requests. Replaces the caching role of the deprecated user field.
safety_identifierstring or null-Stable end-user identifier (up to 128 characters) that helps OpenAI detect users who violate its usage policies; a hash of the username or email is recommended. BeeRoute does not forward this field upstream by default.
service_tierstring or nullautoOfficial values: auto, default, flex, scale, priority, fast. BeeRoute accepts the field but normally ignores it and forwards the request with default processing.
metadataobject or null-Up to 16 key-value pairs; keys up to 64 characters, values are strings up to 512 characters.
storeboolean or nullfalseWhether the upstream provider stores this completion for OpenAI's model distillation or evals products. BeeRoute does not offer endpoints for reading stored completions, so you usually do not need this.

Deprecated Parameters

These parameters are still accepted, but OpenAI no longer recommends them:

ParameterReplacementDescription
max_tokensmax_completion_tokensOld maximum number of generated tokens; not compatible with o-series reasoning models.
usersafety_identifier, prompt_cache_keyOld end-user identifier.
seed-Beta feature for best-effort deterministic sampling; identical results are not guaranteed.
functionstoolsOld list of functions (up to 128).
function_calltool_choiceOld function call control: none, auto, or {"name": "my_function"}.
prompt_cache_retentionprompt_cache_options.ttlPrompt cache retention policy, in_memory or 24h; gpt-5.5, gpt-5.5-pro, and later models support only 24h. BeeRoute still forwards this field but does not forward prompt_cache_options.

Message Types

Each message in messages has a role:

roleDescriptionMain fields
developerDeveloper instructions the model should always follow. OpenAI recommends it instead of system for newer models.content (required, string or array of text parts), name
systemSystem instructions, same purpose as developer.content (required, string or array of text parts), name
userInput from the end user.content (required, string or array of content parts: text, image, audio, file), name
assistantA previous reply from the model, sent back unchanged in multi-turn conversations.content (may be null when tool_calls is present), tool_calls, refusal, audio ({"id": "..."} of a previous audio reply), name
toolResult of a tool call.content (required, string or array of text parts), tool_call_id (required, the id of the tool call)
functionDeprecated, replaced by tool.content, name

name is an optional participant name that distinguishes participants with the same role.

Content Parts

When content is an array, each element is a content part with a type:

typeStructureUsed inDescription
text{"type": "text", "text": "..."}all rolesText.
image_url{"type": "image_url", "image_url": {"url": "...", "detail": "auto"}}userImage. url is an image URL or a base64 data URL; detail is auto (default), low, high, or original, and supported values depend on the model.
input_audio{"type": "input_audio", "input_audio": {"data": "...", "format": "wav"}}userBase64-encoded audio; format is wav or mp3. Requires a model with audio input.
file{"type": "file", "file": {"filename": "a.pdf", "file_data": "data:application/pdf;base64,..."}}userFile input; Chat Completions accepts PDF only. OpenAI also supports file_id for uploaded files; through BeeRoute, use file_data.
refusal{"type": "refusal", "refusal": "..."}assistantA refusal the model generated earlier.

tools Definitions

Function tool:

{
  "type": "function",
  "function": {
    "name": "get_weather",
    "description": "Get the current weather for a city",
    "parameters": {
      "type": "object",
      "properties": {
        "location": {"type": "string"}
      },
      "required": ["location"]
    }
  }
}
FieldRequiredDescription
function.nameyesFunction name: a-z, A-Z, 0-9, underscores, and dashes, up to 64 characters.
function.descriptionnoWhat the function does; helps the model decide when and how to call it.
function.parametersnoParameters described as a JSON Schema object; omit it for a function with no parameters.
function.strictnoOfficial field; when true, generated arguments strictly follow the schema. BeeRoute does not currently forward this field; for strict structure, use response_format with json_schema.

Custom tool (the model sends free-form text or grammar-constrained text as the tool input; mainly for OpenAI models):

{
  "type": "custom",
  "custom": {
    "name": "run_sql",
    "description": "Run a read-only SQL query",
    "format": {"type": "text"}
  }
}

custom.name is required; description is optional; format is optional and defaults to unconstrained text ({"type": "text"}), or it can be a grammar {"type": "grammar", "grammar": {"definition": "...", "syntax": "lark"}} (syntax is lark or regex). When the model calls a custom tool, the tool_calls entry looks like {"id": "...", "type": "custom", "custom": {"name": "run_sql", "input": "..."}}.

tool_choice Values

ValueMeaning
"none"Do not call any tool; generate a message.
"auto"The model chooses between generating a message and calling one or more tools.
"required"The model must call one or more tools.
{"type": "function", "function": {"name": "get_weather"}}Force a call to the named function tool.
{"type": "custom", "custom": {"name": "run_sql"}}Force a call to the named custom tool.
{"type": "allowed_tools", "allowed_tools": {...}}Limit the available tools to a subset; see the example below.

allowed_tools example (with mode set to auto the model may pick from the subset or reply directly; with required it must call a tool from the subset):

{
  "type": "allowed_tools",
  "allowed_tools": {
    "mode": "auto",
    "tools": [
      {"type": "function", "function": {"name": "get_weather"}},
      {"type": "function", "function": {"name": "get_time"}}
    ]
  }
}

response_format

typeStructureDescription
text{"type": "text"}Default; plain text reply.
json_schema{"type": "json_schema", "json_schema": {...}}Structured Outputs; the output matches the given JSON Schema. Recommended for models that support it.
json_object{"type": "json_object"}Older JSON mode that only guarantees valid JSON. You must also tell the model to produce JSON in a system or user message.

Fields of the json_schema object:

FieldRequiredDescription
nameyesFormat name: a-z, A-Z, 0-9, underscores, and dashes, up to 64 characters.
descriptionnoWhat the format is for.
schemanoThe JSON Schema object.
strictnoDefaults to false. When true, the output strictly follows the schema, but only a subset of JSON Schema is supported; see the official Structured Outputs guide.

web_search_options

{
  "search_context_size": "medium",
  "user_location": {
    "type": "approximate",
    "approximate": {
      "country": "US",
      "city": "San Francisco",
      "region": "California",
      "timezone": "America/Los_Angeles"
    }
  }
}
FieldDescription
search_context_sizeHow much context window space search results may use: low, medium (default), or high.
user_locationApproximate location, or null. type is always approximate; approximate can contain country (two-letter ISO country code), region and city (free text), and timezone (IANA time zone), all optional.

audio Parameters

FieldRequiredDescription
voiceyesA built-in voice such as alloy, ash, ballad, coral, echo, sage, shimmer, verse, marin, or cedar, or a custom voice object {"id": "voice_1234"}.
formatyesOutput audio format: wav, aac, mp3, flac, opus, or pcm16.

๐Ÿ“ฅ Response

A non-streaming request returns one chat.completion object; a streaming request returns a sequence of chat.completion.chunk objects.

chat.completion Object

FieldTypeDescription
idstringUnique ID of the completion.
objectstringAlways chat.completion.
createdintegerCreation time (Unix timestamp in seconds).
modelstringThe model that generated the completion.
choicesarrayList of choices; can contain more than one when n is greater than 1.
usageobjectToken usage for the request; see "usage Object" below.
service_tierstring or nullThe service tier actually used (may be present).
system_fingerprintstringDeprecated. Backend configuration fingerprint (may be present).

Each element of choices:

FieldDescription
indexPosition of the choice in the list.
messageThe message generated by the model; fields in the table below.
logprobsLog probability information when logprobs was requested, with content and refusal token lists; otherwise null.
finish_reasonWhy generation stopped; see "finish_reason Values" below.

The message object:

FieldDescription
roleAlways assistant.
contentReply text; may be null (for example, when only tool calls are returned).
refusalExplanation when the model refuses; otherwise null.
tool_callsList of tool calls. A function call entry has id, type (function), and function (with name and arguments); a custom tool call entry has id, type (custom), and custom (with name and input).
annotationsAnnotations, such as url_citation entries (with url, title, start_index, end_index) when web search is used.
audioReturned when audio output is requested; contains id, data (base64 audio), transcript, and expires_at.
function_callDeprecated, replaced by tool_calls.

usage Object

FieldDescription
prompt_tokensNumber of input (prompt) tokens.
completion_tokensNumber of output tokens, including reasoning tokens.
total_tokensTotal tokens (input + output).
prompt_tokens_details.cached_tokensInput tokens served from the prompt cache.
prompt_tokens_details.cache_write_tokensInput tokens written to the prompt cache (a newer official field; may be absent).
prompt_tokens_details.audio_tokensAudio tokens in the input.
completion_tokens_details.reasoning_tokensReasoning tokens generated by the model.
completion_tokens_details.audio_tokensAudio tokens generated by the model.
completion_tokens_details.accepted_prediction_tokensWith Predicted Outputs, prediction tokens that appeared in the completion.
completion_tokens_details.rejected_prediction_tokensWith Predicted Outputs, prediction tokens that did not appear in the completion; they are still billed as output.

For models whose format BeeRoute converts (such as Claude and Gemini), usage may contain a few extra fields; you can ignore them.

finish_reason Values

ValueMeaning
stopThe model finished naturally or hit a stop sequence.
lengthReached max_completion_tokens or the model's output limit.
tool_callsThe model called a tool.
content_filterContent was omitted by a content filter.
function_callDeprecated; the model called a legacy function.

chat.completion.chunk Object

Each chunk in a streaming response:

FieldDescription
idCompletion ID; the same for every chunk of a request.
objectAlways chat.completion.chunk.
createdCreation time; the same for every chunk.
modelThe model that generated the completion.
choicesList of choice deltas, each with index, delta, logprobs, and finish_reason. With include_usage, the final usage chunk has an empty choices array.
choices[].deltaIncremental content; may contain role, content, tool_calls, refusal, and audio.
choices[].finish_reasonnull until the end, then one of the values in the table above.
usagePresent only with include_usage: the total usage on the last chunk, null on the others.
service_tier, system_fingerprintSame as in the chat.completion object.
obfuscationRandom string OpenAI uses to normalize chunk sizes; may be present and can be ignored.

When tool calls are streamed, each entry in delta.tool_calls has an index, and the function name and arguments arrive across several chunks. Concatenate the arguments fragments by index before parsing them.

โ— Errors

A failed request returns a non-2xx status code with an OpenAI-style error object in the body. Common status codes:

StatusCommon causes
400Invalid request: malformed JSON, missing required fields, a parameter the model does not support, and so on.
401Invalid API key: wrong key, or the key is disabled, expired, or out of quota.
403Access denied: insufficient account balance, or the key is not allowed to use the model or group.
429Too many requests; a rate limit was hit. Retry later.
500Internal server error or upstream processing failure; retry later.
503No channel is currently available for the model, or the upstream service is temporarily unavailable.

Errors produced by the BeeRoute gateway itself (such as an invalid key, insufficient balance, or no available channel) look like this; the exact message text may vary with the language setting:

{
  "error": {
    "code": "",
    "message": "Invalid token (request id: 20261127120000123456789abcdefgh)",
    "type": "new_api_error"
  }
}

Errors from upstream model providers are also returned as an error object, usually with message, type, param, and code fields. Include the request id at the end of message when you contact support. If a streaming request fails after output has started, the error may arrive as a data: chunk containing an error field, and the stream may end without [DONE].

Last updated 2026-11-29 ยท Markdown source ยท llms.txt