- Implemented Multi-Function Agent with capabilities for weather, time, calculator, file listing, and jokes. - Created Express API for accessing the agent, including endpoints for generating responses, streaming, and testing tools. - Added middleware for error handling, response formatting, and request validation. - Defined schemas for request validation using Zod. - Translated agent instructions and tool descriptions to Chinese for localization. - Included README documentation for API usage and project structure. |
||
|---|---|---|
| .. | ||
| middleware | ||
| routes | ||
| schemas | ||
| README.md | ||
| index.ts | ||
README.md
Multi-Function Agent Express API
这是一个基于 Express 的 HTTP API 服务,提供对 Mastra 多功能 Agent 的访问。
功能
- 提供 RESTful API 访问 Multi-Function Agent
- 支持生成响应和流式响应
- 内置请求验证和错误处理
- 包含健康检查和工具测试端点
启动方式
开发模式
pnpm server:dev
使用 tsx 监视模式,支持热重载。
生产模式
pnpm build
pnpm server:start
构建项目后运行编译后的代码。
API 端点
根路径
GET /- API 信息
健康检查
GET /health- 服务健康状态
Agent API
GET /api/agent- 获取 Agent 信息POST /api/agent/generate- 生成 Agent 响应POST /api/agent/stream- 流式 Agent 响应POST /api/agent/test-tools- 测试所有工具
请求示例
获取 Agent 信息
curl http://localhost:3000/api/agent
生成响应
curl -X POST http://localhost:3000/api/agent/generate \
-H "Content-Type: application/json" \
-d '{
"message": "What is the weather in Beijing?",
"options": {
"temperature": 0.7
}
}'
流式响应
curl -X POST http://localhost:3000/api/agent/stream \
-H "Content-Type: application/json" \
-d '{
"message": "Tell me a joke"
}'
测试所有工具
curl -X POST http://localhost:3000/api/agent/test-tools
响应格式
成功响应
{
"success": true,
"data": {
"message": "The weather in Beijing is...",
"toolCalls": [],
"usage": {
"totalTokens": 42
}
},
"timestamp": "2025-12-11T08:30:00.000Z"
}
错误响应
{
"success": false,
"error": "ValidationError",
"message": "Message cannot be empty",
"timestamp": "2025-12-11T08:30:00.000Z",
"path": "/api/agent/generate"
}
工具列表
Agent 包含以下工具:
- weatherTool - 查询天气信息
- timeTool - 获取当前时间
- calculatorTool - 基本算术运算
- filelistTool - 列出目录文件
- jokeTool - 生成随机笑话
环境变量
PORT- 服务器端口 (默认: 3000)NODE_ENV- 环境模式 (development/production)CORS_ORIGIN- CORS 允许的源 (默认: '*')
项目结构
src/server/
├── index.ts # 主应用文件
├── middleware/ # Express 中间件
│ ├── error-handler.ts
│ ├── validation.ts
│ └── response-formatter.ts
├── routes/ # 路由定义
│ └── agent-routes.ts
├── schemas/ # 请求验证模式
│ └── agent-schemas.ts
└── README.md # 本文档
开发说明
- 确保已安装所有依赖:
pnpm install - 开发模式运行:
pnpm server:dev - 访问
http://localhost:3000/health确认服务运行正常 - 使用 API 客户端测试各端点功能
注意事项
- 天气工具需要网络连接访问外部 API
- 流式响应使用 Server-Sent Events (SSE)
- 生产环境建议配置合适的 CORS 策略
- 默认端口为 3000,可通过环境变量修改