Files
agent_management/API_DOCUMENTATION.md
T
2026-01-12 15:04:11 +00:00

38 KiB
Raw Blame History

Agent Manager API 接口文档

基础信息

  • Base URL: http://localhost:8000
  • 版本: v1.0.0
  • 协议: HTTP/HTTPS
  • 数据格式: JSON

目录

  1. Agent 管理
  2. 模板查询
  3. 状态监控
  4. 资源管理

Agent 管理

1. 创建 Agent

创建一个新的 AI Agent 实例。

请求

POST /agents
Content-Type: application/json

请求参数

{
  "name": "agent-name",           // 必填,Agent名称,必须唯一
  "template": "echo_agent",       // 必填,模板类型
  "config": {                     // 必填,配置信息
    "user_id": "user-001",        // 推荐,用户标识,用于多租户管理
    "cpu_request": "100m",        // 可选,CPU请求量
    "cpu_limit": "500m",          // 可选,CPU限制
    "memory_request": "128Mi",    // 可选,内存请求量
    "memory_limit": "512Mi"       // 可选,内存限制
  },
  "env_variables": {                        // 可选,环境变量
    "KEY": "value"
  }
}

支持的模板类型

模板 说明 类型 框架
echo_agent Echo 测试服务 平台 -
chat_agent 聊天服务 平台 -
code_agent 代码执行服务 平台 -
search_agent 搜索服务 平台 -
jina_search_agent Jina 搜索服务 平台 -
mysql_agent MySQL 客户端 自定义 -
postgresql_agent PostgreSQL 客户端 自定义 -
azure_blob_agent Azure Blob Storage 客户端 (LangChain) 自定义 LangChain
azure_blob_agent_mcp Azure Blob Storage 客户端 (MCP) 自定义 MCP
azure_blob_agent_a2a Azure Blob Storage 客户端 (A2A) 自定义 A2A

Agent 框架说明

从 v1.1.0 开始,Agent Manager 支持多种 AI Agent 框架:

框架 说明 适用场景
LangChain 使用 LangChain + LiteLLM 复杂推理任务、多步骤处理流程
MCP Model Context Protocol 标准化工具调用、轻量级集成
A2A Agent-to-Agent 多 Agent 协作、分布式任务处理

多框架支持的配置参数

创建支持多框架的 Agent 时,可以使用以下额外参数:

{
  "name": "agent-name",
  "template": "azure_blob_agent_mcp",
  "config": {
    // 基础配置
    "user_id": "user-001",
    "tenant_id": "tenant-001",
    "namespace": "ai-agents",
    
    // 框架配置
    "agent_framework": "mcp",           // 框架类型: langchain, mcp, a2a
    
    // 工具配置
    "tools_config": {                   // 工具配置 JSON
      "max_iterations": 5,
      "enabled_tools": ["list_containers", "list_blobs"]
    },
    "tool_endpoint": "http://tools-api:8080",  // 外部工具端点
    "tool_api_key": "tool-key",                // 工具 API 密钥
    
    // 模型配置
    "model_provider": "openai",               // 模型提供商: openai, azure-openai
    "model_name": "gpt-4",                    // 模型名称
    "model_endpoint": "https://api.openai.com/v1",  // 模型端点
    "model_api_key": "sk-xxxx",               // 模型 API 密钥
    
    // 存储配置 (针对 Azure Blob Agent)
    "storage_connection_string": "DefaultEndpointsProtocol=https;...",
    "storage_account_name": "myaccount",
    
    // 资源配置
    "cpu_request": "100m",
    "cpu_limit": "500m",
    "memory_request": "256Mi",
    "memory_limit": "512Mi"
  }
}

响应

{
  "name": "agent-name",
  "namespace": "ai-agents",
  "status": "Pending",
  "created_at": "2026-01-05T07:35:00+00:00",
  "template": "echo_agent",
  "service_port": null,
  "access_info": null,
  "pod_id": "111175ce-8118-484d-9b3e-009733644acf",
  "pod_ip": "10.244.2.24",
  "host_ip": "10.224.0.5",
  "node_name": "aks-node-123",
  "owner_info": {
    "user_id": "user-001",
    "agent_name": "agent-name",
    "namespace": "ai-agents",
    "labels": {
      "app": "ai-agent",
      "managed-by": "agent-manager",
      "template": "echo_agent",
      "user-id": "user-001"
    }
  }
}

状态码

  • 201 - 创建成功
  • 400 - 请求参数错误
  • 409 - Agent 已存在
  • 500 - 服务器内部错误

示例

基础示例 - Echo Agent:

curl -X POST http://localhost:8000/agents \
  -H "Content-Type: application/json" \
  -d '{
    "name": "alice-echo",
    "template": "echo_agent",
    "config": {
      "user_id": "alice"
    }
  }'

Azure Blob Agent (LangChain 版本) - 提供连接字符串:

