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

# OpenAI 對話格式

> OpenAI-compatible Chat Completions for standard multi-turn chat, structured output, and tool calling. Model names use the `provider/model-name` format, for example `openai/gpt-4o`. Image-capable models can also return generated images through this endpoint.

本頁使用與 [建立對話補全](/zh-Hant/api-reference/chat/create-chat-completion) 相同的 `chat/completions` 操作，上方 playground 已預先填入通用對話結構。以下說明如何從相容 OpenAI 的用戶端，透過這個端點請求由 Gemini 驅動的圖像生成。

<Note>
  請在 `model` 中指定圖像生成模型（例如 `gemini-2.0-flash-preview-image-generation`），依需求設定 `stream`，並透過 `messages` 提供 prompt。你也可以選擇加入 `contents`，搭配 `messages` 提供額外的 Gemini 風格多模態上下文。
</Note>

### 供應商特定說明

| 欄位                   | 類型     | 必填 | 說明                                                        |
| -------------------- | ------ | -- | --------------------------------------------------------- |
| `model`              | string | 是  | 圖像生成模型識別碼，例如 `gemini-2.0-flash-preview-image-generation`。 |
| `messages[].content` | string | 是  | 描述目標圖像的 prompt 文字。                                        |
| `contents`           | array  | 否  | 額外多模態上下文的 Gemini 風格內容陣列，並非標準 OpenAI 對話結構的一部分。             |

<Tip>
  `contents` 欄位是 DGrid 疊加在標準 chat completions 結構上的延伸。當目標模型支援時，它可讓你在 OpenAI 風格的 `messages` 陣列之外，再傳送 Gemini 原生的 `parts`（例如 `inlineData`）。
</Tip>

### 範例：請求圖像

```json theme={null}
{
  "model": "gemini-2.0-flash-preview-image-generation",
  "stream": false,
  "messages": [
    {
      "role": "user",
      "content": "Generate an image of a futuristic city skyline at sunset."
    }
  ]
}
```

### 回應欄位

回應遵循標準 chat completions 結構。生成圖像會直接嵌入在 assistant 訊息內容中：

<ResponseField name="choices" type="array">
  回傳的 choice 條目。

  <Expandable title="choice properties">
    <ResponseField name="index" type="integer">
      Choice 索引。
    </ResponseField>

    <ResponseField name="message" type="object">
      Assistant 訊息物件。

      <Expandable title="message properties">
        <ResponseField name="role" type="string">
          訊息角色，通常為 `assistant`。
        </ResponseField>

        <ResponseField name="content" type="string">
          訊息內容。對於圖像輸出模型，這裡通常是 markdown 圖像參照，會以 base64 data URI 內嵌生成圖像，例如 `![generated image](data:image/png;base64,...)`。
        </ResponseField>
      </Expandable>
    </ResponseField>

    <ResponseField name="finish_reason" type="string">
      完成原因，例如 `stop`。
    </ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="usage" type="object">
  Token 使用摘要。
</ResponseField>

### 回應範例

```json 200 theme={null}
{
  "id": "chatcmpl-abc123",
  "model": "gemini-2.0-flash-preview-image-generation",
  "object": "chat.completion",
  "created": 1719859200,
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "![generated image](data:image/png;base64,<base64-encoded-image-bytes>)"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 12,
    "completion_tokens": 0,
    "total_tokens": 12
  }
}
```


## OpenAPI

````yaml api-reference/openapi.json POST /v1/chat/completions
openapi: 3.1.0
info:
  title: DGrid AI Gateway API
  description: >-
    A single, unified API to access 200+ leading AI models. OpenAI-, Claude-,
    and Gemini-compatible endpoints for chat, completions, embeddings, images,
    audio, and moderations.
  version: 1.0.0
  contact:
    name: DGrid AI
    url: https://dgrid.ai
servers:
  - url: https://api.dgrid.ai
    description: DGrid AI Gateway
security:
  - bearerAuth: []
