Files
taiji_v0/API接口文档.md
2025-12-23 05:15:13 +00:00

880 lines
15 KiB
Markdown

# taiji-AI-PAD API 接口文档
**版本**: v1.2.1
**更新时间**: 2025年12月22日
**最后更新**: 2025年12月22日
**基础URL**:
- Data Ingestion 服务: `http://localhost:8001`
- MCP Server 服务: `http://localhost:8002`
- API Gateway: `http://localhost:80`
---
## 📋 目录
1. [Data Ingestion 服务 API](#data-ingestion-服务-api)
2. [MCP Server 服务 API](#mcp-server-服务-api)
3. [通用响应格式](#通用响应格式)
4. [错误码说明](#错误码说明)
---
## Data Ingestion 服务 API
**基础URL**: `http://localhost:8001`
### 1. 健康检查
**GET** `/health`
检查服务健康状态。
**响应示例**:
```json
{
"status": "healthy",
"timestamp": "2025-12-22T05:04:23.211960",
"services": {
"data_ingestion": "healthy",
"redis": "healthy",
"nats": "healthy",
"rapidapi": "healthy",
"apillama": "healthy"
},
"stats": {
"total_apis": 0,
"processed_apis": 0,
"generated_tools": 20,
"cache_size": 44
}
}
```
---
### 2. 同步 RapidAPI 端点
**POST** `/rapidapi/sync`
同步 RapidAPI 端点列表。
**查询参数**:
- `category` (string, 可选): API 分类
- `limit` (int, 可选, 默认: 100): 同步数量限制
**请求示例**:
```bash
POST /rapidapi/sync?category=weather&limit=50
```
**响应示例**:
```json
{
"message": "RapidAPI端点同步已启动",
"category": "weather",
"limit": 50
}
```
---
### 3. 测试 RapidAPI 端点
**POST** `/rapidapi/test`
测试 RapidAPI 端点调用。
**请求体**:
```json
{
"endpoint": "https://rapidapi.com/api/weather/v1/current",
"method": "GET",
"params": {
"location": "Beijing"
},
"headers": {
"X-Custom-Header": "value"
}
}
```
**响应示例**:
```json
{
"success": true,
"status_code": 200,
"data": {
"temperature": 25,
"condition": "sunny"
},
"response_time": 123.45,
"headers": {
"content-type": "application/json"
}
}
```
---
### 4. 解析 OpenAPI 规范
**POST** `/openapi/parse`
解析 OpenAPI/Swagger 规范文档。
**查询参数**:
- `url` (string, 必需): OpenAPI 文档 URL
**请求示例**:
```bash
POST /openapi/parse?url=https://api.example.com/openapi.json
```
**响应示例**:
```json
{
"url": "https://api.example.com/openapi.json",
"title": "Example API",
"version": "1.0.0",
"endpoints_count": 15,
"schemas_count": 8,
"parsed_data": {
"info": {
"title": "Example API",
"version": "1.0.0"
},
"paths": {
"/users": {
"get": {
"summary": "Get users",
"responses": {
"200": {
"description": "Success"
}
}
}
}
}
},
"parsing_time": 0.234
}
```
---
### 5. APILLAMA 处理 API 文档
**POST** `/apillama/process`
使用 APILLAMA 处理 API 文档,生成结构化 Schema。
**请求体**:
```json
{
"api_doc": {
"title": "Weather API",
"description": "Get weather information",
"parameters": [
{
"name": "location",
"type": "string",
"description": "City name",
"required": true
}
]
},
"context": {
"service": "Weather service",
"version": "1.0"
},
"output_format": "json_schema"
}
```
**请求参数说明**:
- `api_doc` (string | object, 必需): API 文档,可以是字符串或对象
- `context` (object, 可选): 上下文信息
- `output_format` (string, 可选): 输出格式,可选值: `json_schema`, `pydantic`, `openapi` (默认: `json_schema`)
**响应示例**:
```json
{
"processed": true,
"output_format": "json_schema",
"schema": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "City name"
}
},
"required": ["location"]
},
"description": "Weather API for getting current weather information",
"parameters": [
{
"name": "location",
"type": "string",
"description": "City name",
"required": true
}
],
"examples": [
{
"location": "Beijing",
"temperature": 25
}
],
"processing_time": 1.234,
"confidence_score": 0.95,
"completeness_score": 0.88
}
```
---
### 6. 生成工具定义
**POST** `/tools/generate`
从 API 端点生成工具定义。
**请求体**:
```json
{
"url": "https://api.example.com/users",
"method": "GET",
"name": "get_users",
"description": "Get list of users",
"parameters": [
{
"name": "page",
"type": "integer",
"required": false
}
],
"headers": {
"Authorization": "Bearer token"
}
}
```
**响应示例**:
```json
{
"message": "工具生成任务已启动",
"endpoint": "https://api.example.com/users",
"method": "GET"
}
```
---
### 7. 获取工具列表
**GET** `/tools`
获取已生成的工具列表。
**查询参数**:
- `category` (string, 可选): 工具分类
- `limit` (int, 可选, 默认: 100): 返回数量限制
- `offset` (int, 可选, 默认: 0): 偏移量
**请求示例**:
```bash
GET /tools?category=weather&limit=20&offset=0
```
**响应示例**:
```json
[
{
"name": "get_weather",
"description": "Get weather information",
"category": "weather",
"url": "https://api.example.com/weather",
"method": "GET",
"parameters": [
{
"name": "location",
"type": "string",
"required": true
}
],
"created_at": "2025-12-22T05:00:00Z"
}
]
```
---
### 8. 获取特定工具定义
**GET** `/tools/{tool_name}`
获取特定工具的定义。
**路径参数**:
- `tool_name` (string, 必需): 工具名称
**响应示例**:
```json
{
"name": "get_weather",
"description": "Get weather information",
"category": "weather",
"url": "https://api.example.com/weather",
"method": "GET",
"parameters": [
{
"name": "location",
"type": "string",
"required": true
}
],
"created_at": "2025-12-22T05:00:00Z"
}
```
---
### 9. 删除工具
**DELETE** `/tools/{tool_name}`
删除指定的工具定义。
**路径参数**:
- `tool_name` (string, 必需): 工具名称
**响应示例**:
```json
{
"message": "工具已删除",
"tool_name": "get_weather"
}
```
---
### 10. 获取统计信息
**GET** `/stats`
获取服务统计信息。
**响应示例**:
```json
{
"total_apis": 100,
"processed_apis": 85,
"generated_tools": 20,
"failed_processes": 2,
"cache_size": 44,
"last_sync": "2025-12-22T05:00:00Z",
"categories": {
"weather": 15,
"finance": 10,
"general": 5
}
}
```
---
### 11. 清除缓存
**POST** `/cache/clear`
清除所有缓存数据。
**查询参数**:
- `pattern` (string, 可选): 缓存键模式,如 `rapidapi:*`
**请求示例**:
```bash
POST /cache/clear?pattern=rapidapi:*
```
**响应示例**:
```json
{
"message": "缓存已清除",
"cleared_keys": 150
}
```
---
### 12. Prometheus Metrics
**GET** `/metrics`
获取 Prometheus 格式的监控指标。
**响应格式**: Prometheus 文本格式
**示例**:
```
# HELP http_requests_total Total number of HTTP requests
# TYPE http_requests_total counter
http_requests_total{method="GET",status="200"} 1500
http_requests_total{method="POST",status="200"} 800
# HELP apillama_processing_duration_seconds APILLAMA processing duration
# TYPE apillama_processing_duration_seconds histogram
apillama_processing_duration_seconds_bucket{le="0.5"} 100
apillama_processing_duration_seconds_bucket{le="1.0"} 200
```
---
## MCP Server 服务 API
**基础URL**: `http://localhost:8002`
### 1. 健康检查
**GET** `/health`
检查 MCP Server 健康状态。
**响应示例**:
```json
{
"status": "healthy",
"timestamp": "2025-12-22T05:04:23.211960",
"services": {
"database": "healthy",
"redis": "healthy",
"nats": "healthy"
}
}
```
---
### 2. 注册 Agent
**POST** `/agents`
注册新的 Agent。
**请求体**:
```json
{
"name": "weather_agent",
"description": "Weather information agent",
"capabilities": ["weather_query", "location_search"],
"metadata": {
"version": "1.0.0",
"author": "taiji-team"
}
}
```
**响应示例**:
```json
{
"agent_id": "agent_123456",
"name": "weather_agent",
"description": "Weather information agent",
"status": "active",
"created_at": "2025-12-22T05:00:00Z",
"capabilities": ["weather_query", "location_search"],
"metadata": {
"version": "1.0.0",
"author": "taiji-team"
}
}
```
---
### 3. 获取 Agent 列表
**GET** `/agents`
获取所有注册的 Agent 列表。
**查询参数**:
- `status` (string, 可选): 过滤状态,如 `active`, `inactive`
- `limit` (int, 可选, 默认: 100): 返回数量限制
- `offset` (int, 可选, 默认: 0): 偏移量
**响应示例**:
```json
[
{
"agent_id": "agent_123456",
"name": "weather_agent",
"description": "Weather information agent",
"status": "active",
"created_at": "2025-12-22T05:00:00Z"
}
]
```
---
### 4. 获取特定 Agent
**GET** `/agents/{agent_id}`
获取特定 Agent 的详细信息。
**路径参数**:
- `agent_id` (string, 必需): Agent ID
**响应示例**:
```json
{
"agent_id": "agent_123456",
"name": "weather_agent",
"description": "Weather information agent",
"status": "active",
"created_at": "2025-12-22T05:00:00Z",
"capabilities": ["weather_query", "location_search"],
"metadata": {
"version": "1.0.0",
"author": "taiji-team"
}
}
```
---
### 5. 执行 Agent 工具
**POST** `/agents/{agent_id}/execute`
执行 Agent 的工具调用。支持三种工具类型:
- **API 工具**: 调用外部 API
- **函数工具**: 执行本地 Python 函数(新增)
- **LLM 工具**: 调用 LLM 模型
**路径参数**:
- `agent_id` (string, 必需): Agent ID
**请求体**:
```json
{
"tool_name": "math_add",
"parameters": {
"a": 10,
"b": 20
},
"context": {
"session_id": "session_123"
}
}
```
**函数工具示例**:
```json
{
"tool_name": "math_add",
"parameters": {
"a": 10,
"b": 20
}
}
```
**响应示例**:
```json
{
"success": true,
"result": 30.0,
"execution_time": 0.001,
"tool_name": "math_add"
}
```
**可用的函数工具**:
- 数学函数: `math_add`, `math_subtract`, `math_multiply`, `math_divide`, `math_power`
- 字符串函数: `string_upper`, `string_lower`, `string_length`, `string_replace`
- 日期时间: `datetime_now`
- JSON: `json_parse`, `json_stringify`
- 哈希: `hash_md5`, `hash_sha256`
- Base64: `base64_encode`, `base64_decode`
**安全特性**:
- ✅ 函数白名单验证
- ✅ 沙箱执行环境
- ✅ 超时控制(默认 5 秒)
- ✅ 参数验证和类型检查
---
### 6. 获取工具列表
**GET** `/tools`
获取所有可用工具列表。
**查询参数**:
- `category` (string, 可选): 工具分类
- `limit` (int, 可选, 默认: 100): 返回数量限制
**响应示例**:
```json
[
{
"name": "get_weather",
"description": "Get weather information",
"category": "weather",
"parameters": [
{
"name": "location",
"type": "string",
"required": true
}
]
}
]
```
---
### 7. Prometheus Metrics
**GET** `/metrics`
获取 Prometheus 格式的监控指标。
**注意**: 当前返回 TODO 消息,待实现。
---
## WebSocket API
### MCP Protocol WebSocket
**WebSocket URL**: `ws://localhost:8002/ws/{agent_id}`
**连接示例**:
```javascript
const ws = new WebSocket('ws://localhost:8002/ws/agent_123456');
```
**消息格式**:
```json
{
"type": "mcp_request",
"payload": {
"method": "tools/list",
"params": {}
}
}
```
**响应格式**:
```json
{
"type": "mcp_response",
"payload": {
"result": [...]
}
}
```
---
## 通用响应格式
### 成功响应
所有成功响应都遵循以下格式:
```json
{
"status": "success",
"data": {...},
"message": "操作成功"
}
```
### 错误响应
所有错误响应都遵循以下格式:
```json
{
"status": "error",
"error": {
"code": "ERROR_CODE",
"message": "错误描述",
"details": {...}
}
}
```
---
## 错误码说明
| HTTP 状态码 | 错误码 | 说明 |
|------------|--------|------|
| 400 | `BAD_REQUEST` | 请求参数错误 |
| 401 | `UNAUTHORIZED` | 未授权 |
| 403 | `FORBIDDEN` | 禁止访问 |
| 404 | `NOT_FOUND` | 资源不存在 |
| 500 | `INTERNAL_ERROR` | 服务器内部错误 |
| 503 | `SERVICE_UNAVAILABLE` | 服务不可用 |
---
## 认证说明
当前版本暂未实现认证机制,所有 API 均可直接访问。
**未来版本将支持**:
- API Key 认证
- JWT Token 认证
- OAuth 2.0
---
## 限流说明
当前版本暂未实现限流机制。
**未来版本将支持**:
- 基于 IP 的限流
- 基于 API Key 的限流
- 基于用户的限流
---
## 交互式 API 文档
### Swagger UI
- Data Ingestion: `http://localhost:8001/docs`
- MCP Server: `http://localhost:8002/docs`
### ReDoc
- Data Ingestion: `http://localhost:8001/redoc`
- MCP Server: `http://localhost:8002/redoc`
### OpenAPI JSON
- Data Ingestion: `http://localhost:8001/openapi.json`
- MCP Server: `http://localhost:8002/openapi.json`
---
## 前端集成示例
### JavaScript/TypeScript
```typescript
// 健康检查
const healthCheck = async () => {
const response = await fetch('http://localhost:8001/health');
const data = await response.json();
console.log(data);
};
// APILLAMA 处理
const processAPI = async (apiDoc: any) => {
const response = await fetch('http://localhost:8001/apillama/process', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
api_doc: apiDoc,
context: { service: 'example' },
output_format: 'json_schema'
})
});
const data = await response.json();
return data;
};
// 获取工具列表
const getTools = async (category?: string) => {
const url = category
? `http://localhost:8001/tools?category=${category}`
: 'http://localhost:8001/tools';
const response = await fetch(url);
const data = await response.json();
return data;
};
```
### Python
```python
import requests
# 健康检查
def health_check():
response = requests.get('http://localhost:8001/health')
return response.json()
# APILLAMA 处理
def process_api(api_doc, context=None, output_format='json_schema'):
response = requests.post(
'http://localhost:8001/apillama/process',
json={
'api_doc': api_doc,
'context': context or {},
'output_format': output_format
}
)
return response.json()
# 获取工具列表
def get_tools(category=None):
params = {'category': category} if category else {}
response = requests.get('http://localhost:8001/tools', params=params)
return response.json()
```
### cURL
```bash
# 健康检查
curl http://localhost:8001/health
# APILLAMA 处理
curl -X POST http://localhost:8001/apillama/process \
-H "Content-Type: application/json" \
-d '{
"api_doc": {"title": "Test API"},
"context": {"service": "test"},
"output_format": "json_schema"
}'
# 获取工具列表
curl http://localhost:8001/tools?category=weather
```
---
## 注意事项
1. **CORS**: 当前配置允许所有来源,生产环境需要限制
2. **认证**: 当前版本未实现认证,生产环境需要添加
3. **限流**: 当前版本未实现限流,生产环境需要添加
4. **错误处理**: 所有 API 调用都应该处理错误情况
5. **超时设置**: 建议设置合理的请求超时时间
---
**文档版本**: v1.2.1
**最后更新**: 2025年12月22日
**维护者**: taiji-AI-PAD 项目组
## 更新日志
- **v1.2.1** (2025-12-22): 添加 MCP Server 函数工具调用说明
- **v1.2.0** (2025-12-22): 初始版本,包含所有 API 端点文档