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

# 管理 API 密钥

> 使用 Admin 密钥，通过代码创建、限额、跟踪、更新和撤销 Venice API 密钥。

Admin 密钥可以通过 API 管理你的所有其他 API 密钥。为每个应用、环境或客户分配独立的 Inference 密钥，限制每个密钥可以消费的金额，按密钥跟踪使用情况，并在无需打开仪表板的情况下更改或撤销密钥。

> [card] [创建](#create-a-key)
>
> 签发带有支出上限的密钥

> [card] [跟踪](#track-usage)
>
> 查看每个密钥的支出

> [card] [更改](#change-limits-and-settings)
>
> 调高上限或延长过期时间

> [card] [撤销](#revoke-or-rotate-a-key)
>
> 立即停用密钥

## 工作原理

Admin 密钥
你的控制密钥
创建、更改和撤销密钥
读取使用情况和账单
仅保存在你的服务器上

Inference
cust:acme

\$50 / 月
仅限私有模型

Inference
cust:globex

\$5 / 月
仅限来自 11.22.33.0/24

Inference
staging

\$10 / 天
6 月 30 日过期

Admin 密钥可以调用所有端点，包括管理密钥和读取账单的端点。Inference 密钥可以调用模型，但不能管理密钥或读取账单，因此它们才是你分发出去的密钥。

| | Admin | Inference |
| - | :-: | :-: |
| 调用模型和其他推理端点 | ✓ | ✓ |
| 查看自身余额和速率限制（`GET /api_keys/rate_limits`） | ✓ | ✓ |
| 创建、更新和撤销密钥（`/api_keys`） | ✓ | |
| 读取使用情况和账单（`/billing/*`） | ✓ | |

> [!NOTE]
>
> 在仪表板中创建你的第一个 Admin 密钥：按照 [生成 API 密钥](https://docs.venice.ai/zh/guides/getting-started/generating-api-key.md) 操作，并选择 **Admin** 作为密钥类型。请将其保存在服务器端的密钥存储中，切勿放在客户端代码里。

本页中的示例从 `VENICE_ADMIN_KEY` 读取 Admin 密钥：

```bash cURL theme={"system"}
export VENICE_ADMIN_KEY="your-admin-key"
```

```python Python theme={"system"}
import os
import requests

BASE = "https://api.venice.ai/api/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['VENICE_ADMIN_KEY']}"}
```

```javascript Node.js theme={"system"}
const BASE = "https://api.venice.ai/api/v1";
const headers = {
  Authorization: `Bearer ${process.env.VENICE_ADMIN_KEY}`,
  "Content-Type": "application/json",
};
```

## 创建密钥

以下示例为一位客户创建一个 Inference 密钥，上限为每月 \$50，并于 2027 年 6 月 30 日过期：

```bash cURL theme={"system"}
curl https://api.venice.ai/api/v1/api_keys \
  -H "Authorization: Bearer $VENICE_ADMIN_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "apiKeyType": "INFERENCE",
    "description": "cust:acme",
    "consumptionLimit": { "usd": 50 },
    "limitPeriod": "MONTH",
    "expiresAt": "2027-06-30"
  }'
```

```python Python theme={"system"}
resp = requests.post(f"{BASE}/api_keys", headers=HEADERS, json={
    "apiKeyType": "INFERENCE",
    "description": "cust:acme",
    "consumptionLimit": {"usd": 50},
    "limitPeriod": "MONTH",
    "expiresAt": "2027-06-30",
})
resp.raise_for_status()
key = resp.json()["data"]
key_id, secret = key["id"], key["apiKey"]
```

```javascript Node.js theme={"system"}
const res = await fetch(`${BASE}/api_keys`, {
  method: "POST",
  headers,
  body: JSON.stringify({
    apiKeyType: "INFERENCE",
    description: "cust:acme",
    consumptionLimit: { usd: 50 },
    limitPeriod: "MONTH",
    expiresAt: "2027-06-30",
  }),
});
const { data: key } = await res.json();
const { id: keyId, apiKey: secret } = key;
```

```json Response theme={"system"}
{
  "success": true,
  "data": {
    "id": "e28e82dc-9df2-4b47-b726-d0a222ef2ab5",
    "apiKey": "VENICE_INFERENCE_KEY_...",
    "apiKeyType": "INFERENCE",
    "description": "cust:acme",
    "consumptionLimit": { "usd": 50, "vcu": null, "diem": null },
    "limitPeriod": "MONTH",
    "modelPrivacy": "ALL",
    "expiresAt": "2027-06-30T00:00:00.000Z",
    "ipAllowlist": []
  }
}
```

> [!WARNING]
>
> `data.apiKey` 是密钥的机密值，并且只会在此响应中出现一次。请立即保存。如果丢失，请撤销该密钥并创建一个新的。同时请保存 `data.id`：本页中的其他所有调用都会用到它。

### 密钥设置

你可以在创建密钥时设置以下字段，或稍后通过 `PATCH /api_keys` 进行更改。请求体采用严格校验，未知字段会返回 `400`。

| 字段 | 取值 | 作用 |
| - | - | - |
| `apiKeyType` | `INFERENCE` 或 `ADMIN` | 创建时必填，之后无法更改。 |
| `description` | 最多 64 个字符 | 创建时必填。使用分析会用它来标记该密钥，因此请在此填写你自己的标识符，例如 `cust:acme`。 |
| `consumptionLimit` | `{ "usd": 50 }` | 每个 `limitPeriod` 的支出上限，单位为 `usd`、`diem` 或两者。省略某种货币或将其设为 `null` 表示不设上限。USD 上限会将 USD、捆绑积分和赚取的积分合并计算。 |
| `limitPeriod` | `EPOCH`、`MONTH`、`LIFETIME` | 上限的重置时间。默认值 `EPOCH` 每天 00:00 UTC 重置，`MONTH` 在每月 1 日（UTC）重置，`LIFETIME` 从不重置。 |
| `expiresAt` | `"2027-06-30"` | 日期，或 UTC 时间，例如 `"2027-06-30T23:59:59Z"`。仅提供日期表示当天 00:00 UTC。省略则密钥永不过期。 |
| `modelPrivacy` | `ALL`、`PRIVATE_TEXT`、`PRIVATE_ONLY` | 默认值 `ALL` 允许使用任何模型。`PRIVATE_TEXT` 要求文本和嵌入模型为 Private、TEE 或 E2EE 模型。`PRIVATE_ONLY` 对所有模型都有此要求。 |
| `ipAllowlist` | `["11.22.33.0/24"]` | 最多 100 个公网 IPv4 或 IPv6 地址或 CIDR 范围。空列表表示允许任何 IP。 |

你每分钟最多可以创建 20 个密钥，最多可保留 500 个活跃密钥。如需更多，请联系支持团队。

> [!TIP]
>
> 正在构建代理？在 Base 上持有质押 VVV 的钱包无需 Venice 账户即可自行铸造密钥。请参阅 [自主代理 API 密钥创建](https://docs.venice.ai/zh/guides/integrations/generating-api-key-agent.md)。

## 跟踪使用情况

| 想要了解 | 调用 | 读取 |
| - | - | - |
| 单个密钥在本周期内的支出 | `GET /api_keys/{id}` | `currentPeriodUsage` |
| 每个密钥在过去 7 天内的支出 | `GET /api_keys` | `usage.trailingSevenDays` |
| 按天统计的每个密钥支出 | `GET /billing/usage-analytics` | `byKey`、`byKeyDaily` |
| 每笔费用及其计费的密钥 | `GET /billing/usage-history` | `apiKeyId` |
| 某个密钥当前是否可以消费 | `GET /api_keys/rate_limits`，使用该密钥调用 | `accessPermitted`、`balances` |
| 哪些密钥触发了速率限制 | `GET /api_keys/rate_limits/log` | `apiKeyId`、`modelId` |

### 单个密钥

```bash cURL theme={"system"}
curl https://api.venice.ai/api/v1/api_keys/e28e82dc-9df2-4b47-b726-d0a222ef2ab5 \
  -H "Authorization: Bearer $VENICE_ADMIN_KEY"
```

```python Python theme={"system"}
key = requests.get(f"{BASE}/api_keys/{key_id}", headers=HEADERS).json()["data"]
```

```javascript Node.js theme={"system"}
const res = await fetch(`${BASE}/api_keys/${keyId}`, { headers });
const { data: key } = await res.json();
```

```json Response (trimmed) theme={"system"}
{
  "data": {
    "id": "e28e82dc-9df2-4b47-b726-d0a222ef2ab5",
    "description": "cust:acme",
    "consumptionLimits": { "usd": 50, "diem": null, "vcu": null },
    "limitPeriod": "MONTH",
    "currentPeriodUsage": { "usd": "12.5000", "diem": "0.0000" },
    "usage": { "trailingSevenDays": { "usd": "4.2000", "diem": "0.0000", "vcu": "0.0000" } },
    "lastUsedAt": "2026-11-03T14:05:00.000Z"
  }
}
```

该密钥本月已使用其 $50 中的 $12.50。`currentPeriodUsage` 仅出现在设置了 USD 或 DIEM 上限的密钥上，使用量为保留四位小数的字符串。响应返回的是 `consumptionLimits`（复数），而请求发送的是 `consumptionLimit`（单数）。

### 每个密钥随时间的支出

`GET /billing/usage-analytics` 在 `byKey` 中返回每个密钥的总计，在 `byKeyDaily` 中返回每天一行的数据，可直接用于绘制图表。传入 `lookback`（默认 `7d`，最多 `90d`），或传入跨度不超过 90 天的 `startDate` 和 `endDate`。结果会缓存 10 分钟。

```bash cURL theme={"system"}
curl "https://api.venice.ai/api/v1/billing/usage-analytics?lookback=30d" \
  -H "Authorization: Bearer $VENICE_ADMIN_KEY"
```

```json Response (trimmed) theme={"system"}
{
  "byKey": [
    {
      "apiKeyId": "e28e82dc-9df2-4b47-b726-d0a222ef2ab5",
      "description": "cust:acme",
      "totalUsd": 12.5,
      "totalDiem": 0,
      "totalUnits": 1830000
    }
  ]
}
```

### 每个密钥的每笔费用

`GET /billing/usage-history` 列出每一笔费用，每个条目都带有其计费的 `apiKeyId`。可用它来核对支出或向你自己的客户计费。条目按从旧到新的顺序返回。将 `nextCursor` 作为 `cursor` 单独传回，直到其为 `null`。发送 `Accept: text/csv` 可改为获取 CSV 格式。

```bash cURL theme={"system"}
curl -G https://api.venice.ai/api/v1/billing/usage-history \
  -H "Authorization: Bearer $VENICE_ADMIN_KEY" \
  --data-urlencode "startTimestamp=2026-10-01T00:00:00Z" \
  --data-urlencode "endTimestamp=2026-11-01T00:00:00Z"
```

```python Python theme={"system"}
from collections import defaultdict

spend = defaultdict(float)
params = {"startTimestamp": "2026-10-01T00:00:00Z", "endTimestamp": "2026-11-01T00:00:00Z"}
while True:
    page = requests.get(f"{BASE}/billing/usage-history", headers=HEADERS, params=params).json()
    for entry in page["data"]:
        if entry["apiKeyId"]:
            spend[(entry["apiKeyId"], entry["currency"])] -= entry["amount"]
    if page["nextCursor"] is None:
        break
    params = {"cursor": page["nextCursor"]}
```

费用的 `amount` 为负数，因此循环中将其减去，以得到每个密钥和货币的正数总计。没有 `apiKeyId` 的条目来自 Venice 网页应用，或是诸如购买积分之类的账户条目。

### 某个密钥当前是否可以消费

`GET /api_keys/rate_limits` 适用于任何密钥，并报告调用它的那个密钥的情况。`accessPermitted` 表示该密钥当前是否可以消费，`balances` 显示其剩余可消费的额度。

```bash cURL theme={"system"}
curl https://api.venice.ai/api/v1/api_keys/rate_limits \
  -H "Authorization: Bearer $VENICE_API_KEY"
```

使用 Admin 密钥调用 `GET /api_keys/rate_limits/log`，可返回你最近 50 次触发速率限制的记录，每条记录都带有其 `apiKeyId` 和 `modelId`。

## 更改限额和设置

发送密钥的 `id`，以及仅需更改的字段。其他所有设置保持不变。以下示例将上限调高到每月 \$100：

```bash cURL theme={"system"}
curl -X PATCH https://api.venice.ai/api/v1/api_keys \
  -H "Authorization: Bearer $VENICE_ADMIN_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "id": "e28e82dc-9df2-4b47-b726-d0a222ef2ab5",
    "consumptionLimit": { "usd": 100 }
  }'
```

```python Python theme={"system"}
requests.patch(f"{BASE}/api_keys", headers=HEADERS, json={
    "id": key_id,
    "consumptionLimit": {"usd": 100},
}).raise_for_status()
```

```javascript Node.js theme={"system"}
await fetch(`${BASE}/api_keys`, {
  method: "PATCH",
  headers,
  body: JSON.stringify({ id: keyId, consumptionLimit: { usd: 100 } }),
});
```

如需进行其他更改，请改为发送以下任一字段：

| 目的 | 发送 |
| - | - |
| 移除上限 | `"consumptionLimit": { "usd": null }` |
| 将上限改为每月重置而非每天重置 | `"limitPeriod": "MONTH"` |
| 将上限设为一次性预算 | `"limitPeriod": "LIFETIME"` |
| 延长过期时间 | `"expiresAt": "2027-12-31"` |
| 移除过期时间 | `"expiresAt": null` |
| 仅接受来自你的服务器的请求 | `"ipAllowlist": ["11.22.33.0/24"]` |
| 重新接受来自任何 IP 的请求 | `"ipAllowlist": []` |
| 仅允许私有模型 | `"modelPrivacy": "PRIVATE_ONLY"` |
| 重命名密钥 | `"description": "cust:acme-prod"` |

新的 `limitPeriod` 会立即生效，因此切换到 `LIFETIME` 会将该密钥过去的所有支出计入上限。`apiKeyType` 无法更改；请改为创建一个新密钥。

## 撤销或轮换密钥

```bash cURL theme={"system"}
curl -X DELETE \
  "https://api.venice.ai/api/v1/api_keys?id=e28e82dc-9df2-4b47-b726-d0a222ef2ab5" \
  -H "Authorization: Bearer $VENICE_ADMIN_KEY"
```

```python Python theme={"system"}
requests.delete(f"{BASE}/api_keys", headers=HEADERS, params={"id": key_id}).raise_for_status()
```

```javascript Node.js theme={"system"}
await fetch(`${BASE}/api_keys?id=${keyId}`, { method: "DELETE", headers });
```

响应为 `{ "success": true }`。撤销会立即生效：该密钥的下一个请求将收到 `401 Authentication failed`，并且该密钥将从 `GET /api_keys` 中消失。其过去的费用仍保留在使用历史中。

要在不停机的情况下轮换密钥：

**1. 创建替换密钥**

使用相同的设置创建一个新密钥，并保存其机密值。

**2. 部署新密钥**

将你的应用切换为使用新的机密值。

**3. 撤销旧密钥**

当 `GET /api_keys` 中旧密钥的 `lastUsedAt` 不再变化时，将其删除。

## 调用方可能遇到的错误

| 状态码 | 消息 | 处理方法 |
| - | - | - |
| `402` | `API key USD spend limit exceeded...`，DIEM 同理 | 调高或移除上限，或等待下一个周期。账户本身可能仍有资金。 |
| `403` | 该密钥的隐私设置不允许使用此模型 | 使用 Private、TEE 或 E2EE 模型，或更改 `modelPrivacy`。 |
| `403` | `This API key is restricted to configured IP addresses...` | 将调用方的 IP 添加到 `ipAllowlist`。 |
| `401` | `Authentication failed` | 该密钥已被撤销、已过期或输入有误。 |
| `401` | `Admin API key required` | Inference 密钥调用了密钥管理或账单端点。 |
| `429` | `Too many API key creation requests...` | 密钥创建限制为每分钟 20 个。请稍候再重试。 |
| `400` | `Maximum number of active API keys (500) reached...` | 撤销不再使用的密钥，或联系支持团队。 |

完整列表请参见 [错误代码](https://docs.venice.ai/zh/api-reference/error-codes.md)。

## 最佳实践

* 将 Admin 密钥保存在你的服务器上，只分发 Inference 密钥。
* 为每个应用、环境和客户分配独立的密钥，以便单独跟踪和撤销每个密钥。
* 在 `description` 中填写你自己的标识符。使用分析会用它来标记密钥。
* 为你提供给他人的每个密钥设置上限和过期时间，并使用 `ipAllowlist` 将服务器到服务器的密钥锁定到你的 IP。

## API 参考

> [card] [创建 API 密钥](https://docs.venice.ai/zh/api-reference/endpoint/api_keys/create.md)
>
> 创建时接受的所有字段。

> [card] [更新 API 密钥](https://docs.venice.ai/zh/api-reference/endpoint/api_keys/update.md)
>
> 更改限额、过期时间、隐私设置和 IP。

> [card] [列出 API 密钥](https://docs.venice.ai/zh/api-reference/endpoint/api_keys/list.md)
>
> 所有活跃密钥及其使用情况。

> [card] [删除 API 密钥](https://docs.venice.ai/zh/api-reference/endpoint/api_keys/delete.md)
>
> 撤销密钥。

> [card] [使用分析](https://docs.venice.ai/zh/api-reference/endpoint/billing/usage-analytics.md)
>
> 按密钥、模型和日期统计的支出。

> [card] [使用历史](https://docs.venice.ai/zh/api-reference/endpoint/billing/usage-history.md)
>
> 每笔费用及其 API 密钥。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.