curl -X POST http://localhost:8000/agents \
  -H "Content-Type: application/json" \
  -d '{
    "name": "my-azure-blob-agent",
    "template": "azure_blob_agent",
    "config": {
      "user_id": "alice"
    },
    "env": {
      "LITELLM_API_BASE": "http://litellm-service:4000",
      "LITELLM_MODEL": "gpt-4",
      "LITELLM_API_KEY": "sk-your-api-key",
      "AZURE_STORAGE_CONNECTION_STRING": "DefaultEndpointsProtocol=https;AccountName=youraccount;AccountKey=yourkey;EndpointSuffix=core.windows.net",
      "SERVICE_PORT": "8080"
    }
  }'

Azure Blob Agent (MCP 版本) - 标准化工具调用:

curl -X POST http://localhost:8000/agents \
  -H "Content-Type: application/json" \
  -d '{
    "name": "my-blob-mcp",
    "template": "azure_blob_agent_mcp",
    "config": {
      "user_id": "alice",
      "tenant_id": "tenant-001",
      "namespace": "ai-agents",
      "agent_framework": "mcp",
      "model_provider": "openai",
      "model_name": "gpt-4",
      "model_api_key": "sk-your-api-key",
      "model_endpoint": "https://api.openai.com/v1",
      "storage_connection_string": "DefaultEndpointsProtocol=https;AccountName=youraccount;AccountKey=yourkey;EndpointSuffix=core.windows.net",
      "tools_config": {
        "max_iterations": 5,
        "enabled_tools": ["list_containers", "list_blobs", "search_blobs"]
      },
      "cpu_request": "100m",
      "memory_request": "256Mi"
    }
  }'

Azure Blob Agent (A2A 版本) - Agent 间协作:

curl -X POST http://localhost:8000/agents \
  -H "Content-Type: application/json" \
  -d '{
    "name": "my-blob-a2a",
    "template": "azure_blob_agent_a2a",
    "config": {
      "user_id": "alice",
      "tenant_id": "tenant-001",
      "namespace": "ai-agents",
      "agent_framework": "a2a",
      "model_provider": "azure-openai",
      "model_name": "gpt-4",
      "model_api_key": "your-azure-openai-key",
      "model_endpoint": "https://your-resource.openai.azure.com",
      "storage_connection_string": "DefaultEndpointsProtocol=https;AccountName=youraccount;AccountKey=yourkey;EndpointSuffix=core.windows.net",
      "cpu_request": "100m",
      "memory_request": "256Mi"
    },
    "env": {
      "AGENT_ID": "blob-agent-001",
      "AGENT_ROLE": "storage_manager",
      "AGENT_CAPABILITIES": "[\"blob_storage\", \"file_operations\"]"
    }
  }'

测试部署后的 Agent

LangChain 版本测试:

获取 Pod IP 并测试:

# 1. 检查 Agent 状态
curl -s http://localhost:8000/agents/my-azure-blob-agent/status | jq '{status, health_status, pod_ip, access_url}'

# 2. 获取 Pod IP
POD_IP=$(curl -s http://localhost:8000/agents/my-azure-blob-agent/status | jq -r '.pod_ip')
echo "Pod IP: $POD_IP"

# 3. 测试健康检查
curl http://$POD_IP:8080/health

# 4. 查看 Agent 信息
curl http://$POD_IP:8080/ | jq .

# 5. 如果启动时未提供连接字符串,可以动态连接
curl -X POST http://$POD_IP:8080/connect \
  -H "Content-Type: application/json" \
  -d '{
    "connection_string": "DefaultEndpointsProtocol=https;AccountName=youraccount;AccountKey=yourkey;EndpointSuffix=core.windows.net"
  }'

# 6. 检查连接状态
curl http://$POD_IP:8080/status

# 7. 执行自然语言查询 - 列出所有容器
curl -X POST http://$POD_IP:8080/query \
  -H "Content-Type: application/json" \
  -d '{"query": "列出所有容器"}' | jq .

# 8. 查看指定容器的文件
curl -X POST http://$POD_IP:8080/query \
  -H "Content-Type: application/json" \
  -d '{"query": "显示 mycontainer 容器中的所有文件"}' | jq .

# 9. 搜索文件
curl -X POST http://$POD_IP:8080/query \
  -H "Content-Type: application/json" \
  -d '{"query": "搜索包含 report 的文件"}' | jq .

# 10. 获取存储统计
curl -X POST http://$POD_IP:8080/query \
  -H "Content-Type: application/json" \
  -d '{"query": "存储统计"}' | jq .

MCP 版本测试:

# 1. 获取 Pod IP
POD_IP=$(curl -s http://localhost:8000/agents/my-blob-mcp/status | jq -r '.pod_ip')

# 2. 测试健康检查
curl http://$POD_IP:8080/health | jq .

# 3. 查看 Agent 信息(包含框架类型)
curl http://$POD_IP:8080/ | jq .

# 4. 列出所有可用的 MCP 工具
curl http://$POD_IP:8080/mcp/tools | jq .

# 5. 调用 MCP 工具 - 列出所有容器
curl -X POST http://$POD_IP:8080/mcp/call \
  -H "Content-Type: application/json" \
  -d '{
    "tool_name": "list_containers",
    "parameters": {}
  }' | jq .

