> 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/sdk-yu-qian-yi/python.md).

# Python

使用 Python 搭配 `requests` 函式庫向 ApiSmart API 發送請求。

本指南示範 Chat Completions、圖片生成和影片生成的基本設定。

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

***

### 開始之前

請確認你具備：

* 已安裝 Python 3
* 一個已啟用的 **API 權杖**
* 充足的 **目前餘額**
* 一個有效的 **模型 ID**

安裝 `requests`:

```bash
pip install requests
```

將您的 API Token 設為環境變數：

```bash
export APISMART_API_KEY="YOUR_API_KEY"
```

在 PowerShell 中：

```powershell
$env:APISMART_API_KEY="YOUR_API_KEY"
```

***

### 基本設定

```python
import os
import requests

api_key = os.getenv("APISMART_API_KEY")

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

headers = {
    "Authorization": f"Bearer {api_key}",
    "Content-Type": "application/json",
}
```

對受支援的 ApiSmart 端點使用相同的驗證標頭。

***

### 聊天完成

```python
response = requests.post(
    "https://gw.apismart.ai/v1/chat/completions",
    headers=headers,
    json={
        "model": "YOUR_MODEL_ID",
        "messages": [
            {
                "role": "user",
                "content": "Hello!",
            }
        ],
    },
    timeout=120,
)

response.raise_for_status()

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

替換 `YOUR_MODEL_ID` 使用所選模型中顯示的確切值 **程式碼範例**.

***

### 圖片生成

```python
response = requests.post(
    "https://gw.apismart.ai/v1/images/generations",
    headers=headers,
    json={
        "model": "YOUR_MODEL_ID",
        "prompt": "A futuristic city at sunset",
    },
    timeout=120,
)

response.raise_for_status()
result = response.json()

print(result)
```

圖片請求與回應欄位可能因模型而異。

***

### 影片生成

影片生成使用非同步任務工作流程。

對於接受以下內容的影片模型 `prompt` 與 `duration`:

```python
response = requests.post(
    "https://gw.apismart.ai/v1/video/tasks",
    headers=headers,
    json={
        "model": "YOUR_MODEL_ID",
        "prompt": "夕陽下的電影感海浪景象",
        "duration": 5,
    },
    timeout=120,
)

response.raise_for_status()
result = response.json()

task_id = result["id"]
print(task_id)
```

檢查任務狀態：

```python
response = requests.get(
    f"https://gw.apismart.ai/v1/video/tasks/{task_id}",
    headers=headers,
    timeout=60,
)

response.raise_for_status()
print(response.json())
```

> ⚠️ **重要：** 請始終使用所選模型中顯示的確切端點、模型 ID、請求欄位和支援值 **程式碼範例**.

***

### 處理 API 錯誤

一個簡單的模式是：

```python
try:
    response.raise_for_status()
    result = response.json()
except requests.RequestException as error:
    print(f"Request failed: {error}")
```

在排查問題時，也請檢視 [**使用紀錄與成本**](/documentation/zh-tw/api-shi-yong/shi-yong-ji-lu-yu-fei-yong.md).

***

### 🛠️ 常見問題

| 問題        | 檢查項目                  |
| --------- | --------------------- |
| **驗證失敗**  | API Token 與 Bearer 標頭 |
| **找不到模型** | 精確的模型 ID 與大小寫         |
| **無效的請求** | 端點與模型特定欄位             |
| **請求逾時**  | 延長用戶端逾時時間，或檢查任務狀態     |
| **餘額不足**  | 目前餘額與 API 權杖剩餘額度      |

> 🔐 切勿在原始碼、日誌、截圖或支援訊息中提供您的完整 API 權杖。

***

### 🚀 下一步

繼續進行：

* [**cURL**](/documentation/zh-tw/sdk-yu-qian-yi/curl.md)
* [**API 基礎**](/documentation/zh-tw/api-zhi-nan/api-ji-chu.md)
* [**Chat Completions API**](/documentation/zh-tw/api-zhi-nan/liao-tian-wan-cheng-api.md)
* [**圖片生成 API**](/documentation/zh-tw/api-zhi-nan/tu-pian-sheng-cheng-api.md)
* [**影片生成 API**](/documentation/zh-tw/api-zhi-nan/ying-pian-sheng-cheng-api.md)