paths:
  /v1/chat/completions:
    post:
      tags:
        - Chat
      summary: Create chat completion
      description: >-
        OpenAI-compatible Chat Completions for standard multi-turn chat,
        structured output, and tool calling. Model names use the
        `provider/model-name` format, for example `openai/gpt-4o`. Image-capable
        models can also return generated images through this endpoint.
      operationId: createChatCompletion
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - model
                - messages
              properties:
                model:
                  type: string
                  description: Target model ID in `provider/model-name` format.
                  example: openai/gpt-4o
                messages:
                  type: array
                  description: Conversation message list.
                  items:
                    type: object
                    required:
                      - role
                      - content
                    properties:
                      role:
                        type: string
                        enum:
                          - system
                          - user
                          - assistant
                          - tool
                        description: Message author role.
                      content:
                        type: string
                        description: Message content.
                      name:
                        type: string
                        description: Optional participant name.
                      tool_calls:
                        type: array
                        description: Tool invocation payloads.
                        items:
                          type: object
                      tool_call_id:
                        type: string
                        description: Tool call identifier.
                temperature:
                  type: number
                  default: 1
                  description: Sampling temperature.
                top_p:
                  type: number
                  default: 1
                  description: Nucleus sampling value.
                'n':
                  type: integer
                  default: 1
                  description: Number of choices to generate.
                stream:
                  type: boolean
                  default: false
                  description: Enable SSE streaming.
                max_tokens:
                  type: integer
                  description: Maximum token count.
                max_completion_tokens:
                  type: integer
                  description: Max completion-only tokens.
                presence_penalty:
                  type: number
                  default: 0
                  description: Presence penalty.
                frequency_penalty:
                  type: number
                  default: 0
                  description: Frequency penalty.
                logit_bias:
                  type: object
                  description: Token bias configuration.
                stop:
                  description: Stop sequence string or array.
                  oneOf:
                    - type: string
                    - type: array
                      items:
                        type: string
                tools:
                  type: array
                  description: Tool definitions.
                  items:
                    type: object
                tool_choice:
                  description: Tool selection behavior. Defaults to `auto`.
                  oneOf:
                    - type: string
                    - type: object
                response_format:
                  type: object
                  description: Response schema or JSON mode config.
                seed:
                  type: integer
                  description: Deterministic seed.
                user:
                  type: string
                  description: End-user identifier.
            example:
              model: openai/gpt-4o
              messages:
                - role: user
                  content: What is the meaning of life?
      responses:
        '200':
          description: Chat completion result.
          content:
            application/json:
              schema:
                type: object
                properties:
                  id:
                    type: string
                    description: Completion identifier.
                  object:
                    type: string
                    description: Always `chat.completion`.
                  created:
                    type: integer
                    description: Creation timestamp.
                  model:
                    type: string
                    description: Model that served the request.
                  choices:
                    type: array
                    description: Returned choices.
                    items:
                      type: object
                      properties:
                        index:
                          type: integer
                          description: Choice index.
                        message:
                          type: object
                          description: Assistant message object.
                          properties:
                            role:
                              type: string
                              description: Response role.
                            content:
                              type: string
                              description: Response text.
                            reasoning_content:
                              type: string
                              description: Reasoning trace for reasoning models.
                            tool_calls:
                              type: array
                              description: Tool call payloads.
                              items:
                                type: object
                        finish_reason:
                          type: string
                          description: '`stop`, `length`, `content_filter`, or `tool_calls`.'
                  usage:
                    $ref: '#/components/schemas/Usage'
                  system_fingerprint:
                    type: string
        '400':
          $ref: '#/components/responses/BadRequest'
        '429':
          $ref: '#/components/responses/RateLimited'
components:
  schemas:
    Usage:
      type: object
      description: Token usage breakdown.
      properties:
        prompt_tokens:
          type: integer
        completion_tokens:
          type: integer
        total_tokens:
          type: integer
        prompt_tokens_details:
          type: object
          properties:
            cached_tokens:
              type: integer
            text_tokens:
              type: integer
            audio_tokens:
              type: integer
            image_tokens:
              type: integer
        completion_tokens_details:
          type: object
          properties:
            text_tokens:
              type: integer
            audio_tokens:
              type: integer
            reasoning_tokens:
              type: integer
    Error:
      type: object
      properties:
        error:
          type: object
          properties:
            message:
              type: string
            type:
              type: string
            param:
              type: string
            code:
              type: string
  responses:
    BadRequest:
      description: Invalid request.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
    RateLimited:
      description: Rate limit exceeded.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      description: >-
        Your DGrid API key. All endpoints use `Authorization: Bearer
        <DGRID_API_KEY>`.

````