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

# OpenAI Chat Completions 协议

<RequestExample>
  ```bash curl theme={"theme":{"light":"min-light","dark":"min-dark"}}
  curl https://api.poixe.com/v1/chat/completions \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $POIXE_API_KEY" \
    -d '{
      "model": "gpt-5.2",
      "messages": [
        {
          "role": "system",
          "content": "You are a helpful assistant."
        },
        {
          "role": "user",
          "content": "Hello!"
        }
      ],
      "stream": false
    }'
  ```

  ```javascript javascript theme={"theme":{"light":"min-light","dark":"min-dark"}}
  import OpenAI from "openai";

  const openai = new OpenAI({
    apiKey: "POIXE_API_KEY",
    baseURL: "https://api.poixe.com/v1",
  });

  async function main() {
    const completion = await openai.chat.completions.create({
      model: "gpt-5.2",
      messages: [
        { role: "system", content: "You are a helpful assistant." },
        { role: "user", content: "Hello!" },
      ],
    });

    console.log(completion.choices[0].message.content);
  }

  main();
  ```

  ```python python theme={"theme":{"light":"min-light","dark":"min-dark"}}
  from openai import OpenAI

  client = OpenAI(
    api_key="POIXE_API_KEY", 
    base_url="https://api.poixe.com/v1",
  )

  completion = client.chat.completions.create(
      model="gpt-5.2",
      messages=[
          {"role": "system", "content": "You are a helpful assistant."},
          {"role": "user", "content": "Hello!"},
      ],
  )

  print(completion.choices[0].message.content)
  ```

  ```go golang theme={"theme":{"light":"min-light","dark":"min-dark"}}
  package main

  import (
  	"context"
  	"fmt"

  	"github.com/sashabaranov/go-openai"
  )

  func main() {
  	newConfig := openai.DefaultConfig("POIXE_API_KEY")
  	newConfig.BaseURL = "https://api.poixe.com/v1"
  	client := openai.NewClientWithConfig(newConfig)

  	resp, err := client.CreateChatCompletion(
  		context.Background(),
  		openai.ChatCompletionRequest{
  			Model: "gpt-5.2",
  			Messages: []openai.ChatCompletionMessage{
  				{
  					Role:    openai.ChatMessageRoleSystem,
  					Content: "You are a helpful assistant.",
  				},
  				{
  					Role:    openai.ChatMessageRoleUser,
  					Content: "Hello!",
  				},
  			},
  		},
  	)

  	if err != nil {
  		fmt.Printf("ChatCompletion error: %v", err)
  		return
  	}

  	fmt.Println(resp.Choices[0].Message.Content)
  }
  ```
</RequestExample>

<ResponseExample>
  ```json response theme={"theme":{"light":"min-light","dark":"min-dark"}}
  {
    "id": "chatcmpl-Cw5tpkFF274DThTnfODqT87jH15IQ",
    "object": "chat.completion",
    "created": 1767961737,
    "model": "gpt-5.2-2025-12-11",
    "choices": [
      {
        "index": 0,
        "message": {
          "role": "assistant",
          "content": "Hello! What can I help you with today?",
          "refusal": null,
          "annotations": []
        },
        "finish_reason": "stop"
      }
    ],
    "usage": {
      "prompt_tokens": 18,
      "completion_tokens": 13,
      "total_tokens": 31,
      "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",
    "system_fingerprint": null
  }
  ```

  ```json response stream theme={"theme":{"light":"min-light","dark":"min-dark"}}
  data: {"id":"chatcmpl-Cw5xXkcfiYzpGqVIilsB8Q9UnOp3Q","object":"chat.completion.chunk","created":1767961967,"model":"gpt-5.2-2025-12-11","service_tier":"default","system_fingerprint":null,"choices":[{"index":0,"delta":{"role":"assistant","content":"","refusal":null},"finish_reason":null}],"usage":null,"obfuscation":"9FU07UwM"}

  data: {"id":"chatcmpl-Cw5xXkcfiYzpGqVIilsB8Q9UnOp3Q","object":"chat.completion.chunk","created":1767961967,"model":"gpt-5.2-2025-12-11","service_tier":"default","system_fingerprint":null,"choices":[{"index":0,"delta":{"content":"Hello"},"finish_reason":null}],"usage":null,"obfuscation":"ys8pW"}

  ....

  data: {"id":"chatcmpl-Cw5xXkcfiYzpGqVIilsB8Q9UnOp3Q","object":"chat.completion.chunk","created":1767961967,"model":"gpt-5.2-2025-12-11","service_tier":"default","system_fingerprint":null,"choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":null,"obfuscation":"l5BE"}

  data: {"id":"chatcmpl-Cw5xXkcfiYzpGqVIilsB8Q9UnOp3Q","object":"chat.completion.chunk","created":1767961967,"model":"gpt-5.2-2025-12-11","service_tier":"default","system_fingerprint":null,"choices":[],"usage":{"prompt_tokens":18,"completion_tokens":13,"total_tokens":31,"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}},"obfuscation":"jDHNBhRD2"}
  ```
</ResponseExample>

<div className="inline-flex flex-wrap items-center gap-4 rounded-lg border px-3 py-2">
  <Badge color="gray">POST</Badge>
  `https://api.poixe.com/v1/chat/completions`
</div>

这是 OpenAI 最早、最经典的对话协议，目前兼容性最好，几乎所有厂商与 SDK 都支持。

