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

# 创建对话请求 (OpenAI)

> 通用文本对话接口，支持 OpenAI 兼容的大语言模型生成对话回答

## 简介

通用文本对话接口，支持 OpenAI 兼容的大语言模型生成对话回答。通过统一的 API 接口，您可以调用 OpenAI、Claude、DeepSeek、Grok、通义千问等多个主流大模型。

## 认证

Bearer Token，如 `Bearer sk-xxxxxxxxxx`

## 请求参数

<ParamField body="model" type="string" required>
  模型标识，对应模型广场。

  <Tip>
    mixroute支持多种模型，完成模型列表见 [模型广场](https://console.mixroute.ai/models)。
  </Tip>
</ParamField>

<ParamField body="messages" type="array" required>
  对话消息列表，每个元素包含 `role`（user/system/assistant）和 `content`
</ParamField>

<ParamField body="temperature" type="number">
  随机性控制，0-2，值越高回复越随机
</ParamField>

<ParamField body="stream" type="boolean">
  是否启用流式输出，返回 SSE 格式的分片数据
</ParamField>

<ParamField body="max_tokens" type="integer">
  最大生成 token 数，控制回复长度
</ParamField>

<ParamField body="response_format" type="object">
  输出格式，支持 `text` 或 `json_object` / `json_schema`
</ParamField>

<ParamField body="top_p" type="number">
  核采样参数，0-1，替代 temperature 使用，值越低采样越保守
</ParamField>

<ParamField body="frequency_penalty" type="number">
  频率惩罚，-2 到 2，正值根据已有频率减少重复 token
</ParamField>

<ParamField body="presence_penalty" type="number">
  存在惩罚，-2 到 2，正值鼓励讨论新话题
</ParamField>

<ParamField body="stop" type="string | array">
  停止序列，遇到指定字符串时停止生成
</ParamField>

<ParamField body="seed" type="integer">
  随机种子，传入相同 seed 可使生成结果尽量一致
</ParamField>

<ParamField body="user" type="string">
  最终用户标识，用于监控和限流
</ParamField>

<ParamField body="n" type="integer">
  每个 prompt 生成的回复候选数，默认为 1
</ParamField>

<ParamField body="logit_bias" type="object">
  词元偏置，将 token ID 映射到偏置值（-100 到 100）
</ParamField>

<ParamField body="tools" type="array">
  工具定义列表，每个工具须包含 `type` 和 `function`
</ParamField>

<ParamField body="tool_choice" type="string">
  工具选择策略：`"auto"` / `"none"` / `"required"`，或指定工具名
</ParamField>

## 基础示例

<Tabs>
  <Tab title="非流式请求">
    ```bash theme={null}
    curl -X POST "https://api.mixroute.ai/v1/chat/completions" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer sk-xxxxxxxxxx" \
      -d '{
        "model": "gpt-5.5",
        "messages": [
          {"role": "system", "content": "你是一个有用的助手"},
          {"role": "user", "content": "请用中文简要介绍人工智能"}
        ],
        "temperature": 0.7
      }'
    ```
  </Tab>

  <Tab title="流式请求（SSE）">
    ```bash theme={null}
    curl -N -X POST "https://api.mixroute.ai/v1/chat/completions" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer sk-xxxxxxxxxx" \
      -d '{
        "model": "gpt-5.5",
        "stream": true,
        "messages": [
          {"role": "system", "content": "你是一个有用的助手"},
          {"role": "user", "content": "请用中文简要介绍人工智能"}
        ]
      }'
    ```
  </Tab>

  <Tab title="Python 示例">
    ```python theme={null}
    from openai import OpenAI

    client = OpenAI(
        api_key="sk-xxxxxxxxxx",
        base_url="https://api.mixroute.ai/v1"
    )

    # 非流式
    completion = client.chat.completions.create(
        model="gpt-5.5",
        messages=[
            {"role": "system", "content": "你是一个有用的助手"},
            {"role": "user", "content": "请用中文简要介绍人工智能"}
        ],
        temperature=0.7
    )
    print(completion.choices[0].message.content)

    # 流式
    stream = client.chat.completions.create(
        model="doubao-seed-1-8-251228",
        messages=[
            {"role": "user", "content": "请用中文简要介绍人工智能"}
        ],
        stream=True
    )
    for chunk in stream:
        if chunk.choices[0].delta.content:
            print(chunk.choices[0].delta.content, end="")
    ```
  </Tab>
</Tabs>

## 高级功能

<Tabs>
  <Tab title="工具调用">
    支持 OpenAI 兼容的工具调用格式：

    ```shellscript theme={null}
    curl -X POST "https://api.mixroute.ai/v1/chat/completions" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer sk-xxxxxxxxxx" \
      -d '{
        "model": "gpt-5.5",
        "messages": [
          {"role": "user", "content": "上海的天气怎么样？"}
        ],
        "tools": [
          {
            "type": "function",
            "function": {
              "name": "get_weather",
              "description": "根据城市获取天气信息",
              "parameters": {
                "type": "object",
                "properties": {
                  "city": {"type": "string"}
                },
                "required": ["city"]
              }
            }
          }
        ],
        "tool_choice": "auto"
      }'
    ```
  </Tab>

  <Tab title="结构化输出">
    使用 JSON Schema 约束模型输出格式：

    ```bash theme={null}
    curl -X POST "https://api.mixroute.ai/v1/chat/completions" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer sk-xxxxxxxxxx" \
      -d '{
        "model": "gpt-5.5",
        "response_format": {
          "type": "json_schema",
          "json_schema": {
            "name": "Answer",
            "schema": {
              "type": "object",
              "properties": {
                "summary": {"type": "string"}
              },
              "required": ["summary"]
            }
          }
        },
        "messages": [
          {"role": "user", "content": "返回一个包含 summary 字段的 JSON"}
        ]
      }'
    ```
  </Tab>

  <Tab title="思考能力">
    <Tabs>
      <Tab title="DeepSeek">
        DeepSeek 系列支持深度思考能力：

        ```bash theme={null}
        curl -X POST "https://api.mixroute.ai/v1/chat/completions" \
          -H "Content-Type: application/json" \
          -H "Authorization: Bearer sk-xxxxxxxxxx" \
          -d '{
            "model": "deepseek-v4-pro",
            "messages": [
              {"role": "user", "content": "请分析这道数学题：如果 x^2 + 2x - 3 = 0，求 x 的值"}
            ],
            "temperature": 0.6
          }'
        ```

        响应将包含 `reasoning_content` 字段展示思考过程。
      </Tab>

      <Tab title="通义千问">
        通义千问 Qwen 系列支持思考能力：

        ```bash theme={null}
        curl -X POST "https://api.mixroute.ai/v1/chat/completions" \
          -H "Content-Type: application/json" \
          -H "Authorization: Bearer sk-xxxxxxxxxx" \
          -d '{
            "model": "qwen3.7-max",
            "messages": [
              {"role": "user", "content": "分析一下人工智能的发展趋势"}
            ],
            "enable_thinking": true
          }'
        ```
      </Tab>

      <Tab title="GPT-5.6">
        GPT-5.6 系列 (`gpt-5.6-sol` / `gpt-5.6-terra` / `gpt-5.6-luna`) 支持高级推理配置：

        * `reasoning.mode` — 执行模式：`"standard"`（默认）或 `"pro"`。Pro Mode 执行更多推理工作，提升困难任务可靠性
        * `reasoning.effort` — 推理强度：`none` / `low` / `medium` / `high` / `xhigh` / `max`（`max` 为新增档位）

        ```bash theme={null}
        curl https://api.mixroute.ai/v1/responses \
          -H "Content-Type: application/json" \
          -H "Authorization: Bearer sk" \
          -d '{
            "model": "gpt-5.6-luna",
            "reasoning": {
              "mode": "pro",
        	"effort":"max"
            },
            "input": "Analyze the potential risks of this database migration plan."
          }'
        ```
      </Tab>

      <Tab title="Gemini">
        Gemini 2.0 Flash Thinking 支持思考能力：

        ```bash theme={null}
        curl -X POST "https://api.mixroute.ai/v1/chat/completions" \
          -H "Content-Type: application/json" \
          -H "Authorization: Bearer sk-xxxxxxxxxx" \
          -d '{
            "model": "gemini-2.0-flash-thinking-exp",
            "messages": [
              {"role": "user", "content": "解释量子计算的基本原理"}
            ]
          }'
        ```
      </Tab>
    </Tabs>
  </Tab>

  <Tab title="通义千问扩展">
    通义千问支持额外的扩展参数：

    ```bash theme={null}
    curl -X POST "https://api.mixroute.ai/v1/chat/completions" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer sk-xxxxxxxxxx" \
      -d '{
        "model": "qwen3.7-max",
        "messages": [
          {"role": "user", "content": "你好"}
        ],
        "enable_search": true,
        "search_options": {
          "search_strategy": "standard",
          "forced_search": false
        }
      }'
    ```

    | 参数                               | 说明                    |
    | -------------------------------- | --------------------- |
    | `enable_search`                  | 启用联网搜索                |
    | `search_options.search_strategy` | 搜索策略：`standard`/`pro` |
    | `search_options.forced_search`   | 强制搜索                  |
  </Tab>

  <Tab title="联网搜索">
    <Tabs>
      <Tab title="Claude 搜索">
        Claude 模型支持联网搜索功能：

        ```bash theme={null}
        curl -X POST "https://api.mixroute.ai/v1/chat/completions" \
          -H "Content-Type: application/json" \
          -H "Authorization: Bearer sk-xxxxxxxxxx" \
          -d '{
            "model": "claude-sonnet-5",
            "messages": [
              {"role": "user", "content": "今天有什么重大新闻？"}
            ],
            "tools": [
              {
                "type": "web_search_20250305",
                "name": "web_search",
                "max_uses": 5
              }
            ]
          }'
        ```
      </Tab>

      <Tab title="Grok 搜索">
        Grok 模型支持实时联网搜索：

        ```bash theme={null}
        curl -X POST "https://api.mixroute.ai/v1/chat/completions" \
          -H "Content-Type: application/json" \
          -H "Authorization: Bearer sk-xxxxxxxxxx" \
          -d '{
            "model": "grok-3",
            "messages": [
              {"role": "user", "content": "最新的科技新闻有哪些？"}
            ],
            "search_parameters": {
              "mode": "auto",
              "return_citations": true
            }
          }'
        ```
      </Tab>
    </Tabs>
  </Tab>

  <Tab title="GPT 文件输入">
    GPT 模型支持直接处理文件内容：

    ```bash theme={null}
    curl -X POST "https://api.mixroute.ai/v1/chat/completions" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer sk-xxxxxxxxxx" \
      -d '{
        "model": "gpt-5.5",
        "messages": [
          {
            "role": "user",
            "content": [
              {"type": "text", "text": "请分析这个文档的内容"},
              {
                "type": "file",
                "file": {
                  "url": "https://example.com/document.pdf"
                }
              }
            ]
          }
        ]
      }'
    ```

    支持的文件类型包括 PDF、Word、Excel、图片等。

    <Tip>
      模型文件处理能力有一定差别，请留意选择支持上传文件类型的模型。
    </Tip>
  </Tab>

  <Tab title="Grok 推理">
    Grok 模型支持增强推理能力：

    ```bash theme={null}
    curl -X POST "https://api.mixroute.ai/v1/chat/completions" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer sk-xxxxxxxxxx" \
      -d '{
        "model": "grok-3-mini",
        "messages": [
          {"role": "user", "content": "分析以下逻辑问题：如果所有A都是B，且所有B都是C，那么..."}
        ],
        "reasoning_effort": "high"
      }'
    ```

    | reasoning\_effort | 说明        |
    | ----------------- | --------- |
    | `low`             | 快速响应，基础推理 |
    | `medium`          | 平衡模式      |
    | `high`            | 深度推理，更精确  |
  </Tab>
</Tabs>

## 响应格式

<Tabs>
  <Tab title="非流式响应">
    ```json theme={null}
    {
      "id": "chatcmpl-xxx",
      "object": "chat.completion",
      "created": 1234567890,
      "model": "gpt-5.5",
      "choices": [
        {
          "index": 0,
          "message": {
            "role": "assistant",
            "content": "回复内容..."
          },
          "finish_reason": "stop"
        }
      ],
      "usage": {
        "prompt_tokens": 25,
        "completion_tokens": 100,
        "total_tokens": 125
      }
    }
    ```
  </Tab>

  <Tab title="流式响应">
    流式响应使用 Server-Sent Events (SSE) 格式：

    ```text theme={null}
    data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","created":1234567890,"model":"gpt-4o","choices":[{"index":0,"delta":{"role":"assistant","content":"你"},"finish_reason":null}]}

    data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","created":1234567890,"model":"gpt-4o","choices":[{"index":0,"delta":{"content":"好"},"finish_reason":null}]}

    data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","created":1234567890,"model":"gpt-4o","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}

    data: [DONE]
    ```

    每个 chunk 包含增量内容，最后以 `[DONE]` 结束。
  </Tab>
</Tabs>

## 错误处理

| 异常类型                | 触发场景        |
| ------------------- | ----------- |
| AuthenticationError | API密钥无效或未授权 |
| NotFoundError       | 模型不存在或不被支持  |
| APIConnectionError  | 网络中断或服务器未响应 |
| RateLimitError      | 请求频率超限      |

<RequestExample>
  ```bash cURL theme={null}
  curl --request POST \
    --url https://api.mixroute.ai/v1/chat/completions \
    --header 'Authorization: Bearer sk-xxxxxxxxxx' \
    --header 'Content-Type: application/json' \
    --data '{
      "model": "gpt-5.5",
      "messages": [
        {"role": "system", "content": "你是一个有用的助手"},
        {"role": "user", "content": "请用中文简要介绍人工智能"}
      ],
      "temperature": 0.7
    }'
  ```

  ```python Python theme={null}
  from openai import OpenAI

  client = OpenAI(
      api_key="sk-xxxxxxxxxx",
      base_url="https://api.mixroute.ai/v1"
  )

  response = client.chat.completions.create(
      model="gpt-5.5",
      messages=[
          {"role": "system", "content": "你是一个有用的助手"},
          {"role": "user", "content": "请用中文简要介绍人工智能"}
      ],
      temperature=0.7
  )
  print(response.choices[0].message.content)
  ```

  ```javascript JavaScript theme={null}
  const OpenAI = require('openai');

  const client = new OpenAI({
    apiKey: 'sk-xxxxxxxxxx',
    baseURL: 'https://api.mixroute.ai/v1'
  });

  const response = await client.chat.completions.create({
    model: 'gpt-5.5',
    messages: [
      { role: 'system', content: '你是一个有用的助手' },
      { role: 'user', content: '请用中文简要介绍人工智能' }
    ],
    temperature: 0.7
  });
  console.log(response.choices[0].message.content);
  ```

  ```php PHP theme={null}
  <?php
  $client = new GuzzleHttp\Client();
  $response = $client->post('https://api.mixroute.ai/v1/chat/completions', [
      'headers' => [
          'Authorization' => 'Bearer sk-xxxxxxxxxx',
          'Content-Type' => 'application/json',
      ],
      'json' => [
          'model' => 'gpt-5.5',
          'messages' => [
              ['role' => 'system', 'content' => '你是一个有用的助手'],
              ['role' => 'user', 'content' => '请用中文简要介绍人工智能']
          ],
          'temperature' => 0.7
      ]
  ]);
  echo $response->getBody();
  ```

  ```go Go theme={null}
  package main

  import (
      "context"
      "fmt"
      openai "github.com/sashabaranov/go-openai"
  )

  func main() {
      config := openai.DefaultConfig("sk-xxxxxxxxxx")
      config.BaseURL = "https://api.mixroute.ai/v1"
      client := openai.NewClientWithConfig(config)

      resp, _ := client.CreateChatCompletion(
          context.Background(),
          openai.ChatCompletionRequest{
              Model: "gpt-5.5",
              Messages: []openai.ChatCompletionMessage{
                  {Role: "system", Content: "你是一个有用的助手"},
                  {Role: "user", Content: "请用中文简要介绍人工智能"},
              },
          },
      )
      fmt.Println(resp.Choices[0].Message.Content)
  }
  ```

  ```java Java theme={null}
  import com.theokanning.openai.OpenAiService;
  import com.theokanning.openai.completion.chat.*;

  OpenAiService service = new OpenAiService("sk-xxxxxxxxxx");
  ChatCompletionRequest request = ChatCompletionRequest.builder()
      .model("gpt-5.5")
      .messages(Arrays.asList(
          new ChatMessage("system", "你是一个有用的助手"),
          new ChatMessage("user", "请用中文简要介绍人工智能")
      ))
      .temperature(0.7)
      .build();
  ChatCompletionResult result = service.createChatCompletion(request);
  System.out.println(result.getChoices().get(0).getMessage().getContent());
  ```

  ```ruby Ruby theme={null}
  require 'openai'

  client = OpenAI::Client.new(
    access_token: 'sk-xxxxxxxxxx',
    uri_base: 'https://api.mixroute.ai/v1'
  )

  response = client.chat(
    parameters: {
      model: 'gpt-5.5',
      messages: [
        { role: 'system', content: '你是一个有用的助手' },
        { role: 'user', content: '请用中文简要介绍人工智能' }
      ],
      temperature: 0.7
    }
  )
  puts response.dig('choices', 0, 'message', 'content')
  ```
</RequestExample>

<ResponseExample>
  ```json Response theme={null}
  {
    "id": "chatcmpl-xxx",
    "object": "chat.completion",
    "created": 1234567890,
    "model": "gpt-5.5",
    "choices": [
      {
        "index": 0,
        "message": {
          "role": "assistant",
          "content": "人工智能是研究、开发用于模拟、延伸和扩展人的智能的理论、方法、技术及应用系统的一门新的技术科学..."
        },
        "finish_reason": "stop"
      }
    ],
    "usage": {
      "prompt_tokens": 25,
      "completion_tokens": 100,
      "total_tokens": 125
    }
  }
  ```
</ResponseExample>
