Files
taiji-AI-PAD/Docs/HEICODE_API_INTEGRATION.md
chenchenandClaude Opus 4.7 610fde5d03 feat(mcp-server): Heicode integration + register transaction hardening
== Heicode integration (~41 endpoints across 5 modules) ==
- §2 ResourceBinding (5 endpoints) — resources.py / resource_grants.py
- §4 NewAPI metadata proxy (4 endpoints) — heicode_proxy.py + heicode_client.py
- §5 Agnet platform stub (12 endpoints, in-memory mock) — agnet_stub.py
- §6 Task orchestration (5 endpoints + 3 extension endpoints) — heicode_tasks.py
  6.1-6.5: intent / list / get / answer / messages
  6.6-6.8: execution / delivery / audit?tab=... (Slice 8/9/10)
- §7 SSE single channel + approvals (4 endpoints + 5 event types) —
  heicode_events.py + event_bus.py
- §7.8.1 internal billing-provider PUT endpoint — auth.py (routes)

== Schema changes ==
- migrations/026 heicode_tasks (orchestration state)
- migrations/027 users.billing_provider (litellm | newapi switch)
- migrations/028 heicode_approvals (high-risk approval queue)

== Register transaction hardening (P0 + P1 + P2) ==
routes/auth.py register():
- Pre-existing P0: failed register returned IntegrityError str verbatim
  (leaking SQL params + ~50 plaintext LiteLLM keys per attempt).
  Now logs exc_info, returns {code: REGISTER_FAILED, message: ...}.
- Pre-existing P0: model dedupe — two ModelProvider rows with overlapping
  supported_models (e.g. taiji/gpt-4o-mini in both taiji and azure providers)
  collide on uq_tenant_model. seen_models set deduplicates within the loop.
- New P1: track created_litellm_keys; on any failure call delete_key() for
  each — prevents remote orphan keys when DB rollback fires.
- New P1: replace verify_code with peek_verification_code at the start;
  only call verify_code (which consumes) after commit succeeds. Failed
  registrations no longer burn the user's one-shot code.
- New P2: narrow inner `except (LiteLLMClientError, Exception)` to just
  LiteLLMClientError so SQLAlchemy errors bubble to the outer rollback
  instead of being silently swallowed into a half-allocated 200 response.
- New P2: same narrowing on outer `except (AgentManagerError, Exception)`.

== Auth middleware ==
- app/auth.py: allow /api/auth/internal/billing-provider and
  /api/auth/internal/approvals to bypass user JWT (service-token auth
  via HEICODE_INTERNAL_SERVICE_TOKEN, validated in-route).

== Docs ==
- Heicode-接口契约文档.md v2.2 (41 endpoints + SSE schema + 6.6-6.8)
- Heicode-对接进度与待办.md (through §7.14 SSE + 7.8.2 delivery回执)
- Heicode-完整调用流程图.md (sequence + routing diagrams)
- Agent-Manager-Heicode对接需求文档.md
- HEICODE_API_INTEGRATION.md

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-12 15:43:10 +08:00

19 KiB
Raw Permalink Blame History

Heicode Agent Manager API 对接文档

📋 目录


1. 概述

1.1 服务信息

  • 服务名称: Agent Manager - Heicode Integration API
  • 版本: v2.0.0 (heicode-v2)
  • Base URL: http://agent-manager.taijiagnet.com
  • API 前缀: /api/agnet

1.2 核心功能

  • ✅ 多 Agent 编排部署
  • ✅ 预算控制和计费管理
  • ✅ 风险等级评估(low/medium/high)
  • ✅ Vault 密钥集成
  • ✅ 实时日志和事件追踪
  • ✅ 资源监控和指标统计
  • ✅ 幂等性保证

1.3 架构说明

┌─────────────┐
│   Heicode   │
│   Platform  │
└──────┬──────┘
       │ HTTPS + Token Auth
       ▼
