resource-storage-examples.md 3.1 KB

Resource存储系统使用示例

环境配置

.env文件中配置组织密钥:

# 生成密钥(Python)
python -c "import os, base64; print(base64.b64encode(os.urandom(32)).decode())"

# 配置到.env
ORG_KEYS=test:生成的密钥base64,prod:另一个密钥base64

使用示例

1. 存储代码片段

curl -X POST http://localhost:8000/api/resource \
  -H "Content-Type: application/json" \
  -d '{
    "id": "test/code/selenium",
    "title": "Selenium绕过检测",
    "body": "import undetected_chromedriver as uc\ndriver = uc.Chrome()",
    "content_type": "code",
    "metadata": {"language": "python"},
    "submitted_by": "user@example.com"
  }'

2. 存储账号密码(加密)

curl -X POST http://localhost:8000/api/resource \
  -H "Content-Type: application/json" \
  -d '{
    "id": "test/credentials/website",
    "title": "某网站登录凭证",
    "body": "使用方法:直接登录即可",
    "secure_body": "账号:user@example.com\n密码:SecurePass123",
    "content_type": "credential",
    "metadata": {"acquired_at": "2026-03-06T10:00:00Z"},
    "submitted_by": "user@example.com"
  }'

3. 存储Cookie(加密)

curl -X POST http://localhost:8000/api/resource \
  -H "Content-Type: application/json" \
  -d '{
    "id": "test/cookies/website",
    "title": "某网站Cookie",
    "body": "适用于:已登录状态的API调用",
    "secure_body": "session_id=abc123; auth_token=xyz789",
    "content_type": "cookie",
    "metadata": {
      "acquired_at": "2026-03-06T10:00:00Z",
      "expires_at": "2026-03-07T10:00:00Z"
    },
    "submitted_by": "user@example.com"
  }'

4. 获取资源(无密钥)

# 公开内容正常返回,敏感内容显示[ENCRYPTED]
curl http://localhost:8000/api/resource/test/credentials/website

5. 获取资源(有密钥)

# 敏感内容解密返回
curl http://localhost:8000/api/resource/test/credentials/website \
  -H "X-Org-Key: 你的密钥base64"

6. 更新资源

curl -X PATCH http://localhost:8000/api/resource/test/credentials/website \
  -H "Content-Type: application/json" \
  -d '{
    "title": "更新后的标题",
    "metadata": {"acquired_at": "2026-03-06T11:00:00Z"}
  }'

7. 列出所有资源

curl http://localhost:8000/api/resource

8. 按类型过滤

curl "http://localhost:8000/api/resource?content_type=credential"

Knowledge引用Content

在Knowledge中引用Content资源:

curl -X POST http://localhost:8000/api/knowledge \
  -H "Content-Type: application/json" \
  -d '{
    "task": "登录某网站",
    "content": "使用Selenium + undetected_chromedriver绕过检测,详见content资源",
    "types": ["tool"],
    "tags": {
      "content_ref": "test/code/selenium",
      "credential_ref": "test/credentials/website"
    },
    "owner": "agent:test",
    "source": {
      "submitted_by": "user@example.com"
    }
  }'

测试脚本

运行测试脚本验证功能:

# 启动服务器
uvicorn knowhub.server:app --reload

# 运行测试(另一个终端)
python test_content_storage.py