> ## Documentation Index
> Fetch the complete documentation index at: https://docs.haitoken.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# OpenAI 格式

> 创建聊天补全请求，兼容 OpenAI Chat Completions 协议，支持流式和非流式响应

此接口兼容 OpenAI Chat Completions 协议，用于创建聊天补全请求。

## 功能特性

* 支持流式（SSE）和非流式两种响应模式
* 支持多模态输入（文本、图片等）
* 支持函数调用与工具调用（Function/Tool Calling）
* 支持结构化输出（JSON Schema）
* 支持推理模式配置（reasoning\_effort）
* 支持网络搜索选项

## 使用场景

适用于需要与 OpenAI 兼容模型进行对话交互的场景，包括：

* 单轮或多轮对话
* 函数调用与工具编排
* 结构化 JSON 输出
* 流式实时响应

## 认证方式

在请求头中携带 `Authorization` 字段，格式为 `Bearer YOUR_API_KEY`。

<Warning>
  请勿在客户端代码中暴露 API Key，建议通过服务端代理转发请求。
</Warning>

## 快速示例

<CodeGroup>
  ```python Python theme={null}
  import requests

  url = "https://api.haitoken.ai/v1/chat/completions"
  headers = {
      "Authorization": "Bearer YOUR_API_KEY",
      "Content-Type": "application/json"
  }
  data = {
      "model": "gpt-4o",
      "messages": [
          {"role": "user", "content": "你好，请介绍一下自己"}
      ]
  }

  response = requests.post(url, json=data, headers=headers)
  print(response.json())
  ```

  ```javascript Node.js theme={null}
  const response = await fetch('https://api.haitoken.ai/v1/chat/completions', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      model: 'gpt-4o',
      messages: [
        { role: 'user', content: '你好，请介绍一下自己' }
      ]
    })
  });

  const data = await response.json();
  console.log(data);
  ```

  ```curl cURL theme={null}
  curl -X POST 'https://api.haitoken.ai/v1/chat/completions' \
    -H 'Authorization: Bearer YOUR_API_KEY' \
    -H 'Content-Type: application/json' \
    -d '{
      "model": "gpt-4o",
      "messages": [
        {"role": "user", "content": "你好，请介绍一下自己"}
      ]
    }'
  ```
</CodeGroup>


## OpenAPI

````yaml zh/api-reference/chat/openai/openapi.json POST /v1/chat/completions
openapi: 3.0.1
info:
  title: 默认模块
  description: ''
  version: 1.0.0
servers: []
security: []
tags: []
paths:
  /v1/chat/completions:
    post:
      tags: []
      summary: 创建聊天补全
      description: 支持流式（SSE）和非流式两种响应模式
      parameters:
        - name: Authorization
          in: header
          description: ''
          required: true
          schema:
            type: string
            example: Bearer YOUR_API_KEY
        - name: Content-Type
          in: header
          description: ''
          schema:
            type: string
            example: application/json
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ChatCompletionRequest'
              description: ''
            examples: {}
      responses:
        '200':
          description: ''
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ChatCompletionResponse'
                description: OpenAI Chat Completions API 响应对象
          headers: {}
      deprecated: false
      security: []