# 6. 调用 MCP 工具 - 列出容器中的文件
curl -X POST http://$POD_IP:8080/mcp/call \
  -H "Content-Type: application/json" \
  -d '{
    "tool_name": "list_blobs",
    "parameters": {
      "container_name": "mycontainer"
    }
  }' | jq .

# 7. 调用 MCP 工具 - 获取文件信息
curl -X POST http://$POD_IP:8080/mcp/call \
  -H "Content-Type: application/json" \
  -d '{
    "tool_name": "get_blob_info",
    "parameters": {
      "container_name": "mycontainer",
      "blob_name": "myfile.txt"
    }
  }' | jq .

# 8. 调用 MCP 工具 - 搜索文件
curl -X POST http://$POD_IP:8080/mcp/call \
  -H "Content-Type: application/json" \
  -d '{
    "tool_name": "search_blobs",
    "parameters": {
      "container_name": "mycontainer",
      "keyword": "report"
    }
  }' | jq .

# 9. 调用 MCP 工具 - 获取存储统计
curl -X POST http://$POD_IP:8080/mcp/call \
  -H "Content-Type: application/json" \
  -d '{
    "tool_name": "get_storage_stats",
    "parameters": {}
  }' | jq .

# 10. 使用简化的查询接口(规则匹配)
curl -X POST http://$POD_IP:8080/query \
  -H "Content-Type: application/json" \
  -d '{"query": "列出所有容器"}' | jq .

A2A 版本测试:

# 1. 获取 Pod IP
POD_IP=$(curl -s http://localhost:8000/agents/my-blob-a2a/status | jq -r '.pod_ip')

# 2. 测试健康检查(包含 Agent 身份信息)
curl http://$POD_IP:8080/health | jq .

# 3. 获取 Agent 能力
curl http://$POD_IP:8080/a2a/capabilities | jq .

# 4. 发送 A2A 消息 - 列出容器
curl -X POST http://$POD_IP:8080/a2a/message \
  -H "Content-Type: application/json" \
  -d '{
    "message_id": "msg-001",
    "from_agent": "external-caller",
    "to_agent": "blob-agent-001",
    "message_type": "request",
    "action": "list_containers",
    "parameters": {}
  }' | jq .

# 5. 发送 A2A 消息 - 列出文件
curl -X POST http://$POD_IP:8080/a2a/message \
  -H "Content-Type: application/json" \
  -d '{
    "message_id": "msg-002",
    "from_agent": "external-caller",
    "to_agent": "blob-agent-001",
    "message_type": "request",
    "action": "list_blobs",
    "parameters": {
      "container_name": "mycontainer"
    }
  }' | jq .

# 6. 发送 A2A 消息 - 获取统计
curl -X POST http://$POD_IP:8080/a2a/message \
  -H "Content-Type: application/json" \
  -d '{
    "message_id": "msg-003",
    "from_agent": "external-caller",
    "to_agent": "blob-agent-001",
    "message_type": "request",
    "action": "get_stats",
    "parameters": {}
  }' | jq .

# 7. 注册另一个 Agent(用于协作)
curl -X POST http://$POD_IP:8080/a2a/register \
  -H "Content-Type: application/json" \
  -d '{
    "agent_id": "analytics-agent",
    "agent_role": "data_analyzer",
    "capabilities": ["data_analysis", "visualization"],
    "endpoint": "http://analytics-agent:8080"
  }' | jq .

# 8. 列出已注册的 Agent
curl http://$POD_IP:8080/a2a/agents | jq .

# 9. 与其他 Agent 协作(需要先注册目标 Agent)
curl -X POST http://$POD_IP:8080/a2a/collaborate \
  -H "Content-Type: application/json" \
  -d '{
    "target_agent_id": "analytics-agent",
    "action": "analyze_data",
    "parameters": {
      "data_source": "blob_storage"
    }
  }' | jq .

-d '{"query": "统计存储使用情况"}' | jq .


---

### 2. 查询 Agent 列表

获取所有 Agent 的列表。

**请求**

