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

# 创建对话补全

> 为一段对话生成模型回复，支持流式输出。

使用 `Authorization: Bearer $PIPELLM_API_KEY`。`model` 从 [`GET /v1/models`](/zh/api-reference/list-models) 选取。

## 端点

```
POST https://api.pipellm.ai/v1/chat/completions
```

<Note>
  这条 free route 只接受 OpenAI 兼容格式请求，并只路由到 OpenAI 兼容平台。
  如果你想保留 OpenAI 格式去调用 Anthropic 或 Gemini 模型，请使用
  [OpenAI Format Converter](/zh/converter/openai-format)。
</Note>

<RequestExample>
  ```bash cURL theme={"dark"}
  curl https://api.pipellm.ai/v1/chat/completions \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $PIPELLM_API_KEY" \
    -d '{
      "model": "gpt-5",
      "messages": [{"role": "user", "content": "你好"}]
    }'
  ```

  ```python Python theme={"dark"}
  import os
  from openai import OpenAI

  client = OpenAI(
      api_key=os.environ["PIPELLM_API_KEY"],
      base_url="https://api.pipellm.ai/v1",
  )
  print(client.chat.completions.create(
      model="gpt-5",
      messages=[{"role": "user", "content": "你好"}],
  ).choices[0].message.content)
  ```

  ```javascript JavaScript theme={"dark"}
  import OpenAI from "openai";

  const client = new OpenAI({
    apiKey: process.env.PIPELLM_API_KEY,
    baseURL: "https://api.pipellm.ai/v1",
  });
  const response = await client.chat.completions.create({
    model: "gpt-5",
    messages: [{ role: "user", content: "你好" }],
  });
  console.log(response.choices[0].message.content);
  ```
</RequestExample>

## 代码示例

<Tabs>
  <Tab title="cURL">
    ```bash theme={"dark"}
    curl https://api.pipellm.ai/v1/chat/completions \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer $PIPELLM_API_KEY" \
      -d '{
        "model": "gpt-5",
        "max_completion_tokens": 1024,
        "messages": [
          {
            "role": "user",
            "content": "Why is the sky blue?"
          }
        ]
      }'
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={"dark"}
    import os
    from openai import OpenAI

    client = OpenAI(
      api_key=os.getenv('PIPELLM_API_KEY'),
      base_url='https://api.pipellm.ai/v1'
    )

    response = client.chat.completions.create(
      model='gpt-5',
      messages=[
        {
          'role': 'user',
          'content': 'Why is the sky blue?'
        }
      ]
    )
    ```
  </Tab>

  <Tab title="Node.js">
    ```javascript theme={"dark"}
    import OpenAI from 'openai';

    const client = new OpenAI({
      apiKey: process.env.PIPELLM_API_KEY,
      baseURL: 'https://api.pipellm.ai/v1'
    });

    const response = await client.chat.completions.create({
      model: 'gpt-5',
      messages: [
        {
          role: 'user',
          content: 'Why is the sky blue?'
        }
      ]
    });
    ```
  </Tab>

  <Tab title="Go">
    ```go theme={"dark"}
    package main

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

    func main() {
      config := openai.DefaultConfig(os.Getenv("PIPELLM_API_KEY"))
      config.BaseURL = "https://api.pipellm.ai/v1"
      client := openai.NewClientWithConfig(config)

      resp, _ := client.CreateChatCompletion(
        context.Background(),
        openai.ChatCompletionRequest{
          Model: "gpt-5",
          Messages: []openai.ChatCompletionMessage{
            {
              Role:    openai.ChatMessageRoleUser,
              Content: "Why is the sky blue?",
            },
          },
        },
      )
    }
    ```
  </Tab>
</Tabs>

## 请求参数

`model` 从 [`GET /v1/models`](/zh/api-reference/list-models) 选取。原生 `/v1/chat/completions` 只会路由到 OpenAI 兼容平台。

<ParamField body="model" type="string" required>
  当前账号可见的模型 ID。
</ParamField>