┌─────────────────────────────┐
│  Agent Manager API          │
│  /api/agnet/*               │
└──────┬──────────────────────┘
       │
       ▼
┌─────────────────────────────┐
│  Kubernetes Cluster (AKS)   │
│  - Namespace 隔离           │
│  - Pod 管理                 │
│  - ConfigMap/Secret         │
└─────────────────────────────┘

2. 认证方式

2.1 Service Token 认证

所有 API 请求必须在 HTTP Header 中携带服务令牌:

Authorization: Bearer <HEICODE_SERVICE_TOKEN>

2.2 必需的 HTTP Headers

Header 必需 说明 示例
Authorization ✅ 服务令牌 Bearer sk_xxx
X-User-ID ✅ 用户标识 user_12345
X-Binding-Scope ✅ 绑定范围 workspace_abc
X-Correlation-ID ✅ 请求追踪 ID req_xyz789
X-Idempotency-Key ⚪ 幂等性键(推荐) idem_abc123
Content-Type ✅ 内容类型 application/json

2.3 获取 Service Token

请联系系统管理员获取 HEICODE_SERVICE_TOKEN。


3. API 端点

3.1 健康检查

GET /api/agnet/health

检查服务状态。

请求示例:

curl -X GET "http://agent-manager.taijiagnet.com/api/agnet/health" \
  -H "Authorization: Bearer sk_xxx"

响应示例:

{
  "success": true,
  "data": {
    "status": "healthy",
    "service": "agent-manager-agnet",
    "version": "1.0.0",
    "phase": "2-deployments"
  }
}

3.2 创建部署

POST /api/agnet/deployments

创建一个新的 Agent 部署。

请求体:

{
  "orchestration_plan": "multi-agent-workflow",
  "risk_level": "medium",
  "approval_token": "optional_for_high_risk",
  "budget": {
    "max_usd": 100.0,
    "alert_threshold_pct": 80
  },
  "billing_context": {
    "provider": "newapi",
    "default_model_id": "gpt-4",
    "allowed_model_ids": ["gpt-4", "gpt-3.5-turbo"],
    "secret_ref": "vault:heicode/model-gateway-key"
  },
  "agents": [
    {
      "role": "researcher",
      "image": "agnettaiji.azurecr.io/ai-agents/search-agent:latest"
    },
    {
      "role": "writer",
      "image": "agnettaiji.azurecr.io/ai-agents/doc-creator:latest"
    }
  ],
  "resource_grants": [
    {
      "type": "database",
      "ref": "vault:heicode/db-credentials"
    }
  ]
}

响应示例:

{
  "deployment_id": "dep_a1b2c3d4e5f6",
  "status": "pending",
  "agent_instances": [
    {
      "agent_instance_id": "agi_123abc",
      "role": "researcher",
      "status": "pending",
      "phase": null
    },
    {
      "agent_instance_id": "agi_456def",
      "role": "writer",
      "status": "pending",
      "phase": null
    }
  ],
  "created_at": "2026-05-12T10:30:00Z",
  "estimated_ready_at": "2026-05-12T10:32:00Z"
}

3.3 列出部署

GET /api/agnet/deployments

获取部署列表,支持过滤和分页。

查询参数:

参数 类型 必需 说明
user_id string ⚪ 按用户过滤
binding_scope string ⚪ 按绑定范围过滤
status string ⚪ 按状态过滤 (pending/running/stopped/failed)
limit integer ⚪ 每页数量 (默认 50, 最大 200)
cursor string ⚪ 分页游标

请求示例:

curl -X GET "http://agent-manager.taijiagnet.com/api/agnet/deployments?user_id=user_123&status=running&limit=10" \
  -H "Authorization: Bearer sk_xxx" \
  -H "X-User-ID: user_123" \
  -H "X-Binding-Scope: workspace_abc" \
  -H "X-Correlation-ID: req_list_001"

响应示例:

{
  "deployments": [
    {
      "deployment_id": "dep_a1b2c3d4e5f6",
      "status": "running",
      "risk_level": "medium",
      "budget": {
        "max_usd": 100.0,
        "consumed_usd": 23.5,
        "remaining_usd": 76.5
      },
      "created_at": "2026-05-12T10:30:00Z",
      "agent_instances_count": 2
    }
  ],
  "pagination": {
    "next_cursor": null,
    "has_more": false
  }
}

3.4 获取部署详情

GET /api/agnet/deployments/{deployment_id}

获取指定部署的详细信息。

路径参数:

  • deployment_id: 部署 ID

请求示例:

curl -X GET "http://agent-manager.taijiagnet.com/api/agnet/deployments/dep_a1b2c3d4e5f6" \
  -H "Authorization: Bearer sk_xxx" \
  -H "X-User-ID: user_123" \
  -H "X-Binding-Scope: workspace_abc" \
  -H "X-Correlation-ID: req_get_001"

响应示例:

{
  "deployment_id": "dep_a1b2c3d4e5f6",
  "user_id": "user_123",
  "binding_scope": "workspace_abc",
  "status": "running",
  "phase": "executing",
  "orchestration_plan": "multi-agent-workflow",
  "risk_level": "medium",
  "budget": {
    "max_usd": 100.0,
    "consumed_usd": 23.5,
    "remaining_usd": 76.5
  },
  "billing_context": {
    "provider": "newapi",
    "default_model_id": "gpt-4",
    "allowed_model_ids": ["gpt-4", "gpt-3.5-turbo"]
  },
  "agent_instances": [
    {
      "agent_instance_id": "agi_123abc",
      "role": "researcher",
      "status": "running",
      "phase": "searching"
    },
    {
      "agent_instance_id": "agi_456def",
      "role": "writer",
      "status": "running",
      "phase": "writing"
    }
  ],
  "resource_grants": [
    {
      "type": "database",
      "ref": "vault:heicode/db-credentials"
    }
  ],
  "created_at": "2026-05-12T10:30:00Z",
  "updated_at": "2026-05-12T10:35:00Z"
}

3.5 停止部署

POST /api/agnet/deployments/{deployment_id}/stop

停止一个正在运行的部署。

路径参数:

  • deployment_id: 部署 ID

请求体:

{
  "reason": "User requested stop",
  "approval_token": "optional_for_high_risk"
}

请求示例:

curl -X POST "http://agent-manager.taijiagnet.com/api/agnet/deployments/dep_a1b2c3d4e5f6/stop" \
  -H "Authorization: Bearer sk_xxx" \
  -H "X-User-ID: user_123" \
  -H "X-Binding-Scope: workspace_abc" \
  -H "X-Correlation-ID: req_stop_001" \
  -H "Content-Type: application/json" \
  -d '{
    "reason": "Task completed"
  }'

响应示例:

{
  "deployment_id": "dep_a1b2c3d4e5f6",
  "status": "stopped",
  "stopped_at": "2026-05-12T11:00:00Z"
}

3.6 获取部署日志

GET /api/agnet/deployments/{deployment_id}/logs

获取部署的实时日志。

路径参数:

  • deployment_id: 部署 ID

查询参数:

参数 类型 必需 说明
agent_instance_id string ⚪ 按 Agent 实例过滤
since datetime ⚪ 起始时间 (ISO 8601)
limit integer ⚪ 日志条数 (默认 100)

请求示例:

curl -X GET "http://agent-manager.taijiagnet.com/api/agnet/deployments/dep_a1b2c3d4e5f6/logs?limit=50" \
  -H "Authorization: Bearer sk_xxx" \
  -H "X-User-ID: user_123" \
  -H "X-Binding-Scope: workspace_abc" \
  -H "X-Correlation-ID: req_logs_001"

响应示例:

{
  "deployment_id": "dep_a1b2c3d4e5f6",
  "logs": [
    {
      "timestamp": "2026-05-12T10:31:00Z",
      "agent_instance_id": "agi_123abc",
      "level": "info",
      "message": "Starting search task...",
      "source": "stdout"
    },
    {
      "timestamp": "2026-05-12T10:31:05Z",
      "agent_instance_id": "agi_123abc",
      "level": "info",
      "message": "Found 10 relevant documents",
      "source": "stdout"
    }
  ],
  "pagination": {
    "has_more": false
  }
}

3.7 获取部署事件

GET /api/agnet/deployments/{deployment_id}/events

获取部署的事件历史。

路径参数:

  • deployment_id: 部署 ID

查询参数:

参数 类型 必需 说明
event_type string ⚪ 事件类型过滤
since datetime ⚪ 起始时间 (ISO 8601)
limit integer ⚪ 事件条数 (默认 100)

事件类型:

  • deployment.accepted - 部署已接受
  • deployment.started - 部署已启动
  • deployment.stopped - 部署已停止
  • deployment.failed - 部署失败
  • agent.started - Agent 启动
  • agent.completed - Agent 完成
  • budget.alert - 预算告警

请求示例:

curl -X GET "http://agent-manager.taijiagnet.com/api/agnet/deployments/dep_a1b2c3d4e5f6/events" \
  -H "Authorization: Bearer sk_xxx" \
  -H "X-User-ID: user_123" \
  -H "X-Binding-Scope: workspace_abc" \
  -H "X-Correlation-ID: req_events_001"

响应示例:

{
  "deployment_id": "dep_a1b2c3d4e5f6",
  "events": [
    {
      "event_id": "evt_abc123",
      "event_type": "deployment.accepted",
      "agent_instance_id": null,
      "occurred_at": "2026-05-12T10:30:00Z",
      "payload": {
        "risk_level": "medium"
      }
    },
    {
      "event_id": "evt_def456",
      "event_type": "agent.started",
      "agent_instance_id": "agi_123abc",
      "occurred_at": "2026-05-12T10:31:00Z",
      "payload": {
        "role": "researcher"
      }
    }
  ],
  "pagination": {
    "has_more": false
  }
}

3.8 获取资源指标

GET /api/agnet/deployments/{deployment_id}/metrics

获取部署的资源使用指标。

路径参数:

  • deployment_id: 部署 ID

请求示例:

curl -X GET "http://agent-manager.taijiagnet.com/api/agnet/deployments/dep_a1b2c3d4e5f6/metrics" \
  -H "Authorization: Bearer sk_xxx" \
  -H "X-User-ID: user_123" \
  -H "X-Binding-Scope: workspace_abc" \
  -H "X-Correlation-ID: req_metrics_001"

响应示例:

{
  "deployment_id": "dep_a1b2c3d4e5f6",
  "timestamp": "2026-05-12T10:35:00Z",
  "agent_metrics": [
    {
      "agent_instance_id": "agi_123abc",
      "role": "researcher",
      "status": "running",
      "resources": {
        "cpu_usage_cores": 0.25,
        "memory_usage_mb": 256.0,
        "network_rx_bytes": 1048576,
        "network_tx_bytes": 524288
      },
      "uptime_seconds": 300
    },
    {
      "agent_instance_id": "agi_456def",
      "role": "writer",
      "status": "running",
      "resources": {
        "cpu_usage_cores": 0.15,
        "memory_usage_mb": 128.0,
        "network_rx_bytes": 524288,
        "network_tx_bytes": 262144
      },
      "uptime_seconds": 300
    }
  ],
  "total_resources": {
    "cpu_usage_cores": 0.40,
    "memory_usage_mb": 384.0,
    "network_rx_bytes": 1572864,
    "network_tx_bytes": 786432
  }
}

4. 数据模型

4.1 部署状态 (DeploymentStatus)

状态 说明
pending 等待启动
running 运行中
stopped 已停止
failed 失败

4.2 风险等级 (RiskLevel)

等级 说明 审批要求
low 低风险 无需审批
medium 中风险 无需审批
high 高风险 需要 approval_token

4.3 计费提供商 (BillingProvider)

提供商 说明
newapi Heicode NewAPI Gateway
litellm LiteLLM Proxy

4.4 资源授权类型 (ResourceGrantType)

类型 说明
database 数据库访问
storage 存储访问
api API 访问
custom 自定义资源

5. 使用示例

5.1 完整工作流示例

import requests
import time

# 配置
BASE_URL = "http://agent-manager.taijiagnet.com"
TOKEN = "sk_your_service_token"
USER_ID = "user_123"
BINDING_SCOPE = "workspace_abc"

headers = {
    "Authorization": f"Bearer {TOKEN}",
    "X-User-ID": USER_ID,
    "X-Binding-Scope": BINDING_SCOPE,
    "X-Correlation-ID": f"req_{int(time.time())}",
    "Content-Type": "application/json"
}

# 1. 创建部署
create_payload = {
    "orchestration_plan": "research-and-write",
    "risk_level": "medium",
    "budget": {
        "max_usd": 50.0,
        "alert_threshold_pct": 80
    },
    "billing_context": {
        "provider": "newapi",
        "default_model_id": "gpt-4",
        "allowed_model_ids": ["gpt-4", "gpt-3.5-turbo"],
        "secret_ref": "vault:heicode/model-gateway-key"
    },
    "agents": [
        {
            "role": "researcher",
            "image": "agnettaiji.azurecr.io/ai-agents/search-agent:latest"
        },
        {
            "role": "writer",
            "image": "agnettaiji.azurecr.io/ai-agents/doc-creator:latest"
        }
    ],
    "resource_grants": []
}

response = requests.post(
    f"{BASE_URL}/api/agnet/deployments",
    headers=headers,
    json=create_payload
)
deployment = response.json()
deployment_id = deployment["deployment_id"]
print(f"✅ 部署创建成功: {deployment_id}")

# 2. 等待部署就绪
time.sleep(120)  # 等待 2 分钟

# 3. 获取部署详情
response = requests.get(
    f"{BASE_URL}/api/agnet/deployments/{deployment_id}",
    headers=headers
)
details = response.json()
print(f"📊 部署状态: {details['status']}")

# 4. 获取实时日志
response = requests.get(
    f"{BASE_URL}/api/agnet/deployments/{deployment_id}/logs?limit=20",
    headers=headers
)
logs = response.json()
print(f"📝 最新日志: {len(logs['logs'])} 条")

# 5. 获取资源指标
response = requests.get(
    f"{BASE_URL}/api/agnet/deployments/{deployment_id}/metrics",
    headers=headers
)
metrics = response.json()
print(f"💻 CPU 使用: {metrics['total_resources']['cpu_usage_cores']} cores")
print(f"💾 内存使用: {metrics['total_resources']['memory_usage_mb']} MB")

# 6. 停止部署
stop_payload = {
    "reason": "Task completed successfully"
}
response = requests.post(
    f"{BASE_URL}/api/agnet/deployments/{deployment_id}/stop",
    headers=headers,
    json=stop_payload
)
result = response.json()
print(f"🛑 部署已停止: {result['stopped_at']}")

5.2 幂等性示例

使用 X-Idempotency-Key 确保请求幂等性:

import uuid

idempotency_key = f"idem_{uuid.uuid4().hex}"

headers = {
    "Authorization": f"Bearer {TOKEN}",
    "X-User-ID": USER_ID,
    "X-Binding-Scope": BINDING_SCOPE,
    "X-Correlation-ID": f"req_{int(time.time())}",
    "X-Idempotency-Key": idempotency_key,  # 幂等性键
    "Content-Type": "application/json"
}

# 第一次请求
response1 = requests.post(
    f"{BASE_URL}/api/agnet/deployments",
    headers=headers,
    json=create_payload
)

# 重复请求(使用相同的 idempotency_key)
response2 = requests.post(
    f"{BASE_URL}/api/agnet/deployments",
    headers=headers,
    json=create_payload
)

# response1 和 response2 返回相同的结果
assert response1.json()["deployment_id"] == response2.json()["deployment_id"]

6. 错误处理

6.1 错误响应格式

所有错误响应遵循统一格式:

{
  "success": false,
  "error": {
    "code": "ERROR_CODE",
    "message": "Human-readable error message",
    "request_id": "req_xyz789"
  }
}

6.2 错误码列表

HTTP 状态码 错误码 说明
401 UNAUTHORIZED 认证失败,Token 无效
403 FORBIDDEN 权限不足
404 DEPLOYMENT_NOT_FOUND 部署不存在
409 DEPLOYMENT_CONFLICT 部署状态冲突
422 MODEL_NOT_ALLOWED 模型不在允许列表中
422 POLICY_REJECTED 策略拒绝(如高风险需审批)
422 VALIDATION_ERROR 请求参数验证失败
500 INTERNAL_ERROR 服务器内部错误

6.3 错误处理示例

try:
    response = requests.post(
        f"{BASE_URL}/api/agnet/deployments",
        headers=headers,
        json=create_payload
    )
    response.raise_for_status()
    deployment = response.json()
    
except requests.exceptions.HTTPError as e:
    error_data = e.response.json()
    error_code = error_data["error"]["code"]
    error_message = error_data["error"]["message"]
    
    if error_code == "MODEL_NOT_ALLOWED":
        print(f"❌ 模型配置错误: {error_message}")
    elif error_code == "POLICY_REJECTED":
        print(f"❌ 需要审批: {error_message}")
    else:
        print(f"❌ 请求失败: {error_message}")

7. 最佳实践

7.1 认证和安全

✅ 推荐做法:

  • 将 Service Token 存储在环境变量或密钥管理系统中
  • 使用 HTTPS 进行所有 API 调用
  • 定期轮换 Service Token
  • 使用 Vault 存储敏感配置(如 API Key)

❌ 避免:

  • 在代码中硬编码 Token
  • 在日志中打印 Token
  • 在 URL 参数中传递敏感信息

7.2 幂等性

✅ 推荐做法:

  • 对所有创建操作使用 X-Idempotency-Key
  • 使用 UUID 或时间戳生成唯一的幂等性键
  • 在网络不稳定时重试请求

7.3 预算控制

✅ 推荐做法:

  • 设置合理的 max_usd 预算上限
  • 设置 alert_threshold_pct 为 80-90%
  • 定期检查 consumed_usd 和 remaining_usd
  • 在预算告警时及时停止部署

7.4 日志和监控

✅ 推荐做法:

  • 使用 X-Correlation-ID 追踪请求链路
  • 定期轮询 /logs 和 /events 端点
  • 监控 /metrics 端点的资源使用情况
  • 保存审计日志用于问题排查

7.5 错误处理

✅ 推荐做法:

  • 实现指数退避重试机制
  • 区分可重试错误(5xx)和不可重试错误(4xx)
  • 记录完整的错误上下文(request_id, correlation_id)
  • 为高风险操作准备回滚方案

7.6 性能优化

✅ 推荐做法:

  • 使用分页参数避免一次性获取大量数据
  • 缓存不常变化的数据(如模板列表)
  • 使用 since 参数增量获取日志和事件
  • 并发调用独立的 API 端点

8. 附录

8.1 支持的 Agent 镜像

Agent 类型 镜像地址 说明
Search Agent agnettaiji.azurecr.io/ai-agents/search-agent:latest 搜索和信息检索
Doc Creator agnettaiji.azurecr.io/ai-agents/doc-creator:latest 文档生成
Code AI Agent agnettaiji.azurecr.io/ai-agents/code-ai-agent:latest 代码生成和 CI/CD
Ad Creator agnettaiji.azurecr.io/ai-agents/ad-creator:latest 广告创意生成
Video Generator agnettaiji.azurecr.io/ai-agents/video-generator:latest 视频生成

8.2 联系方式

8.3 更新日志

版本 日期 更新内容
v2.0.0 2026-05-12 初始版本,支持 Heicode 集成

文档版本: v2.0.0
最后更新: 2026-05-12
维护者: Agent Manager Team