```http
GET /agents

查询参数

参数 类型 必填 说明
template string 否 按模板类型过滤

响应

{
  "agents": [
    {
      "name": "alice-echo",
      "namespace": "ai-agents",
      "status": "Running",
      "template": "echo_agent",
      "pod_ip": "10.244.2.24",
      "labels": {
        "user-id": "alice"
      }
    }
  ],
  "count": 1
}

示例

# 获取所有 Agents
curl http://localhost:8000/agents

# 按模板过滤
curl http://localhost:8000/agents?template=echo_agent

3. 获取 Agent 状态

获取指定 Agent 的详细状态信息,包括 Pod 状态、容器健康状态、资源配额等。

请求

GET /agents/{agent_name}/status

路径参数

参数 类型 说明
agent_name string Agent 名称

响应 - 健康状态

{
  "name": "alice-echo",
  "namespace": "ai-agents",
  "status": "Running",
  "health_status": "healthy",
  "template": "echo_agent",
  "created_at": "2026-01-05T07:35:00+00:00",
  "node": "aks-node-123",
  "pod_ip": "10.244.2.24",
  "containers": [
    {
      "name": "alice-echo",
      "ready": true,
      "restart_count": 0,
      "state": "running",
      "started_at": "2026-01-05T07:35:15+00:00"
    }
  ],
  "resources": {
    "requests": {
      "cpu": "100m",
      "memory": "128Mi"
    },
    "limits": {
      "cpu": "500m",
      "memory": "512Mi"
    },
    "usage": {
      "cpu": "14502n",
      "memory": "8704Ki",
      "available": true
    }
  },
  "service_port": 8080,
  "access_url": "http://10.244.2.24:8080",
  "endpoints": {
    "root": "http://10.244.2.24:8080/",
    "health": "http://10.244.2.24:8080/health"
  },
  "conditions": [
    {
      "type": "Ready",
      "status": "True",
      "reason": null
    },
    {
      "type": "ContainersReady",
      "status": "True",
      "reason": null
    }
  ]
}

响应 - 崩溃状态

{
  "name": "my-mysql-agent",
  "namespace": "ai-agents",
  "status": "Waiting",
  "health_status": "unhealthy",
  "template": "mysql_agent",
  "created_at": "2026-01-04T06:40:38+00:00",
  "node": "aks-node-123",
  "pod_ip": "10.244.1.53",
  "containers": [
    {
      "name": "my-mysql-agent",
      "ready": false,
      "restart_count": 599,
      "state": "waiting",
      "reason": "CrashLoopBackOff",
      "message": "back-off 5m0s restarting failed container=my-mysql-agent pod=my-mysql-agent_ai-agents(...)"
    }
  ],
  "resources": {
    "requests": {
      "cpu": "100m",
      "memory": "128Mi"
    },
    "limits": {
      "cpu": "500m",
      "memory": "512Mi"
    },
    "usage": {
      "cpu": null,
      "memory": null,
      "available": false,
      "reason": "metrics-server未安装或Pod不存在"
    }
  },
  "conditions": [
    {
      "type": "Ready",
      "status": "False",
      "reason": "ContainersNotReady"
    },
    {
      "type": "ContainersReady",
      "status": "False",
      "reason": "ContainersNotReady"
    }
  ]
}

字段说明

字段 类型 说明
name string Agent 名称
namespace string 命名空间
status string Pod 状态 (Running/Pending/Waiting/Terminated/Failed)
health_status string 健康状态 (healthy/unhealthy/degraded)
template string 使用的模板
created_at string 创建时间 (ISO 8601)
node string 运行的节点
pod_ip string Pod IP 地址
containers array 容器详细状态
resources object 资源配额和使用情况
service_port int | null 服务端口
access_url string | null 访问地址
endpoints object | null API 端点
conditions array Pod 条件状态

健康状态说明

状态 说明
healthy 所有容器运行正常且就绪
unhealthy 容器崩溃、终止或未就绪
degraded 容器重启次数过多 (>5次)

容器状态字段

字段 类型 说明
name string 容器名称
ready boolean 是否就绪
restart_count int 重启次数
state string 状态 (running/waiting/terminated)
reason string | null 状态原因 (如 CrashLoopBackOff)
message string | null 详细消息
exit_code int | null 退出码 (terminated 状态)
started_at string | null 启动时间 (running 状态)
finished_at string | null 结束时间 (terminated 状态)

Pod 状态类型

状态 说明
Running Pod 正在运行
Pending Pod 等待调度
Waiting 容器等待启动
Terminated 容器已终止
Failed Pod 失败
Succeeded Pod 成功完成

状态码

  • 200 - 成功
  • 404 - Agent 不存在
  • 500 - 服务器内部错误

示例

# 查询健康的 Agent
curl http://localhost:8000/agents/alice-echo/status

# 查询崩溃的 Agent
curl http://localhost:8000/agents/my-mysql-agent/status

使用建议

  1. 监控告警:使用 health_status 字段而非 status 进行健康监控
  2. 故障排查:检查 containers 数组获取容器崩溃原因和重启次数
  3. 自动化运维:根据 health_status 自动触发重启或告警
  4. 日志分析:结合 restart_count 和 reason 定位问题

4. 获取 Agent 资源使用情况

获取 Agent 的 CPU 和内存使用情况。

请求

GET /agents/{agent_name}/metrics

功能说明

获取 Agent 的资源使用情况,包括:

  • requests/limits: 资源配额(从 Pod spec 获取)
  • usage: 实时资源使用情况(从 metrics-server 获取,需要集群安装 metrics-server)
  • timestamp: metrics 数据的时间戳

响应

{
  "name": "alice-echo",
  "namespace": "ai-agents",
  "requests": {
    "cpu": "100m",
    "memory": "128Mi"
  },
  "limits": {
    "cpu": "500m",
    "memory": "512Mi"
  },
  "usage": {
    "cpu": "14502n",
    "memory": "8704Ki"
  },
  "timestamp": "2026-01-06T05:01:04Z",
  "metrics_available": null
}

字段说明

字段 类型 说明
name string Pod 名称
namespace string 命名空间
requests object 资源请求配额
limits object 资源限制配额
usage object | null 实时资源使用(需要 metrics-server)
timestamp string | null metrics 时间戳(ISO 8601 格式)
metrics_available bool | null metrics-server 是否可用

CPU 单位说明

  • n (nanocores): 1 核 = 1,000,000,000n
  • m (millicores): 1 核 = 1,000m
  • 例如: 14502n = 0.014502m ≈ 0.000014 核

内存单位说明

  • Ki (Kibibytes): 1024 字节
  • Mi (Mebibytes): 1024 KiB
  • 例如: 8704Ki ≈ 8.5 MiB

示例

curl http://localhost:8000/agents/alice-echo/metrics

注意事项

  • 如果集群未安装 metrics-server,usage 和 timestamp 将为 null
  • metrics 数据由 Kubernetes metrics-server 提供,更新频率通常为 15-60 秒
  • usage 显示的是 Pod 的实际资源消耗,不是配额

5. 删除 Agent

删除指定的 Agent。

请求

DELETE /agents/{agent_name}

路径参数

参数 类型 说明
agent_name string Agent 名称

响应

{
  "message": "Agent alice-echo 删除成功"
}

状态码

  • 200 - 删除成功
  • 404 - Agent 不存在
  • 500 - 服务器内部错误

示例

curl -X DELETE http://localhost:8000/agents/alice-echo

模板查询

1. 获取所有模板

获取所有可用的 Agent 模板列表。

请求

GET /templates

响应

{
  "templates": [
    {
      "template": "echo_agent",
      "port": null,
      "env_info": {}
    },
    {
      "template": "jina_search_agent",
      "port": 8080,
      "env_info": {}
    },
    {
      "template": "mysql_agent",
      "port": null,
      "env_info": {
        "required": {
          "MYSQL_HOST": "MySQL数据库主机地址",
          "MYSQL_USER": "MySQL用户名",
          "MYSQL_PASSWORD": "MySQL密码",
          "MYSQL_DATABASE": "MySQL数据库名",
          "OPENAI_API_KEY": "OpenAI API密钥"
        },
        "optional": {
          "MYSQL_PORT": "MySQL端口,默认3306"
        }
      }
    }
  ],
  "count": 7
}

示例

curl http://localhost:8000/templates

2. 获取平台模板

获取平台提供的标准 Agent 模板列表。

请求

GET /templates/platform

响应

{
  "templates": [
    {
      "template": "echo_agent",
      "type": "platform",
      "port": null,
      "env_info": {}
    },
    {
      "template": "chat_agent",
      "type": "platform",
      "port": null,
      "env_info": {}
    },
    {
      "template": "code_agent",
      "type": "platform",
      "port": null,
      "env_info": {}
    },
    {
      "template": "search_agent",
      "type": "platform",
      "port": null,
      "env_info": {}
    },
    {
      "template": "jina_search_agent",
      "type": "platform",
      "port": 8080,
      "env_info": {}
    }
  ],
  "count": 5,
  "type": "platform"
}

平台模板说明

  • echo_agent: 简单的 Echo 服务,用于测试
  • chat_agent: 聊天对话服务
  • code_agent: 代码生成和执行服务
  • search_agent: 通用搜索服务
  • jina_search_agent: 基于 Jina 的向量搜索服务(端口: 8080)

示例

curl http://localhost:8000/templates/platform

3. 获取自定义模板

获取需要用户配置环境变量的自定义 Agent 模板列表。

请求

GET /templates/custom

响应

{
  "templates": [
    {
      "template": "mysql_agent",
      "type": "custom",
      "port": null,
      "env_info": {
        "required": {
          "MYSQL_HOST": "MySQL数据库主机地址",
          "MYSQL_USER": "MySQL用户名",
          "MYSQL_PASSWORD": "MySQL密码",
          "MYSQL_DATABASE": "MySQL数据库名",
          "OPENAI_API_KEY": "OpenAI API密钥"
        },
        "optional": {
          "MYSQL_PORT": "MySQL端口,默认3306"
        }
      }
    },
    {
      "template": "postgresql_agent",
      "type": "custom",
      "port": null,
      "env_info": {
        "required": {
          "POSTGRES_HOST": "PostgreSQL数据库主机地址",
          "POSTGRES_USER": "PostgreSQL用户名",
          "POSTGRES_PASSWORD": "PostgreSQL密码",
          "POSTGRES_DATABASE": "PostgreSQL数据库名",
          "OPENAI_API_KEY": "OpenAI API密钥"
        },
        "optional": {
          "POSTGRES_PORT": "PostgreSQL端口,默认5432"
        }
      }
    }
  ],
  "count": 2,
  "type": "custom"
}

自定义模板说明

自定义模板需要用户在创建时通过 env 参数提供必需的环境变量。

示例:创建 MySQL Agent

curl -X POST http://localhost:8000/agents \
  -H "Content-Type: application/json" \
  -d '{
    "name": "my-mysql-agent",
    "template": "mysql_agent",
    "config": {
      "user_id": "alice"
    },
    "env": {
      "MYSQL_HOST": "mysql.example.com",
      "MYSQL_USER": "root",
      "MYSQL_PASSWORD": "password",
      "MYSQL_DATABASE": "mydb",
      "OPENAI_API_KEY": "sk-..."
    }
  }'

示例

curl http://localhost:8000/templates/custom

4. 获取指定模板详情

获取单个模板的详细信息。

请求

GET /templates/{template_name}

路径参数

参数 类型 说明
template_name string 模板名称

响应

{
  "template": "mysql_agent",
  "port": null,
  "env_info": {
    "required": {
      "MYSQL_HOST": "MySQL数据库主机地址",
      "MYSQL_USER": "MySQL用户名",
      "MYSQL_PASSWORD": "MySQL密码",
      "MYSQL_DATABASE": "MySQL数据库名",
      "OPENAI_API_KEY": "OpenAI API密钥"
    },
    "optional": {
      "MYSQL_PORT": "MySQL端口,默认3306"
    }
  }
}

状态码

  • 200 - 成功
  • 404 - 模板不存在

示例

curl http://localhost:8000/templates/mysql_agent

状态监控

健康检查

检查服务是否正常运行。

请求

GET /

响应

{
  "service": "Agent Manager API",
  "version": "1.0.0",
  "status": "running"
}

示例

curl http://localhost:8000/

多租户管理

按用户查询 Agents

使用 Kubernetes 标签选择器按用户 ID 查询 Agents。

方法 1: 通过 kubectl

# 查询特定用户的所有 Agents
kubectl get pods -n ai-agents -l user-id=alice

# 查看详细信息
kubectl get pods -n ai-agents -l user-id=alice \
  -o custom-columns=NAME:.metadata.name,POD_ID:.metadata.uid,STATUS:.status.phase

方法 2: 通过 API 查询后过滤

curl http://localhost:8000/agents | \
  jq '.agents[] | select(.labels["user-id"]=="alice")'

验证 Pod 归属

通过 Pod ID 验证

# 通过 Pod ID 查询
kubectl get pods -n ai-agents -o json | \
  jq ".items[] | select(.metadata.uid==\"$POD_ID\")"

通过 user-id 标签验证

kubectl get pod <pod-name> -n ai-agents \
  -o jsonpath='{.metadata.labels.user-id}'

错误码

HTTP 状态码

状态码 说明
200 请求成功
201 创建成功
400 请求参数错误
404 资源不存在
409 资源冲突(如 Agent 已存在)
500 服务器内部错误

错误响应格式

{
  "detail": "错误详细信息"
}

使用示例

Python SDK 示例

import requests

class AgentManagerClient:
    def __init__(self, base_url="http://localhost:8000"):
        self.base_url = base_url
    
    def create_agent(self, name, template, user_id, env=None):
        """创建 Agent"""
        payload = {
            "name": name,
            "template": template,
            "config": {"user_id": user_id},
            "env": env or {}
        }
        response = requests.post(
            f"{self.base_url}/agents",
            json=payload
        )
        response.raise_for_status()
        return response.json()
    
    def get_agent_status(self, name):
        """获取 Agent 状态"""
        response = requests.get(
            f"{self.base_url}/agents/{name}/status"
        )
        response.raise_for_status()
        return response.json()
    
    def list_agents(self, template=None):
        """列出所有 Agents"""
        params = {"template": template} if template else {}
        response = requests.get(
            f"{self.base_url}/agents",
            params=params
        )
        response.raise_for_status()
        return response.json()
    
    def delete_agent(self, name):
        """删除 Agent"""
        response = requests.delete(
            f"{self.base_url}/agents/{name}"
        )
        response.raise_for_status()
        return response.json()
    
    def list_templates(self, type=None):
        """列出模板"""
        if type == "platform":
            url = f"{self.base_url}/templates/platform"
        elif type == "custom":
            url = f"{self.base_url}/templates/custom"
        else:
            url = f"{self.base_url}/templates"
        
        response = requests.get(url)
        response.raise_for_status()
        return response.json()

# 使用示例
client = AgentManagerClient()

# 创建 Agent
result = client.create_agent(
    name="alice-echo",
    template="echo_agent",
    user_id="alice"
)
print(f"✅ Agent 创建成功,Pod ID: {result['pod_id']}")

# 查询状态
status = client.get_agent_status("alice-echo")
print(f"Agent 状态: {status['status']}")

# 列出所有 Agents
agents = client.list_agents()
print(f"总共 {agents['count']} 个 Agents")

# 删除 Agent
client.delete_agent("alice-echo")
print("✅ Agent 删除成功")

JavaScript/Node.js 示例

const axios = require('axios');

class AgentManagerClient {
  constructor(baseURL = 'http://localhost:8000') {
    this.client = axios.create({ baseURL });
  }

  async createAgent(name, template, userId, env = {}) {
    const response = await this.client.post('/agents', {
      name,
      template,
      config: { user_id: userId },
      env
    });
    return response.data;
  }

  async getAgentStatus(name) {
    const response = await this.client.get(`/agents/${name}/status`);
    return response.data;
  }

  async listAgents(template = null) {
    const params = template ? { template } : {};
    const response = await this.client.get('/agents', { params });
    return response.data;
  }

  async deleteAgent(name) {
    const response = await this.client.delete(`/agents/${name}`);
    return response.data;
  }

  async listTemplates(type = null) {
    let url = '/templates';
    if (type === 'platform') url = '/templates/platform';
    if (type === 'custom') url = '/templates/custom';
    
    const response = await this.client.get(url);
    return response.data;
  }
}

// 使用示例
(async () => {
  const client = new AgentManagerClient();

  // 创建 Agent
  const result = await client.createAgent('bob-chat', 'chat_agent', 'bob');
  console.log(`✅ Agent 创建成功,Pod ID: ${result.pod_id}`);

  // 查询状态
  const status = await client.getAgentStatus('bob-chat');
  console.log(`Agent 状态: ${status.status}`);

  // 列出平台模板
  const templates = await client.listTemplates('platform');
  console.log(`平台模板: ${templates.count} 个`);
})();

附录

A. 资源配置建议

Agent 类型 CPU Request CPU Limit Memory Request Memory Limit
echo_agent 100m 500m 128Mi 512Mi
chat_agent 200m 1000m 256Mi 1Gi
code_agent 500m 2000m 512Mi 2Gi
search_agent 200m 1000m 256Mi 1Gi
mysql_agent 100m 500m 128Mi 512Mi
postgresql_agent 100m 500m 128Mi 512Mi
jina_search_agent 500m 2000m 1Gi 4Gi

B. 命名规范

  • Agent 名称: 小写字母、数字、连字符,长度 1-63 字符
  • 推荐格式: {user_id}-{type} 或 {user_id}-{type}-{number}
  • 示例: alice-echo, bob-chat-001, team-a-search

C. 标签说明

所有创建的 Agent 自动包含以下标签:

标签 说明 示例值
app 应用类型 ai-agent
template 模板类型 echo_agent
managed-by 管理器标识 agent-manager
user-id 用户标识 alice, bob

更新日志

v1.0.0 (2026-01-05)

  • ✅ 实现 Agent 创建和管理
  • ✅ 支持 10 种 Agent 模板(包含 3 种框架版本)
  • ✅ 多租户支持(user-id 标签)
  • ✅ 多框架支持(LangChain、MCP、A2A)
  • ✅ Pod ID 返回和归属验证
  • ✅ 模板分类查询(平台/自定义)
  • ✅ 资源监控和状态查询
  • ✅ 可自定义命名空间

多框架 Agent 支持 (v1.1.0+)

框架对比

特性 LangChain MCP A2A
实现方式 LangChain + LiteLLM Model Context Protocol Agent-to-Agent Protocol
工具调用 LangChain Tools MCP Tool Classes A2A Action Handlers
主要端点 /query /mcp/tools, /mcp/call /a2a/capabilities, /a2a/message
协作能力 ❌ ❌ ✅ Agent 注册和通信
适用场景 复杂推理任务 标准化工具调用 多 Agent 协作
集成难度 中等 简单 中等

配置参数说明

通用参数(所有框架)

参数 类型 必需 说明 示例
user_id string ✅ 用户标识 "user-001"
tenant_id string ❌ 租户标识 "tenant-001"
namespace string ❌ Kubernetes 命名空间 "ai-agents"
agent_framework string ❌ 框架类型 "mcp" 或 "a2a"
cpu_request string ❌ CPU 请求量 "100m"
cpu_limit string ❌ CPU 限制 "500m"
memory_request string ❌ 内存请求量 "256Mi"
memory_limit string ❌ 内存限制 "512Mi"

模型配置参数(MCP/A2A)

参数 类型 必需 说明 示例
model_provider string ✅ 模型提供商 "openai", "azure-openai"
model_name string ✅ 模型名称 "gpt-4", "gpt-3.5-turbo"
model_api_key string ✅ 模型 API 密钥 "sk-xxxx"
model_endpoint string ❌ 模型 API 端点 "https://api.openai.com/v1"

工具配置参数(MCP/A2A)

参数 类型 必需 说明 示例
tools_config object ❌ 工具配置 JSON {"max_iterations": 5}
tool_endpoint string ❌ 外部工具端点 "http://tools-api:8080"
tool_api_key string ❌ 工具 API 密钥 "tool-key-xxx"

存储配置参数(Azure Blob Agent)

参数 类型 必需 说明
storage_connection_string string ❌ Azure Storage 连接字符串
storage_account_name string ❌ 存储账户名称

MCP 框架 API 端点

MCP Agent 部署后提供以下额外端点:

GET /mcp/tools

列出所有可用的 MCP 工具

响应示例:

{
  "tools": [
    {
      "name": "list_containers",
      "description": "列出 Azure Blob Storage 中的所有容器",
      "inputSchema": {
        "type": "object",
        "properties": {},
        "required": []
      }
    },
    {
      "name": "list_blobs",
      "description": "列出指定容器中的所有文件",
      "inputSchema": {
        "type": "object",
        "properties": {
          "container_name": {
            "type": "string",
            "description": "容器名称"
          }
        },
        "required": ["container_name"]
      }
    }
  ],
  "count": 5,
  "framework": "mcp"
}

POST /mcp/call

调用指定的 MCP 工具

请求:

{
  "tool_name": "list_blobs",
  "parameters": {
    "container_name": "mycontainer"
  }
}

响应:

{
  "tool": "list_blobs",
  "result": {
    "success": true,
    "container": "mycontainer",
    "blobs": [...],
    "count": 10,
    "total_size_mb": 125.5
  },
  "timestamp": "2026-01-12T14:50:00Z"
}

A2A 框架 API 端点

A2A Agent 部署后提供以下额外端点:

GET /a2a/capabilities

获取 Agent 的能力信息

响应示例:

{
  "agent_id": "blob-agent-001",
  "agent_role": "storage_manager",
  "capabilities": ["blob_storage", "file_operations"],
  "supported_actions": [
    "list_containers",
    "list_blobs",
    "get_blob_info",
    "search_blobs",
    "get_stats"
  ],
  "framework": "a2a"
}

POST /a2a/register

注册其他 Agent(用于协作)

请求:

{
  "agent_id": "analytics-agent",
  "agent_role": "data_analyzer",
  "capabilities": ["data_analysis", "visualization"],
  "endpoint": "http://analytics-agent:8080"
}

POST /a2a/message

发送 A2A 消息给 Agent

请求:

{
  "message_id": "msg-001",
  "from_agent": "caller-agent",
  "to_agent": "blob-agent-001",
  "message_type": "request",
  "action": "list_containers",
  "parameters": {}
}

响应:

{
  "message_id": "msg-001",
  "from_agent": "blob-agent-001",
  "to_agent": "caller-agent",
  "message_type": "response",
  "action": "list_containers",
  "result": {
    "success": true,
    "containers": [...],
    "count": 5
  },
  "timestamp": "2026-01-12T14:50:00Z"
}

GET /a2a/agents

列出已注册的 Agent

POST /a2a/collaborate

与其他 Agent 协作

命名空间支持

从 v1.1.0 开始,支持自定义 Kubernetes 命名空间:

# 在自定义命名空间中创建 Agent
curl -X POST http://localhost:8000/agents \
  -H "Content-Type: application/json" \
  -d '{
    "name": "my-agent",
    "template": "azure_blob_agent_mcp",
    "config": {
      "namespace": "my-namespace",
      "user_id": "user-001",
      ...
    }
  }'

# 查询特定命名空间的 Agent
kubectl get pods -n my-namespace -l app=ai-agent

# 通过 API 查询时,namespace 会在响应中返回
curl http://localhost:8000/agents/my-agent | jq '.namespace'

环境变量传递

创建 Agent 时,以下配置会自动转换为容器环境变量:

配置参数 环境变量名
agent_framework AGENT_FRAMEWORK
tools_config TOOLS_CONFIG (JSON字符串)
tool_endpoint TOOL_ENDPOINT
tool_api_key TOOL_API_KEY
model_provider MODEL_PROVIDER
model_name MODEL_NAME
model_endpoint MODEL_ENDPOINT
model_api_key MODEL_API_KEY
storage_connection_string AZURE_STORAGE_CONNECTION_STRING
storage_account_name STORAGE_ACCOUNT_NAME
user_id USER_ID
tenant_id TENANT_ID
namespace NAMESPACE

故障排查

Agent 创建失败

  1. 检查模板名称是否正确
  2. 验证必需参数是否提供(如 model_api_key)
  3. 查看 agent-manager 日志

MCP 工具调用失败

  1. 使用 GET /mcp/tools 确认工具名称
  2. 检查参数格式是否符合 inputSchema
  3. 查看 agent pod 日志

A2A Agent 无法协作

  1. 确认目标 Agent 已注册
  2. 检查网络连接和端点可访问性
  3. 验证 message 格式是否正确

更多资源


联系支持

如有问题或建议,请联系开发团队。