# simple_agent **Repository Path**: xj999777/simple_agent ## Basic Information - **Project Name**: simple_agent - **Description**: No description available - **Primary Language**: Python - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-08-25 - **Last Updated**: 2026-10-14 ## Categories & Tags **Categories**: Uncategorized **Tags**: 智能体系统, FastAPI, Python ## README # Simple Agent 简单智能体系统 基于 **Python FastAPI** 的简单智能体系统:通过配置文件对接大模型(OpenAI 兼容 / Anthropic),提供统一的 HTTP 调用接口、按天写入调用日志(含唯一调用标识,可统计调用量)。 ## 目录结构 ``` simple_agent/ ├── app/ │ ├── main.py # 服务入口:组装应用(挂载 router)+ 启停服务 │ ├── model.py # API 请求 / 响应数据模型(ChatRequest 等) │ ├── agents.py # 智能体注册表 AGENTS(新增智能体在此登记) │ └── task_store.py # 异步任务存储层(Redis 为主,内存降级) ├── agent/ │ ├── base_agent.py # 智能体基类:模型调用 + 唯一调用标识 │ ├── chat_agent.py # 自定义 prompt 的智能体示例:通用对话 │ └── translate_agent.py # 自定义 prompt 的智能体示例:中英互译 ├── route/ # 具体接口的 router 集中管理(由 app/main.py 统一挂载) │ ├── system.py # GET /、/health、/agent/list │ ├── agents.py # POST /agent/chat │ └── chat.py # POST /chat、GET /chat/{task_id}、POST /chat/stream ├── common/ │ └── log.py # 独立日志模块(按天写日志,路径/级别在 settings.toml 配置) ├── config/ │ ├── model.toml # 对接模型信息(base_url / api_key / model) │ └── settings.toml # 项目配置(部署端口、日志目录等) ├── logs/ # 调用日志(按天命名,如 2026-08-13.log,不自动清理) ├── tests/ │ ├── test_gateway.sh # 测试网关提供的服务(模型网关可达性 / 鉴权) │ ├── test_model.sh # 测试该智能体使用模型是否正常(真实调用) │ └── test_api.sh # 测试本地服务是否正常(健康检查 / 路由) ├── scripts/ │ ├── _api.sh # sh 启停脚本共用的函数库(start/stop/restart) │ ├── _common.py # 服务启停共用库(Python,跨平台) │ ├── _common.sh # 共用的 Python 探测(bash,测试脚本与 _api.sh 复用) │ ├── start_api.sh # bash 版:后台启动服务(写入 PID) │ ├── stop_api.sh # bash 版:停止服务(幂等) │ ├── restart_api.sh # bash 版:先杀掉已有服务,再启动服务 │ ├── start_api.py # py 版:通过 app/main.py 启动服务(后台,写入 PID) │ └── restart_api.py # py 版:先杀掉已有服务,再启动服务 ├── requirements.txt └── README.md ``` ## 快速开始 ```bash # 1. 安装依赖 pip install -r requirements.txt # 或使用虚拟环境 # 2. 配置模型(编辑 config/model.toml,推荐用环境变量存密钥) # api_key 支持 ${ENV_NAME} 语法,也可在项目根目录 .env 中配置 # 例如 .env: LLM_API_KEY=sk-xxxx # 配置为 TOML 格式,由标准库 tomllib 读取(无需安装 PyYAML) # 3. 启动服务(默认端口 8000) bash scripts/start_api.sh # bash 版(Linux / Git Bash) python scripts/start_api.py # py 跨平台版:Windows 也可用 py -3.11 scripts/start_api.py # 部署端口:config/settings.toml -> server.port,默认 8000 # 也可用环境变量覆盖:PORT=9000 bash scripts/start_api.sh # 4. 验证 bash tests/test_gateway.sh # 网关 bash tests/test_model.sh # 智能体 -> 模型 bash tests/test_api.sh # 本地 API 服务 # 5. 重启 / 停止 bash scripts/restart_api.sh # py 版:python scripts/restart_api.py(Windows 也可用 py -3.11) bash scripts/stop_api.sh # 仅停止 ``` ## 脚本逻辑与跨平台说明 可以前台启动: ```bash python app/main.py # 监听 http://0.0.0.0:8000 PORT=9000 python app/main.py ``` ## HTTP 接口 | 接口 | 方法 | 说明 | | --- | --- | --- | | `/health` | GET | 健康检查 | | `/` | GET | 服务信息(含部署端口) | | `/agent/list` | GET | 已注册智能体列表 | | `/agent/chat` | POST | 调用智能体(同步,阻塞返回完整回复) | | `/chat` | POST | 异步提交聊天任务,立刻返回 `task_id` | | `/chat/{task_id}` | GET | 查询异步任务状态与结果 | | `/chat/stream` | POST | 流式输出(SSE,打字机效果) | `agent` 可选值:`chat`(对话)、`translate`(中英互译)。 ### 同步接口 `POST /agent/chat` `POST /agent/chat` 请求体: ```json { "message": "你好", "agent": "chat", "temperature": 0.7, "max_tokens": 512 } ``` 返回体(`call_id` 即本次调用的唯一标识): ```json { "call_id": "20260813153012456123-1a2b3c4d5e6f", "agent": "chat", "model": "deepseek-chat", "reply": "你好!有什么可以帮你的吗?", "latency_ms": 830 } ``` ### 异步接口 `POST /chat` + `GET /chat/{task_id}` `POST /chat` 请求体(在同步请求体基础上,可选 `callback_url`): ```json { "message": "你好", "agent": "chat", "callback_url": "https://your-service.example.com/callback" } ``` 提交后**立刻**返回 `task_id`,后台执行模型调用,任务状态与结果存 Redis (`chat_task:{task_id}`,默认保留 3600 秒;Redis 连不上时降级为进程内内存存储): ```json { "task_id": "20260813153012456123-1a2b3c4d5e6f", "status": "pending", "agent": "chat" } ``` 轮询 `GET /chat/{task_id}` 获取状态与结果: ```json { "task_id": "20260813153012456123-1a2b3c4d5e6f", "status": "success", "agent": "chat", "message": "你好", "created_at": 1755060000.0, "updated_at": 1755060008.0, "callback_url": "https://your-service.example.com/callback", "call_id": "20260813153012456123-1a2b3c4d5e6f", "model": "openai/glm-5", "reply": "你好!有什么可以帮你的吗?", "latency_ms": 830, "callback_status": "ok:200" } ``` `status` 取值:`pending` → `running` → `success` / `failed`(失败时含 `error` 字段)。 任务不存在或已过期返回 `404`。 ### 回调(callback) `POST /chat` 请求体中带 `callback_url` 时,任务**成功或失败**都会向该地址 `POST` 完整结果 JSON(内容同 `GET /chat/{task_id}` 的核心字段,含 `task_id`、 `status`、`call_id`、`agent`、`model`、`reply` / `error`、`latency_ms`)。 回调超时默认 10 秒,回调失败只记日志、不影响任务状态;回调结果记录在任务的 `callback_status` 字段。 ### 流式接口 `POST /chat/stream` 请求体同 `POST /agent/chat`,响应为 SSE(`text/event-stream`),每个事件: ```json data: {"type":"content","text":"你好"} data: {"type":"content","text":"!"} data: {"type":"done","call_id":"20260813153012456123-1a2b3c4d5e6f","agent":"chat","model":"openai/glm-5","latency_ms":830} ``` `type` 取值:`content`(正式回复增量)、`reasoning`(模型思考内容,如 GLM-5/ DeepSeek 推理模型)、`error`(失败信息)、`done`(流结束,含 `call_id`)。 ## 新增自定义智能体 在 `agent/` 目录新建一个 py 文件,继承 `BaseAgent`,设置 `name` 与 `system_prompt`, 然后在 `app/agents.py` 的 `AGENTS` 字典中注册即可: ```python # agent/poetry_agent.py from agent.base_agent import BaseAgent class PoetryAgent(BaseAgent): name = "poetry" system_prompt = "你是一位诗人,用七言绝句回答问题。" ``` ```python # app/agents.py 中注册 from agent.poetry_agent import PoetryAgent AGENTS = { ChatAgent.name: ChatAgent(), TranslateAgent.name: TranslateAgent(), PoetryAgent.name: PoetryAgent(), } ``` ## 调用日志与调用量统计 - 日志按天写入 `logs/YYYY-MM-DD.log`,如 `logs/2026-08-13.log`(日志目录与级别在 `config/settings.toml` 的 `[logging]` 段配置)。 - 不自动清理历史日志。 - 每次模型调用都有唯一标识 `call_id`(时间戳 + 随机串),并打印在日志中: ``` 2026-08-13 15:30:12 | INFO | CALL_START call_id=20260813153012456123-1a2b3c4d5e6f agent=chat model=deepseek-chat input=你好 2026-08-13 15:30:12 | INFO | CALL_END call_id=20260813153012456123-1a2b3c4d5e6f agent=chat model=deepseek-chat status=ok latency_ms=830 output=你好!... ``` 统计某天调用量: ```bash grep -c 'CALL_START call_id=' logs/2026-08-13.log ``` ## 模型对接说明 `config/model.toml` 中的 `provider.name` 支持两种: 1. **`openai-compatible`**(默认):OpenAI 兼容接口,适用于 DeepSeek、通义千问、智谱、OpenAI 及各类 OpenAI 风格网关。 2. **`anthropic`**:Anthropic Claude 官方接口(使用官方 `anthropic` SDK)。 密钥两种写法:直接明文,或 `${ENV_NAME}` 引用环境变量(推荐,配合项目根目录 `.env`)。 ## 端口说明 - 部署端口默认 **8000**,配置在 `config/settings.toml` 的 `server.port`。 - 可用环境变量 `PORT` 覆盖:`PORT=9000 bash scripts/start_api.sh`。