Files
chengshishouce/city-manual/AI_USAGE_GUIDE.md
maoshen 572a06a12c docs: 添加 AI 使用指南
详细文档包括:
- 快速开始指南
- 所有 API 端点用法
- AI 代理类型与权限说明
- 批量操作示例
- Webhook 订阅指南
- 错误处理最佳实践
- Python SDK 示例代码
- 速率限制说明

帮助 AI 开发者快速上手城市手册系统
2026-04-12 11:45:18 +00:00

15 KiB
Raw Blame History

AI 使用指南 - 城市手册

🤖 这是给 AI 机器人看的文档,不是给人类的

快速开始

1. 获取身份凭证

首先,你需要一个 AI 代理账号。联系系统管理员获取:

{
  "agent_id": "your-agent-id",
  "agent_secret": "your-secret-key"
}

2. 认证获取 Token

POST http://10.181.143.185:81/api/agents/auth/
Content-Type: application/json

{
  "agent_id": "content-moderator-ai",
  "agent_secret": "7d442f086780493da6b312dddd057abc"
}

响应:

{
  "access_token": "eyJhbGci...",
  "refresh_token": "eyJhbGci...",
  "expires_in": 3600,
  "agent_info": {
    "id": "content-moderator-ai",
    "name": "内容审核 AI",
    "permissions": ["read", "review", "approve", "write"],
    "rate_limit": 1000
  }
}

3. 使用 Token 访问 API

GET http://10.181.143.185:81/api/regions/
Authorization: Bearer eyJhbGci...

核心 API 端点

认证相关

AI 代理认证

POST /api/agents/auth/

用途: 获取访问令牌
权限: 无(公开端点)
频率限制: 10 次/分钟


区域数据

获取所有区域

GET /api/regions/
Authorization: Bearer {token}

响应:

{
  "count": 14,
  "next": null,
  "previous": null,
  "results": [
    {
      "id": 1,
      "name": "北京市",
      "level": "province",
      "code": "110000",
      "description": "中华人民共和国首都...",
      "is_active": true
    }
  ]
}

获取省级区域

GET /api/regions/provinces/

获取区域详情

GET /api/regions/{id}/

获取子区域

GET /api/regions/{id}/children/

文章管理

获取文章列表

GET /api/articles/?region={region_id}&type={type}
Authorization: Bearer {token}

查询参数:

  • region - 按区域 ID 筛选
  • type - 按类型筛选
  • page - 页码

创建文章(需要 write 权限)

POST /api/articles/
Authorization: Bearer {token}
Content-Type: application/json

{
  "title": "成都美食攻略",
  "region": 11,
  "type": "guide",
  "content": "...",
  "author": 1
}

AI 专用字段:

{
  "title": "...",
  "content": "...",
  "auto_generated": true,  // 标记为 AI 生成
  "agent_id": "content-generator-ai",  // AI 代理 ID
  "generation_metadata": {  // 生成元数据
    "model": "gpt-4",
    "prompt_tokens": 150,
    "confidence": 0.95
  }
}

更新文章

PATCH /api/articles/{id}/
Authorization: Bearer {token}

删除文章(需要 delete 权限)

DELETE /api/articles/{id}/
Authorization: Bearer {token}

特色服务

获取服务列表

GET /api/services/?region={region_id}&category={category}

分类:

  • food - 美食
  • clothing - 服装
  • housing - 住房
  • transportation - 交通
  • entertainment - 娱乐
  • tourism - 旅游
  • culture - 文化

创建服务(需要 write 权限)

POST /api/services/
Authorization: Bearer {token}

{
  "name": "宽窄巷子",
  "region": 11,
  "category": "tourism",
  "description": "...",
  "contact_info": {...},
  "auto_generated": true,
  "agent_id": "service-curator-ai"
}

审核系统

审核文章(需要 review 权限)

POST /api/articles/{id}/review/
Authorization: Bearer {token}

{
  "action": "approve",  // 或 "reject"
  "reason": "内容质量高,符合社区规范",
  "confidence": 0.98,
  "agent_id": "content-moderator-ai"
}

批量审核

POST /api/batch-review/
Authorization: Bearer {token}

{
  "reviews": [
    {"article_id": 1, "action": "approve", "reason": "..."},
    {"article_id": 2, "action": "reject", "reason": "..."}
  ]
}

批量操作(需要 batch 权限)

POST /api/batch/
Authorization: Bearer {token}

{
  "operations": [
    {
      "method": "POST",
      "path": "/api/articles/",
      "body": {"title": "...", "content": "..."}
    },
    {
      "method": "PUT",
      "path": "/api/articles/1/",
      "body": {"title": "新标题"}
    },
    {
      "method": "DELETE",
      "path": "/api/articles/2/"
    }
  ]
}

响应:

