> For the complete documentation index, see [llms.txt](https://docs.apismart.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.apismart.ai/documentation/zh-tw/api-zhi-nan/liao-tian-wan-cheng-api.md).

# 聊天完成 API

使用 Chat Completions API 搭配支援的語言模型產生文字回應。

指定精確的 **模型 ID**，送出一串對話訊息，並以 JSON 格式接收產生的回應。

關於 API 基礎 URL、驗證與一般請求規則，請參閱 [**API 基礎**](/documentation/zh-tw/api-zhi-nan/api-ji-chu.md).

***

### API 端點

```
POST https://gw.apismart.ai/v1/chat/completions
```

必要標頭：

```http
Authorization: Bearer YOUR_API_KEY
Content-Type: application/json
```

> ⚠️ **重要：** 請務必使用所選模型 **程式碼範例**.

***

### 送出基本請求

以下 cURL 範例會送出一則簡單的使用者訊息：

```bash
curl https://gw.apismart.ai/v1/chat/completions \
  -H "Authorization: Bearer $APISMART_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "YOUR_MODEL_ID",
    "messages": [
      {
        "role": "user",
        "content": "請用一句話解釋 ApiSmart。"
      }
    ]
  }'
```

將 `YOUR_MODEL_ID` 替換為所選模型詳細資料頁面上顯示的精確模型 ID。

***

### 理解請求

基本請求通常包含：

| 欄位         | 說明          |
| ---------- | ----------- |
| `model`    | 要使用的精確模型 ID |
| `messages` | 傳送給模型的對話訊息  |

範例：

```json
{
  "model": "YOUR_MODEL_ID",
  "messages": [
    {
      "role": "user",
      "content": "Hello!"
    }
  ]
}
```

每則訊息通常包含：

* `role` — 用於識別訊息傳送者
* `content` — 包含傳送給模型的訊息內容

常見角色可能包括：

```
system
user
assistant
```

可用的角色與訊息格式可能因模型而異。

***

### 可選參數

某些模型可能支援其他欄位，例如：

```json
{
  "temperature": 0.7,
  "max_tokens": 500
}
```

模型也可能提供特定於模型的推理、多模態或生成參數。

不要假設每個語言模型都支援相同的欄位或值。請先檢閱所選模型的 **程式碼範例** ，再加入可選參數。

***

### 讀取回應

成功的回應可能如下：

```json
{
  "choices": [
    {
      "message": {
        "role": "assistant",
        "content": "產生的回應"
      }
    }
  ]
}
```

產生的文字通常可在以下位置取得：

```
choices[0].message.content
```

視模型而定，回應也可能包含：

* 模型資訊
* 使用量資訊
* 結束原因
* 請求識別碼

確切的回應結構可能有所不同。

***

### Python 範例

```python
import os
import requests

api_key = os.getenv("APISMART_API_KEY")

if not api_key:
    raise RuntimeError("未設定 APISMART_API_KEY。")

response = requests.post(
    "https://gw.apismart.ai/v1/chat/completions",
    headers={
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json",
    },
    json={
        "model": "YOUR_MODEL_ID",
        "messages": [
            {
                "role": "user",
                "content": "請用一句話解釋 ApiSmart。",
            }
        ],
    },
    timeout=120,
)

response.raise_for_status()

result = response.json()
print(result["choices"][0]["message"]["content"] )
```

***

### 串流回應

支援的模型可能允許透過加入以下內容，以逐步方式傳回回應：

```json
{
  "stream": true
}
```

串流支援因模型而異。

如需實作細節，請參閱 [**串流回應**](/documentation/zh-tw/api-zhi-nan/hui-ying-mo-shi.md).

***

### 🛠️ 常見問題

| 問題         | 檢查項目                |
| ---------- | ------------------- |
| **驗證失敗**   | API 權杖狀態與 Bearer 標頭 |
| **找不到模型**  | 精確的模型 ID 與大小寫       |
| **無效的請求**  | 必要欄位與模型特定參數         |
| **餘額不足**   | 目前餘額與 API 權杖剩餘額度    |
| **不支援的參數** | 所選模型是否支援該欄位         |

排除問題時，請檢閱中的相關請求 [**使用記錄與費用**](/documentation/zh-tw/api-shi-yong/shi-yong-ji-lu-yu-fei-yong.md) 並儲存 **請求 ID** （若可取得）。

> 🔐 絕對不要向支援人員提供完整的 API 權杖。

***

### 🚀 下一步

繼續進行：

* [**串流回應**](/documentation/zh-tw/api-zhi-nan/hui-ying-mo-shi.md)
* [**選擇模型並找到其模型 ID**](/documentation/zh-tw/mo-xing-yu-ding-jia/mo-xing-yu-mo-xing-id.md)
* [**了解模型定價與計費**](/documentation/zh-tw/mo-xing-yu-ding-jia/mo-xing-ding-jia-yu-ji-fei.md)
* [**使用記錄與費用**](/documentation/zh-tw/api-shi-yong/shi-yong-ji-lu-yu-fei-yong.md)