components:
  schemas:
    ChatCompletionRequest:
      type: object
      properties:
        stream_options:
          $ref: '#/components/schemas/StreamOptions'
          description: 流式响应选项（仅在 stream=true 时使用）
        top_p:
          type: number
          description: 核采样，0-1 之间
        max_tokens:
          type: integer
          description: 生成的最大 token 数量（已弃用，建议使用 max_completion_tokens）
        max_completion_tokens:
          type: integer
          description: 生成的最大 token 数量（包括可见输出 token 和推理 token）
        frequency_penalty:
          type: number
          description: 频率惩罚，-2.0 到 2.0
        presence_penalty:
          type: number
          description: 存在惩罚，-2.0 到 2.0
        logit_bias:
          $ref: '#/components/schemas/MapInteger'
          description: 修改指定 token 出现概率的映射
        top_logprobs:
          type: integer
          description: 每个 token 位置返回的最可能 token 的最大数量（0-20）
        response_format:
          $ref: '#/components/schemas/ResponseFormat'
          description: 响应格式，支持 "text"、"json_object"、"json_schema"
        prompt_cache_key:
          type: string
          description: 稳定标识符，用于缓存优化
        prompt_cache_retention:
          type: string
          description: 缓存保留策略："in_memory" 或 "24h"
        safety_identifier:
          type: string
          description: 安全标识符，用于检测违规用户
        tool_choice:
          type: object
          properties: {}
          description: 控制模型调用哪个工具，可以是字符串（"none"/"auto"/"required"）或对象
        parallel_tool_calls:
          type: boolean
          description: 是否启用并行工具调用
        service_tier:
          type: string
          description: 服务层级："auto"、"default"、"flex"、"scale"、"priority"
        reasoning_effort:
          type: string
          description: 推理努力程度："none"、"minimal"、"low"、"medium"、"high"、"xhigh"
        web_search_options:
          type: object
          properties: {}
          description: 网络搜索选项
        function_call:
          type: object
          properties: {}
          description: 已弃用：函数调用控制
        model:
          type: string
          description: 模型 ID，如 gpt-4o、deepseek-chat 等
        messages:
          type: array
          items:
            $ref: '#/components/schemas/ChatMessage'
            description: 聊天消息对象，兼容 OpenAI 各种角色消息
          description: 消息列表
        stream:
          type: boolean
          description: 是否启用流式输出
        temperature:
          type: number
          description: 采样温度，0-2 之间，值越高输出越随机
        stop:
          type: object
          properties: {}
          description: 停止序列
        'n':
          type: integer
          description: 每个输入消息生成的聊天补全选择数量
        logprobs:
          type: boolean
          description: 是否返回输出 token 的对数概率
        seed:
          type: integer
          description: 用于确定性采样的种子值
          format: int64
        user:
          type: string
          description: 用户标识（已弃用，建议使用 prompt_cache_key）
        tools:
          type: array
          items:
            $ref: '#/components/schemas/ToolDefinition'
            description: 工具定义（请求参数中使用）
          description: 模型可调用的工具列表
        modalities:
          type: array
          items:
            type: string
          description: 输出类型列表：["text"] 或 ["text", "audio"]
        audio:
          type: object
          properties: {}
          description: 音频输出参数
        metadata:
          $ref: '#/components/schemas/MapString'
          description: 元数据，最多16个键值对
        prediction:
          type: object
          properties: {}
          description: 预测输出内容
        verbosity:
          type: string
          description: 响应详细程度："low"、"medium"、"high"
        functions:
          type: array
          items:
            type: object
            properties: {}
          description: 已弃用：函数定义列表
      required:
        - model
        - messages
    ChatCompletionResponse:
      type: object
      properties:
        system_fingerprint:
          type: string
          description: 系统指纹，表示后端配置
        service_tier:
          type: string
          description: 实际使用的服务层级
        id:
          type: string
          description: 聊天补全的唯一标识
        object:
          type: string
          description: 对象类型，始终为 "chat.completion"
        created:
          type: integer
          description: 创建时间（Unix 时间戳）
          format: int64
        model:
          type: string
          description: 使用的模型 ID
        choices:
          type: array
          items:
            $ref: '#/components/schemas/ChatChoice'
            description: 聊天补全选择项
          description: 聊天补全选择列表
        usage:
          $ref: '#/components/schemas/Usage'
          description: 使用统计信息
    StreamOptions:
      type: object
      properties:
        include_usage:
          type: boolean
          description: 是否在最终 chunk 中包含 usage 统计信息
    MapInteger:
      type: object
      properties:
        key:
          type: integer
    ResponseFormat:
      type: object
      properties:
        json_schema:
          $ref: '#/components/schemas/JsonSchema'
          description: JSON Schema 配置（仅当 type 为 "json_schema" 时使用）
        type:
          type: string
          description: 响应格式类型："text" | "json_object" | "json_schema"
    ChatMessage:
      type: object
      properties:
        tool_calls:
          type: array
          items:
            $ref: '#/components/schemas/ToolCall'
            description: 模型生成的工具调用（如函数调用）
          description: 工具调用列表（模型生成）
        tool_call_id:
          type: string
          description: 工具调用 ID（仅 tool 角色消息使用）
        reasoning_content:
          type: string
          description: 深度思考内容（DeepSeek等推理模型扩展字段）
        role:
          type: string
          description: 消息角色：system/developer/user/assistant/tool/function
          enum:
            - SYSTEM
            - DEVELOPER
            - USER
            - ASSISTANT
            - TOOL
            - FUNCTION
        content:
          type: object
          properties: {}
          description: 消息内容，支持字符串或内容部件数组（多模态）
        name:
          type: string
          description: 消息发送者名称（可选）
        refusal:
          type: string
          description: 拒绝消息（模型生成的拒绝回复）
        annotations:
          type: array
          items:
            type: object
            properties: {}
          description: 注释列表（如 web search 时的 URL 引用）
      required:
        - role
    ToolDefinition:
      type: object
      properties:
        type:
          type: string
          description: 工具类型，目前仅支持 "function"
        function:
          $ref: '#/components/schemas/FunctionDefinition'
          description: 函数定义详情
    MapString:
      type: object
      properties:
        key:
          type: string
    ChatChoice:
      type: object
      properties:
        finish_reason:
          type: string
          description: >-
            模型停止生成的原因："stop"、"length"、"tool_calls"、"content_filter"、"function_call"
        index:
          type: integer
          description: 选择在列表中的索引
        message:
          $ref: '#/components/schemas/ChatMessage'
          description: 模型生成的消息
        logprobs:
          $ref: '#/components/schemas/LogProbs'
          description: 对数概率信息
    Usage:
      type: object
      properties:
        prompt_tokens:
          type: integer
          description: 提示词 token 数量
        completion_tokens:
          type: integer
          description: 补全 token 数量
        total_tokens:
          type: integer
          description: 总 token 数量
        prompt_tokens_details:
          $ref: '#/components/schemas/PromptTokensDetails'
          description: 提示词 token 明细
        completion_tokens_details:
          $ref: '#/components/schemas/CompletionTokensDetails'
          description: 补全 token 明细
        ephemeral_5m_input_tokens:
          type: integer
          description: 创建 5 分钟缓存条目的输入 token 数
        ephemeral_1h_input_tokens:
          type: integer
          description: 创建 1 小时缓存条目的输入 token 数
        web_search_requests:
          type: integer
          description: Web 搜索工具请求次数
    JsonSchema:
      type: object
      properties:
        name:
          type: string
          description: 响应格式名称
        description:
          type: string
          description: 描述
        schema:
          type: object
          properties: {}
          description: JSON Schema 对象
        strict:
          type: boolean
          description: 是否启用严格 schema 遵循
    ToolCall:
      type: object
      properties:
        id:
          type: string
          description: 工具调用的唯一标识
        index:
          type: integer
          description: 工具调用的索引
        type:
          type: string
          description: 工具类型，目前仅支持 "function"
        function:
          $ref: '#/components/schemas/FunctionCall'
          description: 函数调用详情
    FunctionDefinition:
      type: object
      properties:
        name:
          type: string
          description: 函数名称，必须为 a-z, A-Z, 0-9, 下划线和短横线，最大长度64
        description:
          type: string
          description: 函数描述，模型根据此描述决定何时以及如何调用函数
        parameters:
          type: object
          properties: {}
          description: 函数参数，JSON Schema 对象
        strict:
          type: boolean
          description: 是否启用严格 schema 遵循
    LogProbs:
      type: object
      properties:
        content:
          type: array
          items:
            $ref: '#/components/schemas/TokenLogprob'
            description: 单个 token 的对数概率信息
          description: 消息内容 token 的对数概率信息列表
        refusal:
          type: array
          items:
            $ref: '#/components/schemas/TokenLogprob'
            description: 单个 token 的对数概率信息
          description: 拒绝消息 token 的对数概率信息列表
    PromptTokensDetails:
      type: object
      properties:
        cached_tokens:
          type: integer
          description: 缓存 token 数量
        audio_tokens:
          type: integer
          description: 音频 token 数量
    CompletionTokensDetails:
      type: object
      properties:
        reasoning_tokens:
          type: integer
          description: 推理 token 数量
        audio_tokens:
          type: integer
          description: 音频 token 数量
        accepted_prediction_tokens:
          type: integer
          description: 预测输出中出现在补全中的 token 数量
        rejected_prediction_tokens:
          type: integer
          description: 预测输出中未出现在补全中的 token 数量
    FunctionCall:
      type: object
      properties:
        name:
          type: string
          description: 函数名称
        arguments:
          type: string
          description: 函数参数（JSON格式字符串）
    TokenLogprob:
      type: object
      properties:
        top_logprobs:
          type: array
          items:
            $ref: '#/components/schemas/TopLogprob'
            description: com.haitoken.core.interfaces.dto.TokenLogprob.TopLogprob
          description: 最可能的 token 列表及其对数概率
        token:
          type: string
          description: token 文本
        logprob:
          type: number
          description: token 的对数概率
        bytes:
          type: array
          items:
            type: integer
          description: token 的 UTF-8 字节表示
    TopLogprob:
      type: object
      properties:
        token:
          type: string
          description: token 文本
        logprob:
          type: number
          description: token 的对数概率
        bytes:
          type: array
          items:
            type: integer
          description: token 的 UTF-8 字节表示

````