<ParamField body="messages" type="array" required>
  对话消息，至少一条。

  <Expandable title="messages[]">
    <ParamField body="role" type="string" required>
      `system`、`user`、`assistant` 或 `tool`。
    </ParamField>

    <ParamField body="content" type="string | array" required>
      纯文本，或内容块数组。

      <Expandable title="content parts">
        <ParamField body="type" type="string" required>
          `text` 或 `image_url`。
        </ParamField>

        <ParamField body="text" type="string">
          `type` 为 `text` 时必填。
        </ParamField>

        <ParamField body="image_url" type="object">
          `type` 为 `image_url` 时必填。`url` 为 HTTPS 或 data URL。
        </ParamField>
      </Expandable>
    </ParamField>

    <ParamField body="name" type="string">
      可选发送者名称。
    </ParamField>

    <ParamField body="tool_call_id" type="string">
      `role` 为 `tool` 时必填。
    </ParamField>
  </Expandable>
</ParamField>

<ParamField body="temperature" type="number">
  采样温度，0–2。默认 `1`。
</ParamField>

<ParamField body="max_tokens" type="integer">
  最大生成 token 数。
</ParamField>

<ParamField body="max_completion_tokens" type="integer">
  较新的 OpenAI 兼容模型优先用这个字段，而不是 `max_tokens`。
</ParamField>

<ParamField body="stream" type="boolean">
  为 `true` 时返回 SSE。见 [流式输出](/zh/api-reference/streaming)。
</ParamField>

<ParamField body="stream_options" type="object">
  流式附加选项。

  <Expandable title="stream_options 字段">
    <ParamField body="include_usage" type="boolean">
      为 `true` 时，最后一条 SSE 分片带 `usage`。
    </ParamField>
  </Expandable>
</ParamField>

<ParamField body="top_p" type="number">
  核采样，0–1。
</ParamField>

<ParamField body="n" type="integer">
  生成条数。默认 `1`。
</ParamField>

<ParamField body="stop" type="string | string[]">
  停止序列，或停止序列列表。
</ParamField>

<ParamField body="presence_penalty" type="number">
  存在惩罚，-2 到 2。默认 `0`。
</ParamField>

<ParamField body="frequency_penalty" type="number">
  频率惩罚，-2 到 2。默认 `0`。
</ParamField>

