Files
agent_management/API_DOCUMENTATION.md
T
2026-01-05 12:44:28 +00:00

843 lines
16 KiB
Markdown

# Agent Manager API 接口文档
## 基础信息
- **Base URL**: `http://localhost:8000`
- **版本**: v1.0.0
- **协议**: HTTP/HTTPS
- **数据格式**: JSON
---
## 目录
1. [Agent 管理](#agent-管理)
2. [模板查询](#模板查询)
3. [状态监控](#状态监控)
4. [资源管理](#资源管理)
---
## Agent 管理
### 1. 创建 Agent
创建一个新的 AI Agent 实例。
**请求**
```http
POST /agents
Content-Type: application/json
```
**请求参数**
```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": { // 可选,环境变量
"KEY": "value"
}
}
```
**支持的模板类型**
| 模板 | 说明 | 类型 |
|------|------|------|
| `echo_agent` | Echo 测试服务 | 平台 |
| `chat_agent` | 聊天服务 | 平台 |
| `code_agent` | 代码执行服务 | 平台 |
| `search_agent` | 搜索服务 | 平台 |
| `jina_search_agent` | Jina 搜索服务 | 平台 |
| `mysql_agent` | MySQL 客户端 | 自定义 |
| `postgresql_agent` | PostgreSQL 客户端 | 自定义 |
**响应**
```json
{
"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` - 服务器内部错误
**示例**
```bash
curl -X POST http://localhost:8000/agents \
-H "Content-Type: application/json" \
-d '{
"name": "alice-echo",
"template": "echo_agent",
"config": {
"user_id": "alice"
}
}'
```
---
### 2. 查询 Agent 列表
获取所有 Agent 的列表。
**请求**
```http
GET /agents
```
**查询参数**
| 参数 | 类型 | 必填 | 说明 |
|------|------|------|------|
| template | string | 否 | 按模板类型过滤 |
**响应**
```json
{
"agents": [
{
"name": "alice-echo",
"namespace": "ai-agents",
"status": "Running",
"template": "echo_agent",
"pod_ip": "10.244.2.24",
"labels": {
"user-id": "alice"
}
}
],
"count": 1
}
```
**示例**
```bash
# 获取所有 Agents
curl http://localhost:8000/agents
# 按模板过滤
curl http://localhost:8000/agents?template=echo_agent
```
---
### 3. 获取 Agent 状态
获取指定 Agent 的详细状态信息。
**请求**
```http
GET /agents/{agent_name}/status
```
**路径参数**
| 参数 | 类型 | 说明 |
|------|------|------|
| agent_name | string | Agent 名称 |
**响应**
```json
{
"name": "alice-echo",
"namespace": "ai-agents",
"status": "Running",
"pod_ip": "10.244.2.24",
"node_name": "aks-node-123",
"created_at": "2026-01-05T07:35:00+00:00",
"labels": {
"user-id": "alice",
"template": "echo_agent"
}
}
```
**状态码**
- `200` - 成功
- `404` - Agent 不存在
- `500` - 服务器内部错误
**示例**
```bash
curl http://localhost:8000/agents/alice-echo/status
```
---
### 4. 获取 Agent 资源使用情况
获取 Agent 的 CPU 和内存使用情况。
**请求**
```http
GET /agents/{agent_name}/metrics
```
**响应**
```json
{
"name": "alice-echo",
"namespace": "ai-agents",
"resources": {
"cpu_usage": "50m",
"memory_usage": "128Mi",
"available": true
}
}
```
**示例**
```bash
curl http://localhost:8000/agents/alice-echo/metrics
```
---
### 5. 删除 Agent
删除指定的 Agent。
**请求**
```http
DELETE /agents/{agent_name}
```
**路径参数**
| 参数 | 类型 | 说明 |
|------|------|------|
| agent_name | string | Agent 名称 |
**响应**
```json
{
"message": "Agent alice-echo 删除成功"
}
```
**状态码**
- `200` - 删除成功
- `404` - Agent 不存在
- `500` - 服务器内部错误
**示例**
```bash
curl -X DELETE http://localhost:8000/agents/alice-echo
```
---
## 模板查询
### 1. 获取所有模板
获取所有可用的 Agent 模板列表。
**请求**
```http
GET /templates
```
**响应**
```json
{
"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
}
```
**示例**
```bash
curl http://localhost:8000/templates
```
---
### 2. 获取平台模板
获取平台提供的标准 Agent 模板列表。
**请求**
```http
GET /templates/platform
```
**响应**
```json
{
"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)
**示例**
```bash
curl http://localhost:8000/templates/platform
```
---
### 3. 获取自定义模板
获取需要用户配置环境变量的自定义 Agent 模板列表。
**请求**
```http
GET /templates/custom
```
**响应**
```json
{
"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**
```bash
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-..."
}
}'
```
**示例**
```bash
curl http://localhost:8000/templates/custom
```
---
### 4. 获取指定模板详情
获取单个模板的详细信息。
**请求**
```http
GET /templates/{template_name}
```
**路径参数**
| 参数 | 类型 | 说明 |
|------|------|------|
| template_name | string | 模板名称 |
**响应**
```json
{
"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` - 模板不存在
**示例**
```bash
curl http://localhost:8000/templates/mysql_agent
```
---
## 状态监控
### 健康检查
检查服务是否正常运行。
**请求**
```http
GET /
```
**响应**
```json
{
"service": "Agent Manager API",
"version": "1.0.0",
"status": "running"
}
```
**示例**
```bash
curl http://localhost:8000/
```
---
## 多租户管理
### 按用户查询 Agents
使用 Kubernetes 标签选择器按用户 ID 查询 Agents。
**方法 1: 通过 kubectl**
```bash
# 查询特定用户的所有 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 查询后过滤**
```bash
curl http://localhost:8000/agents | \
jq '.agents[] | select(.labels["user-id"]=="alice")'
```
### 验证 Pod 归属
**通过 Pod ID 验证**
```bash
# 通过 Pod ID 查询
kubectl get pods -n ai-agents -o json | \
jq ".items[] | select(.metadata.uid==\"$POD_ID\")"
```
**通过 user-id 标签验证**
```bash
kubectl get pod <pod-name> -n ai-agents \
-o jsonpath='{.metadata.labels.user-id}'
```
---
## 错误码
### HTTP 状态码
| 状态码 | 说明 |
|--------|------|
| 200 | 请求成功 |
| 201 | 创建成功 |
| 400 | 请求参数错误 |
| 404 | 资源不存在 |
| 409 | 资源冲突(如 Agent 已存在) |
| 500 | 服务器内部错误 |
### 错误响应格式
```json
{
"detail": "错误详细信息"
}
```
---
## 使用示例
### Python SDK 示例
```python
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 示例
```javascript
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 创建和管理
- ✅ 支持 7 种 Agent 模板
- ✅ 多租户支持(user-id 标签)
- ✅ Pod ID 返回和归属验证
- ✅ 模板分类查询(平台/自定义)
- ✅ 资源监控和状态查询
---
## 联系支持
如有问题或建议,请联系开发团队。