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

# Create chat completion

> 用 OpenAI 兼容协议调用 Claude、GPT、Grok 等所有文本模型。

`/v1/chat/completions` 是 DimiLinks 推荐的对话入口。请求与响应结构与 OpenAI 官方接口保持一致，可直接使用 OpenAI SDK；只要把 `model` 换成对应名称，就可以调用 Claude、GPT、Grok 等所有文本模型。

## 请求地址

```http theme={null}
POST https://dimilinks.com/v1/chat/completions
Content-Type: application/json
Authorization: Bearer <DIMILINKS_API_KEY>
```

## 简单示例

```bash theme={null}
curl "https://dimilinks.com/v1/chat/completions" \
  -H "Authorization: Bearer $DIMILINKS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "claude-sonnet-4-6",
    "messages": [
      {"role": "system", "content": "你是一位简洁的中文助手。"},
      {"role": "user", "content": "用一句话解释什么是冥王星。"}
    ]
  }'
```

返回（节选）：

```json theme={null}
{
  "id": "chatcmpl_xxx",
  "object": "chat.completion",
  "created": 1777080000,
  "model": "claude-sonnet-4-6",
  "choices": [
    {
      "index": 0,
      "message": { "role": "assistant", "content": "..." },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 32,
    "completion_tokens": 24,
    "total_tokens": 56
  }
}
```

## 流式输出

请求加上 `"stream": true`，服务端会以 `text/event-stream` 推回增量片段，最后以 `data: [DONE]` 结束。

```bash theme={null}
curl "https://dimilinks.com/v1/chat/completions" \
  -H "Authorization: Bearer $DIMILINKS_API_KEY" \
  -H "Content-Type: application/json" \
  -N \
  -d '{
    "model": "gpt-5.5",
    "stream": true,
    "messages": [
      {"role": "user", "content": "写一首关于深海的四行小诗"}
    ]
  }'
```

每个事件结构：

```text theme={null}
data: {"id":"chatcmpl_xxx","object":"chat.completion.chunk","model":"gpt-5.5",
"choices":[{"index":0,"delta":{"content":"深"},"finish_reason":null}]}
```

## 参数

仅列出常用字段，未列出的字段如果模型支持则原样透传给上游。

| 参数                  | 类型                  | 默认值     | 说明                                                                                          |
| ------------------- | ------------------- | ------- | ------------------------------------------------------------------------------------------- |
| `model`             | string              | 必填      | 模型 ID，例如 `claude-sonnet-4-6`、`claude-opus-4-7`、`gpt-5.5`、`gpt-5.4-mini`、`grok-4.20-fast` 等。 |
| `messages`          | array               | 必填      | 消息数组，至少包含一条 `role=user`。`role` 支持 `system` / `user` / `assistant` / `tool`。                 |
| `stream`            | boolean             | `false` | `true` 时返回 SSE 流式片段。                                                                        |
| `temperature`       | number              | 模型默认    | 采样温度，0–2。                                                                                   |
| `top_p`             | number              | 模型默认    | 核采样概率，0–1。                                                                                  |
| `max_tokens`        | integer             | 模型默认    | 单次输出最大 token；调用 Claude 系模型时建议显式设置。                                                          |
| `stop`              | string \| string\[] | 空       | 命中即停止生成。                                                                                    |
| `presence_penalty`  | number              | `0`     | 重复主题惩罚，-2 到 2。                                                                              |
| `frequency_penalty` | number              | `0`     | 重复词惩罚，-2 到 2。                                                                               |
| `tools`             | array               | 空       | 工具调用定义，结构兼容 OpenAI Tool Calling。                                                            |
| `tool_choice`       | string \| object    | `auto`  | 控制是否强制调用某个工具。                                                                               |
| `response_format`   | object              | 空       | 请求 JSON 输出，例如 `{ "type": "json_object" }`。                                                  |
| `user`              | string              | 空       | 终端用户标识，用于审计与限流。                                                                             |

## 推荐模型

| 场景         | 模型                                                                                 |
| ---------- | ---------------------------------------------------------------------------------- |
| 通用对话 / 长文档 | `claude-sonnet-4-6`、`claude-opus-4-7`、`gpt-5.5`                                    |
| 复杂推理 / 编码  | `claude-opus-4-7`、`gpt-5.3-codex`、`gpt-5.4`                                        |
| 思考模式       | `claude-opus-4-7-thinking`、`claude-sonnet-4-6-thinking`、`grok-4.20-0309-reasoning` |
| 低成本批量      | `claude-haiku-4-5-20251001`、`gpt-5.4-mini`、`deepseek-v4-flash`                     |
| 多模态视觉      | `gpt-image-2`（图片生成专用）；视觉对话能力随模型而定，请先看 `/v1/models` 的 `input_modalities`。           |

## 用 OpenAI SDK 调用

Python：

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

client = OpenAI(
    api_key="sk-...",
    base_url="https://dimilinks.com/v1",
)

