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

# API Key 管理

> 创建、查看和吊销 API Key

API Key 是你调用袋袋 Platform API 的凭证。本页介绍如何在 Platform Console 中管理 API Key。

## 创建 API Key

<Steps>
  <Step title="访问 Platform Console">
    登录 [app.profy.cn](https://app.profy.cn)，然后访问 [platform.profy.cn](https://platform.profy.cn)。两者共享登录态。
  </Step>

  <Step title="进入 API Keys 页面">
    在左侧导航栏点击 **API Keys**。
  </Step>

  <Step title="创建新 Key">
    点击 **创建 API Key** 按钮，填写以下信息：

    * **名称**：为 Key 起一个描述性名称（如「生产环境后端」、「数据分析脚本」）
    * **权限范围（Scopes）**：选择 Key 可访问的端点范围
    * **过期时间**：选择 Key 的过期期限（30 天 / 90 天 / 1 年 / 永不过期）
  </Step>

  <Step title="保存 Key">
    点击确认后，系统会生成一个以 `sk-pro-` 开头的 API Key。

    <Warning>
      API Key **仅在创建时展示一次**。页面关闭后无法再次查看完整 Key。请立即将它保存到安全的位置（如密码管理器、环境变量或密钥管理服务）。
    </Warning>
  </Step>
</Steps>

## 权限范围（Scopes）

创建 API Key 时，你可以选择 Key 的权限范围：

| Scope          | 说明   | 可访问的端点                                                               |
| -------------- | ---- | -------------------------------------------------------------------- |
| `all`          | 全部权限 | 所有 `/v1/*` 端点                                                        |
| `events:write` | 事件写入 | `/v1/agents/run`, `/v1/chat/completions`, `/v1/models`, `/v1/events` |

<Tip>
  遵循最小权限原则——只授予 Key 实际需要的权限。
</Tip>

## 查看 API Keys

在 API Keys 页面，你可以看到所有已创建的 Key 列表：

| 信息         | 说明                       |
| ---------- | ------------------------ |
| **名称**     | Key 的描述性名称               |
| **Key 前缀** | `sk-pro-xxxx...`（仅显示前几位） |
| **创建时间**   | Key 的创建日期                |
| **过期时间**   | Key 的过期日期（如有）            |
| **状态**     | 活跃 / 已过期 / 已吊销           |

## 吊销 API Key

当 Key 不再需要或可能泄露时，应立即吊销：

<Steps>
  <Step title="找到目标 Key">
    在 API Keys 列表中找到要吊销的 Key。
  </Step>

  <Step title="点击吊销">
    点击 Key 旁的删除/吊销按钮。
  </Step>

  <Step title="确认吊销">
    确认操作。**吊销是不可逆的**——被吊销的 Key 将立即失效，无法恢复。
  </Step>
</Steps>

<Warning>
  吊销 Key 后，使用该 Key 的所有请求将立即返回 `401 Unauthorized`。请确保在吊销前已更新所有使用该 Key 的服务。
</Warning>

## 安全存储

### 使用环境变量

```bash theme={null}
# .env 文件（不要提交到版本控制）
PROFY_API_KEY=sk-pro-your-key-here
```

<CodeGroup>
  ```python Python theme={null}
  import os
  from profy import Profy

  client = Profy(api_key=os.environ["PROFY_API_KEY"])
  ```

  ```typescript TypeScript theme={null}
  import { Profy } from "@profy-ai/sdk";

  const client = new Profy({
    apiKey: process.env.PROFY_API_KEY!,
  });
  ```
</CodeGroup>

### 使用密钥管理服务

对于生产环境，推荐使用云服务商的密钥管理服务：

* **AWS Secrets Manager**
* **腾讯云 SSM**
* **HashiCorp Vault**

```python theme={null}
import boto3

def get_profy_key():
    client = boto3.client("secretsmanager")
    response = client.get_secret_value(SecretId="profy/api-key")
    return response["SecretString"]
```

## 安全最佳实践

<AccordionGroup>
  <Accordion title="不要在前端代码中使用 API Key">
    浏览器端的 JavaScript 代码可被用户查看。如果你的 App 需要在前端调用袋袋 API，请使用 OAuth 流程获取用户级 Token，或通过你自己的后端代理请求。
  </Accordion>

  <Accordion title="不要将 Key 提交到版本控制">
    使用 `.env` 文件存储 Key，并将 `.env` 添加到 `.gitignore`。CI/CD 环境使用密钥管理服务注入。
  </Accordion>

  <Accordion title="设置过期时间">
    为 Key 设置合理的过期时间。对于测试用途，使用 30 天过期；对于生产用途，使用 90 天或 1 年过期并定期轮换。
  </Accordion>

  <Accordion title="定期审计和轮换">
    定期检查 API Keys 列表，吊销不再使用的 Key。对于长期运行的服务，制定轮换计划（如每季度更换一次 Key）。
  </Accordion>

  <Accordion title="监控异常使用">
    在 Platform Console 的 Usage Stats 和 Call Logs 中监控 API 调用量。如发现异常激增，可能是 Key 泄露的信号。
  </Accordion>
</AccordionGroup>

## 调用日志

每个 API Key 的调用都会被记录。在 Platform Console 的 **Call Logs** 页面，你可以：

* **按 Key 筛选**：查看特定 Key 的调用记录
* **按状态码筛选**：找到失败的调用
* **按端点筛选**：查看特定 API 的调用
* **查看详情**：展开查看请求和响应摘要

## 速率限制

API Key 受速率限制保护。当触发限制时，API 返回 `429 Too Many Requests`。建议在客户端实现指数退避重试：

```python theme={null}
import asyncio
from profy import Profy, ProfyApiError

async def call_with_retry(client, max_retries=3):
    for attempt in range(max_retries):
        try:
            return await client.agents.run("my-expert", "你好")
        except ProfyApiError as e:
            if e.status_code == 429 and attempt < max_retries - 1:
                wait = 2 ** attempt
                await asyncio.sleep(wait)
                continue
            raise
```

## Desktop 自动配置

袋袋 Desktop 客户端在首次登录时会自动创建一个名为「袋袋 Desktop」的 API Key。这个过程对用户透明，无需手动操作。

## 下一步

<CardGroup cols={2}>
  <Card title="认证指南" icon="lock" href="/zh/developers/authentication">
    了解 API Key 与 OAuth 的对比
  </Card>

  <Card title="Platform Console" icon="monitor" href="/zh/developers/platform-console">
    了解控制台的完整功能
  </Card>
</CardGroup>
