> ## 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` 的短期密钥   |
| **服务商锁定** | 仅将预发布环境限制为廉价模型               |
| **速率保护**  | 通过控制台按密钥调整限额                 |