response = client.chat.completions.create(
    model="claude-sonnet-4-6",
    messages=[
        {"role": "system", "content": "你是一位严谨的中文助手。"},
        {"role": "user", "content": "解释下傅里叶变换。"},
    ],
    max_tokens=1024,
)

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

Node.js：

```ts theme={null}
import OpenAI from 'openai'

const client = new OpenAI({
  apiKey: process.env.DIMILINKS_API_KEY,
  baseURL: 'https://dimilinks.com/v1',
})

const response = await client.chat.completions.create({
  model: 'gpt-5.5',
  messages: [{ role: 'user', content: '你好' }],
})
```

## 工具调用 (Tool calling)

```bash theme={null}
curl "https://dimilinks.com/v1/chat/completions" \
  -H "Authorization: Bearer $DIMILINKS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "claude-sonnet-4-6",
    "messages": [
      {"role": "user", "content": "帮我查 Tokyo 现在的天气"}
    ],
    "tools": [
      {
        "type": "function",
        "function": {
          "name": "get_weather",
          "description": "查询某个城市的当前天气",
          "parameters": {
            "type": "object",
            "properties": {
              "city": {"type": "string"}
            },
            "required": ["city"]
          }
        }
      }
    ]
  }'
```

模型返回 `tool_calls` 后，再把工具执行结果以 `role=tool` 的消息放回 `messages` 继续调用即可。

## 错误处理

请求失败时返回 OpenAI 风格的 `error` 包装，详见 [Errors](/api-reference/errors)。流式请求中如果上游断开，最后一个事件可能不是 `[DONE]`，建议把「连接断开」也当作可重试错误。


## OpenAPI

````yaml POST /chat/completions
openapi: 3.1.0
info:
  title: DimiLinks API
  description: >-
    DimiLinks unified API for chat (OpenAI-compatible and Anthropic native),
    image generation/editing, and video generation.
  version: 1.1.0
servers:
  - url: https://dimilinks.com/v1
    description: OpenAI 兼容入口：chat completions / images / videos / models / tasks
security:
  - bearerAuth: []
tags:
  - name: Models
  - name: Chat
  - name: Images
  - name: Videos
  - name: Tasks
paths:
  /chat/completions:
    post:
      tags:
        - Chat
      summary: Create chat completion
      description: >-
        OpenAI-compatible chat completions endpoint. Supports Claude / GPT /
        Grok and other text models.
      operationId: createChatCompletion
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ChatCompletionRequest'
      responses:
        '200':
          description: >-
            Chat completion result. When `stream` is true the response is
            text/event-stream.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ChatCompletionResponse'
            text/event-stream:
              schema:
                type: string
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '429':
          $ref: '#/components/responses/RateLimited'
components:
  schemas:
    ChatCompletionRequest:
      type: object
      properties:
        model:
          type: string
          example: claude-sonnet-4-6
        messages:
          type: array
          items:
            $ref: '#/components/schemas/ChatMessage'
        stream:
          type: boolean
          default: false
        temperature:
          type: number
        top_p:
          type: number
        max_tokens:
          type: integer
        stop:
          oneOf:
            - type: string
            - type: array
              items:
                type: string
        presence_penalty:
          type: number
        frequency_penalty:
          type: number
        tools:
          type: array
          items:
            type: object
            additionalProperties: true
        tool_choice:
          oneOf:
            - type: string
            - type: object
              additionalProperties: true
        response_format:
          type: object
          additionalProperties: true
        user:
          type: string
      required:
        - model
        - messages
    ChatCompletionResponse:
      type: object
      properties:
        id:
          type: string
          example: chatcmpl_xxx
        object:
          type: string
          example: chat.completion
        created:
          type: integer
          example: 1777080000
        model:
          type: string
          example: claude-sonnet-4-6
        choices:
          type: array
          items:
            $ref: '#/components/schemas/ChatCompletionChoice'
        usage:
          type: object
          properties:
            prompt_tokens:
              type: integer
            completion_tokens:
              type: integer
            total_tokens:
              type: integer
    ChatMessage:
      type: object
      properties:
        role:
          type: string
          enum:
            - system
            - user
            - assistant
            - tool
        content:
          oneOf:
            - type: string
            - type: array
              items:
                type: object
                additionalProperties: true
        name:
          type: string
        tool_call_id:
          type: string
      required:
        - role
    ChatCompletionChoice:
      type: object
      properties:
        index:
          type: integer
        message:
          $ref: '#/components/schemas/ChatMessage'
        finish_reason:
          type: string
    ErrorResponse:
      type: object
      properties:
        error:
          $ref: '#/components/schemas/ErrorObject'
    ErrorObject:
      type: object
      properties:
        message:
          type: string
        type:
          type: string
          example: invalid_request_error
        code:
          oneOf:
            - type: string
            - type: integer
  responses:
    BadRequest:
      description: Invalid request
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    Unauthorized:
      description: Missing or invalid API key
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    Forbidden:
      description: Model is not allowed for this API key
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    RateLimited:
      description: Rate limit exceeded
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer

````