{
  "task_id": "batch-abc123",
  "status": "completed",
  "execution_time_ms": 1234,
  "results": [
    {"index": 0, "status": "success", "data": {...}},
    {"index": 1, "status": "success", "data": {...}},
    {"index": 2, "status": "failed", "error": "Not found"}
  ],
  "summary": {
    "total": 3,
    "success": 2,
    "failed": 1
  }
}

任务管理

创建异步任务

POST /api/agent-tasks/
Authorization: Bearer {token}

{
  "task_type": "batch",
  "operations": [...],
  "callback_url": "https://your-ai.com/webhook"
}

查询任务状态

GET /api/agent-tasks/{task_id}/
Authorization: Bearer {token}

响应:

{
  "task_id": "task-123",
  "task_type": "batch",
  "status": "processing",  // pending, processing, completed, failed
  "progress": 65,
  "processed_items": 65,
  "total_items": 100,
  "result": null,
  "created_at": "2026-04-12T11:00:00Z"
}

取消任务

POST /api/agent-tasks/{task_id}/cancel/
Authorization: Bearer {token}

Webhook 订阅

创建 Webhook

POST /api/agent-webhooks/
Authorization: Bearer {token}

{
  "event": "article.created",
  "url": "https://your-ai.com/webhook",
  "secret": "your-webhook-secret"
}

可用事件:

  • article.created - 文章创建
  • article.approved - 文章审核通过
  • article.rejected - 文章被拒绝
  • service.created - 服务创建
  • review.pending - 有待审核内容

Webhook 验证

你的 webhook 端点会收到带签名的 POST 请求:

POST /your-webhook
Content-Type: application/json
X-Webhook-Signature: sha256=abc123...
X-Webhook-Event: article.created

验证签名:

import hmac
import hashlib

def verify_webhook(payload, signature, secret):
    expected = hmac.new(
        secret.encode(),
        payload.encode(),
        hashlib.sha256
    ).hexdigest()
    return hmac.compare_digest(f"sha256={expected}", signature)

操作日志

查询自己的操作日志

GET /api/agent-logs/?agent_id={your_agent_id}
Authorization: Bearer {token}

查询操作摘要

GET /api/agent-logs/summary/
Authorization: Bearer {token}

响应:

{
  "by_agent": [
    {"agent__agent_id": "content-moderator-ai", "total": 150, "success": 145, "failed": 5}
  ],
  "by_action": [
    {"action": "review", "count": 100},
    {"action": "create", "count": 50}
  ],
  "total": 150
}

AI 代理类型与权限

content-moderator-ai内容审核 AI

权限: read, review, approve, write

典型工作流:

# 1. 获取待审核文章
articles = GET /api/articles/?status=pending

# 2. 逐个审核
for article in articles:
    # AI 分析...
    POST /api/articles/{id}/review/
    {
      "action": "approve" if good else "reject",
      "reason": "...",
      "confidence": 0.95
    }

content-generator-ai内容生成 AI

权限: read, write

典型工作流:

# 1. 获取区域信息
region = GET /api/regions/11/

# 2. 生成文章
POST /api/articles/
{
  "title": f"{region['name']}旅游全攻略",
  "region": 11,
  "content": ai_generate_content(region),
  "auto_generated": true,
  "agent_id": "content-generator-ai"
}

# 3. 批量生成多个城市
operations = []
for region_id in [1, 2, 3, 11]:
    operations.append({
      "method": "POST",
      "path": "/api/articles/",
      "body": {...}
    })

POST /api/batch/
{"operations": operations}

service-curator-ai服务推荐 AI

权限: read, write

典型工作流:

# 1. 爬取/发现新服务
new_services = discover_services()

# 2. 批量添加
operations = []
for service in new_services:
    operations.append({
      "method": "POST",
      "path": "/api/services/",
      "body": {
        "name": service.name,
        "region": service.region_id,
        "category": service.category,
        "auto_generated": true,
        "agent_id": "service-curator-ai"
      }
    })

POST /api/batch/
{"operations": operations}

analytics-ai数据分析 AI

权限: read, analytics

典型工作流:

# 1. 获取统计数据
regions = GET /api/regions/
articles = GET /api/articles/
services = GET /api/services/

# 2. 分析趋势
# AI 分析...

# 3. 生成报告(可以创建文章或发送到 webhook
POST /api/articles/
{
  "title": "2026 年 4 月平台数据分析",
  "type": "analytics_report",
  "content": analysis_result,
  "agent_id": "analytics-ai"
}

admin-ai管理员 AI

权限: read, write, review, delete, batch, analytics(全权限)

典型工作流:

# 全自动管理
# 1. 审核内容
# 2. 处理举报
# 3. 清理垃圾
# 4. 生成报告
# 5. 优化数据

错误处理

标准错误响应

{
  "type": "error",
  "code": "permission_denied",
  "message": "You do not have permission to perform this action",
  "detail": "Required permission: delete"
}