<ParamField body="tools" type="array">
  模型可调用的函数工具。见 [Function Calling](#function-calling)。

  <Expandable title="tools[]">
    <ParamField body="type" type="string" required>
      固定为 `function`。
    </ParamField>

    <ParamField body="function" type="object" required>
      工具定义。

      <Expandable title="function 字段">
        <ParamField body="name" type="string" required>
          函数名。
        </ParamField>

        <ParamField body="description" type="string">
          函数用途。
        </ParamField>

        <ParamField body="parameters" type="object">
          函数参数的 JSON Schema。
        </ParamField>
      </Expandable>
    </ParamField>
  </Expandable>
</ParamField>

<ParamField body="tool_choice" type="string | object">
  `auto`、`none`，或 `{"type":"function","function":{"name":"..."}}`。
</ParamField>

<ParamField body="user" type="string">
  终端用户标识，用于滥用追踪。
</ParamField>

## 响应格式

```json theme={"dark"}
{
  "id": "chatcmpl-xxx",
  "object": "chat.completion",
  "created": 1234567890,
  "model": "gpt-5",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "The sky appears blue because..."
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 10,
    "completion_tokens": 50,
    "total_tokens": 60
  }
}
```

<ResponseField name="id" type="string">
  补全 ID。
</ResponseField>

<ResponseField name="object" type="string">
  非流式为 `chat.completion`，流式为 `chat.completion.chunk`。
</ResponseField>

<ResponseField name="model" type="string">
  实际生成用的模型。
</ResponseField>

<ResponseField name="choices" type="array">
  生成结果。

  <Expandable title="choices[]">
    <ResponseField name="index" type="integer">
      选项下标。
    </ResponseField>

    <ResponseField name="message" type="object">
      `stream` 为 false 时出现，包含 `role`、`content` 和可选的 `tool_calls`。
    </ResponseField>

    <ResponseField name="delta" type="object">
      流式时出现，是部分的 `role` / `content` / `tool_calls`。
    </ResponseField>

    <ResponseField name="finish_reason" type="string">
      `stop`、`length` 或 `tool_calls`。
    </ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="usage" type="object">
  Token 计数：`prompt_tokens`、`completion_tokens`、`total_tokens`。
</ResponseField>

## 错误

错误信封与 [错误](/zh/api-reference/errors) 相同。

<AccordionGroup>
  <Accordion title="400 invalid_request_error">
    JSON 不合法、缺少 `model` / `messages`，或原生路由协议不匹配。

    ```json theme={"dark"}
    {
      "error": {
        "type": "invalid_request_error",
        "code": "400",
        "message": "The 'model' field is required but was not provided in the request"
      }
    }
    ```
  </Accordion>

  <Accordion title="401 authentication_error">
    缺少或无效的 API Key。

    ```json theme={"dark"}
    {
      "error": {
        "type": "authentication_error",
        "code": "401",
        "message": "Incorrect API key provided. Please visit https://console.pipellm.ai/account/api-keys to find your API key."
      }
    }
    ```
  </Accordion>

  <Accordion title="402 insufficient_balance">
    处理前余额检查失败。

    ```json theme={"dark"}
    {
      "error": {
        "type": "insufficient_balance",
        "code": "402",
        "message": "Insufficient balance. Please recharge your account at https://console.pipellm.ai/billing."
      }
    }
    ```
  </Accordion>

  <Accordion title="429 rate_limit_error">
    账号 RPM 超限。见 [速率限制](/zh/api-reference/rate-limits)。

    ```json theme={"dark"}
    {
      "error": {
        "type": "rate_limit_error",
        "code": "429",
        "message": "Rate limit exceeded. Your current limit is 120 requests per minute (approximately 2.00 requests per second). Please visit https://console.pipellm.ai/billing to upgrade your plan for higher limits."
      }
    }
    ```
  </Accordion>
</AccordionGroup>

## Function Calling

Function Calling 允许模型生成结构化的 JSON 来调用代码中的函数。

<Tabs>
  <Tab title="Python">
    ```python theme={"dark"}
    tools = [
      {
        "type": "function",
        "function": {
          "name": "get_weather",
          "description": "获取指定地点的当前天气",
          "parameters": {
            "type": "object",
            "properties": {
              "location": {"type": "string", "description": "城市名称"}
            },
            "required": ["location"]
          }
        }
      }
    ]

    response = client.chat.completions.create(
      model="gpt-5",
      messages=[{"role": "user", "content": "东京现在天气怎么样？"}],
      tools=tools,
      tool_choice="auto"
    )

    if response.choices[0].message.tool_calls:
      tool_call = response.choices[0].message.tool_calls[0]
      # 执行你的函数并返回结果
    ```
  </Tab>

  <Tab title="Node.js">
    ```javascript theme={"dark"}
    const tools = [
      {
        type: "function",
        function: {
          name: "get_weather",
          description: "获取指定地点的当前天气",
          parameters: {
            type: "object",
            properties: {
              location: { type: "string", description: "城市名称" }
            },
            required: ["location"]
          }
        }
      }
    ];

    const response = await client.chat.completions.create({
      model: 'gpt-5',
      messages: [{ role: 'user', content: '东京现在天气怎么样？' }],
      tools: tools,
      tool_choice: 'auto'
    });

    if (response.choices[0].message.tool_calls) {
      const toolCall = response.choices[0].message.tool_calls[0];
      // 执行你的函数并返回结果
    }
    ```
  </Tab>
</Tabs>

<Card title="Function Calling 官方文档" icon="book" href="https://platform.openai.com/docs/guides/function-calling">
  完整的函数定义和响应处理指南
</Card>


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.