但它的能力相对有限，OpenAI 新推出的模型有许多新特性更倾向在 [**Responses** 协议](/cn/api-reference/text-api/openai-responses) 中提供。如果只是轻量对话与基础流式输出，用它就足够。

## 鉴权与请求头

所有 API 请求都必须在 HTTP Header 中包含您的 API 密钥。

<ParamField header="Authorization" type="string" required>
  Bearer Token。格式为 `Bearer YOUR_API_KEY`。
</ParamField>

<ParamField header="Content-Type" type="string" required>
  必须设置为 `application/json`。
</ParamField>

## 请求参数

以下是构建对话请求时最常用的核心参数。

<ParamField body="model" type="string" required>
  请求的模型名称。例如：`gpt-4o`, `gpt-4o-mini` 等。
</ParamField>

<ParamField body="messages" type="object[]" required>
  对话消息列表。

  <Expandable title="messages[] 字段">
    <ParamField body="role" type="string" required>
      角色，可选值：`system` (系统提示), `user` (用户), `assistant` (模型回复), `tool` (工具结果)。
    </ParamField>

    <ParamField body="content" type="string or array" required>
      消息内容。对于多模态模型，这里可以是一个包含文本和图象 URL 的数组。
    </ParamField>

    <ParamField body="name" type="string">
      可选：参与者名称，用于区分同 role 的不同发送者（或 tool 名称）。
    </ParamField>
  </Expandable>
</ParamField>

<ParamField body="stream" type="boolean" default="false">
  是否流式输出。开启后，服务器将通过 SSE (Server-Sent Events) 逐字发送 Token。
</ParamField>

<ParamField body="temperature" type="number" default="1">
  采样温度（0\~2）。较低的值（如 0.2）使输出更聚焦且确定；较高的值（如 0.8）使输出更具创意和随机性。
</ParamField>

<ParamField body="top_p" type="number" default="1">
  核采样（nucleus sampling）。通常与 `temperature` 二选一调整即可。
</ParamField>

<ParamField body="max_completion_tokens" type="integer">
  模型生成内容的最大 Token 限制（包含推理 Token）。建议用于替代已弃用的 `max_tokens`。
</ParamField>

<ParamField body="n" type="integer" default="1">
  返回多少个候选回复（choices）。为降低成本建议保持 `1`。
</ParamField>

<ParamField body="presence_penalty" type="number" default="0">
  话题惩罚（-2\~2）：鼓励生成新话题（更少重复）。
</ParamField>

<ParamField body="frequency_penalty" type="number" default="0">
  频率惩罚（-2\~2）：降低重复用词/句子的概率。
</ParamField>

<ParamField body="tools" type="object[]">
  工具列表（函数调用）。

  <Expandable title="tools[] 字段">
    <ParamField body="type" type="string" required>
      常用：`function`
    </ParamField>

    <ParamField body="function" type="object" required>
      函数定义（JSON Schema）。

      <Expandable title="function 字段">
        <ParamField body="name" type="string" required>函数名</ParamField>
        <ParamField body="description" type="string">函数描述</ParamField>
        <ParamField body="parameters" type="object">参数 Schema</ParamField>
      </Expandable>
    </ParamField>
  </Expandable>
</ParamField>

<ParamField body="tool_choice" type="string | object">
  工具调用策略：`none` / `auto` / `required`，或强制指定某个 tool。
</ParamField>

<ParamField body="response_format" type="object">
  输出格式控制。

  <Expandable title="response_format 字段">
    <ParamField body="type" type="string" required>
      常用：`text` / `json_object`（需要稳定 JSON 时使用）
    </ParamField>
  </Expandable>
</ParamField>

## 响应结构

接口返回一个包含生成结果及消耗统计的对象。

<ResponseField name="id" type="string">
  本次请求的唯一标识符。
</ResponseField>

<ResponseField name="object" type="string">
  对象类型，通常为 `chat.completion`。
</ResponseField>

<ResponseField name="created" type="integer">
  创建时间（Unix 秒级时间戳）。
</ResponseField>

<ResponseField name="model" type="string">
  实际处理请求的模型名称。
</ResponseField>

<ResponseField name="choices" type="object[]">
  生成结果列表（通常只有 1 条）。

  <Expandable title="choices[] 字段">
    <ResponseField name="index" type="integer">候选索引</ResponseField>

    <ResponseField name="message" type="object">
      模型回复消息对象。

      <Expandable title="message 字段">
        <ResponseField name="role" type="string">一般为 `assistant`</ResponseField>
        <ResponseField name="content" type="string">生成的文本内容</ResponseField>
        <ResponseField name="tool_calls" type="object[]">工具调用请求（如有）</ResponseField>
      </Expandable>
    </ResponseField>

    <ResponseField name="finish_reason" type="string">
      停止原因：`stop` / `length` / `tool_calls`
    </ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="usage" type="object">
  Token 用量统计（如有返回）。

  <Expandable title="usage 字段">
    <ResponseField name="prompt_tokens" type="integer">输入消耗</ResponseField>
    <ResponseField name="completion_tokens" type="integer">输出消耗</ResponseField>
    <ResponseField name="total_tokens" type="integer">总消耗</ResponseField>
  </Expandable>
</ResponseField>

<br />

<CardGroup cols={1}>
  <Card title="官方文档：Create chat completion" href="https://platform.openai.com/docs/api-reference/chat/create">
    查看 OpenAI 官方参数说明与示例。
  </Card>
</CardGroup>
