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

# 金鑰管理

> 建立和管理具有服務商限制、速率限制、消費限額和有效期的 API Key。

## 概覽

ARouter 使用兩種類型的金鑰：

| 金鑰類型        | 前綴             | 用途                            |
| ----------- | -------------- | ----------------------------- |
| **管理金鑰**    | `lr_mgmt_xxxx` | 透過管理 API 建立、列出、更新和刪除 API Key。 |
| **API Key** | `lr_live_xxxx` | 發起 LLM 請求（聊天補全、嵌入等）。          |

管理金鑰可以建立具有範圍存取權限的 API Key：

* **允許的服務商** — 例如只允許 OpenAI 和 Anthropic
* **允許的模型** — 例如只允許 `gpt-5.4` 和 `claude-sonnet-4.6`
* **消費限額** — 每日/每週/每月最大預算
* **有效期** — 到期後自動失效

```
管理金鑰: lr_mgmt_abc123
  ├── API Key 1: lr_live_def456  (OpenAI+Anthropic, $150/月, 2025年12月到期)
  ├── API Key 2: lr_live_ghi789  (僅 DeepSeek, $50/天)
  └── API Key 3: lr_live_jkl012  (所有服務商, 無限額)
```

## 建立 API Key

<Tabs>
  <Tab title="cURL">
    ```bash theme={null}
    curl -X POST https://api.arouter.ai/api/v1/keys \
      -H "Authorization: Bearer lr_mgmt_xxxx" \
      -H "Content-Type: application/json" \
      -d '{
        "name": "production-backend",
        "allowed_providers": ["openai", "anthropic"],
        "allowed_models": ["gpt-5.4", "claude-sonnet-4.6"],
        "limit": 150,
        "limit_reset": "monthly",
        "expires_at": "2025-12-31T23:59:59Z"
      }'
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    import requests

    resp = requests.post(
        "https://api.arouter.ai/api/v1/keys",
        headers={"Authorization": "Bearer lr_mgmt_xxxx"},
        json={
            "name": "production-backend",
            "allowed_providers": ["openai", "anthropic"],
            "limit": 150,
            "limit_reset": "monthly",
            "expires_at": "2025-12-31T23:59:59Z",
        },
    )
    data = resp.json()
    print("API Key:", data["key"])
    ```
  </Tab>

  <Tab title="Go">
    ```go theme={null}
    key, err := client.CreateKey(ctx, &arouter.CreateKeyRequest{
        Name:             "production-backend",
        AllowedProviders: []string{"openai", "anthropic"},
        Limit:            float64Ptr(150),
        LimitReset:       "monthly",
    })
    fmt.Println("API Key:", key.Key)
    ```
  </Tab>

  <Tab title="Node.js">
    ```typescript theme={null}
    const key = await router.createKey({
      name: "production-backend",
      allowed_providers: ["openai", "anthropic"],
      limit: 150,
      limit_reset: "monthly",
    });
    console.log("API Key:", key.key);
    ```
  </Tab>
</Tabs>

<Info>
  `key` 欄位僅在**建立時**回傳**一次**。請安全儲存，之後無法再次取得。
</Info>

## 回應

```json theme={null}
{
  "data": {
    "hash": "abc123...",
    "name": "production-backend",
    "key_type": "regular",
    "disabled": false,
    "limit": 150,
    "limit_remaining": 150,
    "limit_reset": "monthly",
    "allowed_providers": ["openai", "anthropic"],
    "allowed_models": ["gpt-5.4", "claude-sonnet-4.6"],
    "usage": 0,
    "created_at": "2025-01-15T10:30:00Z",
    "expires_at": "2025-12-31T23:59:59Z"
  },
  "key": "lr_live_xxxxxxxxxxxxxxxx"
}
```

## 列出 API Key

```bash theme={null}
curl "https://api.arouter.ai/api/v1/keys?page_size=20" \
  -H "Authorization: Bearer lr_mgmt_xxxx"
```

支援透過 `page_size`、`page_token` 和 `offset` 查詢參數進行分頁。

## 更新 API Key

```bash theme={null}
curl -X PATCH https://api.arouter.ai/api/v1/keys/KEY_HASH \
  -H "Authorization: Bearer lr_mgmt_xxxx" \
  -H "Content-Type: application/json" \
  -d '{"disabled": true}'
```

可以更新 `name`、`disabled`、`limit`、`limit_reset`、`allowed_providers` 和 `allowed_models`。

## 刪除 API Key

```bash theme={null}
curl -X DELETE https://api.arouter.ai/api/v1/keys/KEY_HASH \
  -H "Authorization: Bearer lr_mgmt_xxxx"
```

已刪除的金鑰立即失效，無法復原。

## 使用案例

| 場景        | 設定                           |
| --------- | ---------------------------- |
| **按服務隔離** | 每個微服務使用一個 API Key，具有特定模型存取權限 |
| **成本控制**  | 按團隊或環境設定消費限額                 |
| **臨時存取**  | 為承包商設定帶 `expires_at` 的短期金鑰   |
| **服務商鎖定** | 僅將預發布環境限制為廉價模型               |
| **速率保護**  | 透過控制台按金鑰調整限額                 |