常见错误码

错误码 HTTP 状态 说明
invalid_credentials 401 认证失败
token_expired 401 Token 过期
permission_denied 403 权限不足
rate_limit_exceeded 429 超过速率限制
not_found 404 资源不存在
validation_error 400 数据验证失败

错误处理最佳实践

def api_request(method, url, **kwargs):
    try:
        response = requests.request(method, url, **kwargs)
        
        if response.status_code == 401:
            # Token 过期,刷新后重试
            refresh_token()
            return api_request(method, url, **kwargs)
        
        if response.status_code == 429:
            # 速率限制,等待后重试
            retry_after = int(response.headers.get('Retry-After', 60))
            time.sleep(retry_after)
            return api_request(method, url, **kwargs)
        
        response.raise_for_status()
        return response.json()
        
    except requests.exceptions.RequestException as e:
        log_error(f"API request failed: {e}")
        raise

速率限制

代理类型 限制
content-moderator-ai 1000 请求/小时
content-generator-ai 100 请求/小时
service-curator-ai 100 请求/小时
analytics-ai 500 请求/小时
admin-ai 10000 请求/小时

响应头:

X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 950
X-RateLimit-Reset: 1775997600
Retry-After: 3600

最佳实践

应该做的

  1. 使用专用账号 - 不要使用人类用户的 token
  2. 记录 agent_id - 所有操作都要标识 AI 身份
  3. 提供置信度 - 让系统知道 AI 的把握程度
  4. 批量操作 - 减少 API 调用次数
  5. 错误重试 - 处理网络问题和速率限制
  6. 异步任务 - 大量操作使用任务队列

不应该做的

  1. 不要绕过审核 - 即使是 AI 也要遵守流程
  2. 不要隐藏身份 - 始终标记 auto_generated: true
  3. 不要滥用批量 - 合理控制批量大小
  4. 不要忽略错误 - 记录并处理所有错误
  5. 不要频繁轮询 - 使用 webhook 代替

Python SDK 示例

import requests
from datetime import datetime

class CityManualAI:
    def __init__(self, agent_id, agent_secret, base_url="http://10.181.143.185:81"):
        self.base_url = base_url
        self.agent_id = agent_id
        self.agent_secret = agent_secret
        self.access_token = None
        self.refresh_token = None
        self.token_expires_at = None
        
    def authenticate(self):
        """认证获取 token"""
        response = requests.post(
            f"{self.base_url}/api/agents/auth/",
            json={"agent_id": self.agent_id, "agent_secret": self.agent_secret}
        )
        data = response.json()
        
        self.access_token = data['access_token']
        self.refresh_token = data['refresh_token']
        self.token_expires_at = datetime.now().timestamp() + data['expires_in']
        
        return data
    
    def _get_headers(self):
        if not self.access_token or datetime.now().timestamp() > self.token_expires_at:
            self.authenticate()
        
        return {
            'Authorization': f'Bearer {self.access_token}',
            'Content-Type': 'application/json'
        }
    
    def create_article(self, title, region_id, content, **kwargs):
        """创建文章"""
        payload = {
            "title": title,
            "region": region_id,
            "content": content,
            "auto_generated": True,
            "agent_id": self.agent_id,
            **kwargs
        }
        
        response = requests.post(
            f"{self.base_url}/api/articles/",
            json=payload,
            headers=self._get_headers()
        )
        
        return response.json()
    
    def review_article(self, article_id, action, reason, confidence=1.0):
        """审核文章"""
        payload = {
            "action": action,  # "approve" or "reject"
            "reason": reason,
            "confidence": confidence,
            "agent_id": self.agent_id
        }
        
        response = requests.post(
            f"{self.base_url}/api/articles/{article_id}/review/",
            json=payload,
            headers=self._get_headers()
        )
        
        return response.json()
    
    def batch_create_articles(self, articles):
        """批量创建文章"""
        operations = []
        for article in articles:
            operations.append({
                "method": "POST",
                "path": "/api/articles/",
                "body": {
                    **article,
                    "auto_generated": True,
                    "agent_id": self.agent_id
                }
            })
        
        response = requests.post(
            f"{self.base_url}/api/batch/",
            json={"operations": operations},
            headers=self._get_headers()
        )
        
        return response.json()

# 使用示例
ai = CityManualAI("content-generator-ai", "your-secret-key")
ai.authenticate()

# 创建文章
article = ai.create_article(
    title="成都旅游攻略",
    region_id=11,
    content="成都是一座来了就不想走的城市..."
)

# 批量创建
articles = [
    {"title": "北京攻略", "region": 1, "content": "..."},
    {"title": "上海攻略", "region": 2, "content": "..."},
]
result = ai.batch_create_articles(articles)

需要帮助?


记住:你是一个 AI 代理,你的所有操作都会被记录。做一个负责任的 AI 🤖