# Agent 组员详细开发与使用手册 > 版本:v1.0|日期:2026-09-10 > 本文是业务组员及其 AI 编码助手的详细开发手册。请先完整阅读,再修改代码。 > > 📌 **接入流程与工具清单请以 `docs/14-Agent组员统一接入说明书.md` 为准**(唯一推荐入口)。 > 本文的**独有价值**是"关键源码解释 / HTTP 恢复 / 交接模板"等展开说明,作为 `14` 的**配套详解**使用; > 两者冲突时以 `14` 为准。 ## 0. AI 编码助手必须遵守的规则 接到业务 Agent 开发任务后,AI 必须按以下顺序工作: 1. 先阅读本文件、`AGENTS.md`、`TODO.md` 和对应业务流程文档; 2. 先确认这是场内基金模拟交易还是场外运营;场外流程不得写入场内交易表; 3. 只修改业务 Agent、业务 Service、业务工具和测试,不复制公共底座; 4. 不得修改已有数据库表名、字段名、字段类型、可空性和既有含义; 5. 修改前后运行契约测试、Ruff、MyPy 和相关单元测试; 6. 在提交说明中写清修改文件、测试命令和未完成事项。 如果需求与本文、`AGENTS.md` 或数据库基线冲突,暂停编码并报告冲突,不要自行猜测。 ## 1. 项目结构和 MVC+S 分层 ```text app/core/ 公共 DTO、错误、配置和安全契约 app/api/ Controller、View、HTTP Schema app/service/ Service;BaseAgent 和业务 Agent 位于这里 app/repository/ 数据访问封装 app/model/ SQLAlchemy 数据模型 app/infrastructure/ 外部系统 Adapter、缓存、向量库连接 app/worker/ 异步任务、Outbox、运行 Worker tests/contract/ 公共契约测试 tests/unit/ 单元测试 tests/integration/ MySQL/外部依赖集成测试 docs/ 设计、接口和使用文档 ``` 依赖方向必须保持: ```text Controller/View → Service → Repository/Infrastructure ↓ Model ``` 业务 Agent 是 Service,不得直接访问 Model、Session、Redis、Milvus、Neo4j 或外部 HTTP。 ## 2. 环境和启动 ```powershell .\.venv\Scripts\python.exe --version .\.venv\Scripts\python.exe -m pip install -r requirements.txt Copy-Item .env.example .env ``` 至少配置 MySQL、Redis、Milvus、Neo4j、JWT 公钥。`.env` 不提交;JWT 私钥和模型密钥也不提交。 执行迁移和结构审计: ```powershell .\.venv\Scripts\python.exe -m alembic upgrade head .\.venv\Scripts\python.exe tools\audit_schema.py .\.venv\Scripts\python.exe tools\schema_fingerprint.py ``` 启动服务: ```powershell .\.venv\Scripts\python.exe -m uvicorn app.main:app --host 127.0.0.1 --port 8099 .\.venv\Scripts\python.exe -m app.worker ``` HTTP 服务负责认证、受理和查询;Worker 负责实际 Agent 执行、模型调用和结果持久化。 ## 3. 一个业务 Agent 的最小代码 ```python from app.core.contracts import AgentDefinition, AgentRequest, CoreResult, RequestContext from app.service.agent.base import BaseAgent class AdvisorAgent(BaseAgent): definition = AgentDefinition( agent_type="advisor", version="1.0.0", allowed_roles=("customer", "advisor", "operator", "admin"), allowed_portals=("api",), allowed_tools=("query_fund_quote",), supported_intents=("fund_quote", "general"), ) async def handle( self, request: AgentRequest, context: RequestContext ) -> CoreResult: return CoreResult(text=f"已收到:{request.message}") ``` ### 代码说明 - `AgentDefinition` 是静态能力声明;`agent_type` 必须是小写蛇形; - `allowed_roles` 控制哪些角色可以使用; - `allowed_portals` 控制入口,例如 `api`; - `allowed_tools` 是代码层权限上限,配置中心不能扩大它; - `supported_intents` 是自动意图分类的白名单; - `handle()` 只写业务逻辑,返回 `CoreResult`; - `request` 是客户端业务输入;`context` 是服务端认证后的身份和权限上下文。 ## 4. 注册入口 在 `app/service/agent/bootstrap.py` 的统一工厂中注册: ```python factory.register( AdvisorAgent.definition, lambda _context: AdvisorAgent(AdvisorAgent.definition), ) ``` `get_agent_factory()` 同时被 HTTP 和 Worker 使用,因此不能在两个地方分别注册。工厂会检查: 1. Agent 类型已经注册; 2. Builder 返回值是 `BaseAgent`; 3. 返回实例的 `definition` 与注册定义完全一致; 4. 自动注入治理、模型、意图分类和工具执行器。 验证: ```powershell python -m pytest tests/contract/test_agent_factory_contract.py -q -p no:cacheprovider ``` ## 5. BaseAgent 自动执行链 `BaseAgent.execute()` 不允许业务子类覆盖,实际顺序是: ```text validate_input() → validate_access() → resolve_config() → recall_memory() → classify_intent() → _execute_governed() → governance.review() → done 事件 ``` ### 各步骤的含义 | 步骤 | 作用 | 组员是否实现 | |---|---|---| | `validate_input` | 检查请求 Agent 类型一致 | 否 | | `validate_access` | 角色、入口、权限校验 | 否 | | `resolve_config` | 读取生效配置快照 | 否 | | `recall_memory` | 召回授权客户记忆 | 否 | | `classify_intent` | 模型分类并校验意图白名单 | 否 | | `handle` | 业务流程和编排 | 是 | | `governance.review` | 引用、禁止表达、脱敏和合规 | 否 | ## 6. 自动意图分类 组员不需要创建 `IntentClassifier`,也不需要传 `endpoints`。工厂统一注入分类器,底座在 `handle()` 前调用模型端点解析器,要求模型返回: ```json {"intent":"fund_quote","confidence":0.92} ``` 底座将结果写入 `CoreResult.intent`。如果置信度低于阈值,`needs_clarification` 为 `true`。 业务代码必须对低置信结果采取澄清、转人工或安全回复,不能继续执行高风险动作。 非法 JSON、未声明意图、空输入和模型端点不可用均失败关闭或进入 Worker 重试。 ## 7. 模型生成 统一链路: ```text ConfigRelease → ModelRouterService/端点解析 → ModelGateway → fallback ``` 如果业务确实需要二次生成,只能使用底座注入的 `generate_with_model()`,并且 `endpoints` 必须来自 底座批准的路由结果: ```python model_result = await self.generate_with_model(approved_endpoints, prompt) text = model_result.text ``` 禁止直接使用 `httpx`、供应商 SDK、环境变量密钥或未批准模型地址。模型原始响应和异常不得直接返回给用户。 ## 8. 工具开发和调用 业务只读工具需要声明: ```text name input_model(Pydantic) required_permission allowed_roles read_only=True timeout_seconds ``` 调用: ```python value = await self.call_tool( "query_fund_quote", {"fund_codes": ["159511"], "limit": 20}, intent="fund_quote", context=context, ) ``` `ToolExecutor` 会依次完成:工具注册检查、意图白名单、权限、角色、Pydantic 参数、超时、异常转换、 输入摘要脱敏、`interaction_audit` 审计和 `SourceReference` 生成。 工具处理器不要自行写审计、不要自行判断用户身份,也不要执行写交易数据的操作。 ### 公共只读工具清单 底座在 `app/service/agent/bootstrap.py` 的 `ToolRegistry` 中注册了 **4 个公共只读工具**(约 L155-192): | 工具名 | 必需权限 | 允许角色 | 只读 | 越权与失败行为 | |---|---|---|---|---| | `check_suitability` | `suitability:read` | customer、advisor、operator、admin | 是 | 测评过期/缺失一律拒绝(失败关闭);通过和拒绝都写 `interaction_audit` | | `query_fund_quote` | `fund:quote:read` | customer、advisor、operator、risk_operator、admin | 是 | 只读行情,不得改写为成交、委托或持仓语义;超时 15s | | `query_knowledge` | `knowledge:query` | customer、operator、advisor、risk_operator、admin | 是 | 集合名由服务端按意图映射,调用方不得指定;维度不符失败关闭;超时 8s | | `query_customer_profile` | `memory:read:self`(查他人为 `memory:read:customer`) | customer、advisor、operator、risk_operator、admin | 是 | 越范围按"不存在"处理;无当前画像**抛错**而不返回空画像 | **白名单两段式**:`AgentDefinition.allowed_tools` 是代码上限,实际可用范围是它与当前 `active` 的 `config_release` 中 `namespace=agent_tools`、`config_key=:` 发布白名单的**交集**; 缺发布配置时交集为空、工具失败关闭。接口面登记口径见《05-接口文档.md》§8.4。 ## 9. 基金行情工具详解 公共工具(底座注册的 4 个只读工具全清单见 §8 末尾): ```text query_fund_quote 权限:fund:quote:read 角色:customer、advisor、operator、risk_operator、admin 超时:15s ``` 声明: ```python allowed_tools=("query_fund_quote",) supported_intents=("fund_quote", "general") ``` 发布配置: ```text namespace = agent_tools config_key = :fund_quote value_json = {"allowed_tools": ["query_fund_quote"]} ``` 调用: ```python quotes = await self.call_tool( "query_fund_quote", {"fund_codes": ["159511", "588890"], "limit": 20}, intent="fund_quote", context=context, ) ``` 返回值重点字段: ```text fund_code、fund_name、nav、nav_date、daily_change quote_source = eastmoney | cache | degraded is_intraday、degraded、quote_time ``` 行情是外部数据源,只能用于查询、解释和分析。不能据此确认成交、委托、持仓或收益保证。 禁止业务 Agent 导入 `hq.py`、调用东方财富 URL 或自己解析外部 JSON。 ## 10. 适当性校验 投顾流程使用公共 `SuitabilityService` 或 `check_suitability` 工具,不得复制风险匹配规则。 ```python decision = await self.call_tool( "check_suitability", { "customer_risk_level": 3, "product_risk_level": 3, "product_requires_disclosure": True, }, intent="risk_check", context=context, ) ``` 返回字段:`allowed`、`reason_code`、`required_disclosure`、`requires_confirmation`、 `requires_recording`。客户风险等级低于产品、测评过期时必须拒绝;通过和拒绝都审计。 ## 11. 记忆、关系推理、转人工 - 记忆只能读取当前客户授权范围; - `complete_run()` 在同一事务写入记忆提取 Outbox,组员不得直接调用提取服务; - Neo4j 只能通过 `RelationshipService` 查询白名单关系和受限跳数; - Agent 只能提出转人工请求,不能接单、解决或关闭工单; - 来源引用只能来自授权记忆或本次工具真实返回值; - 不得伪造 `SourceReference`。 ## 12. HTTP 运行和恢复 提交运行: ```http POST /api/v1/agent-runs Authorization: Bearer Idempotency-Key: unique-request-key Content-Type: application/json ``` ```json { "agent_type": "advisor", "message": "查询基金 159511 的行情", "session_id": "session-id", "idempotency_key": "request-key-202609100001" } ``` 查询结果: ```http GET /api/v1/agent-runs/{run_id} ``` SSE: ```http GET /api/v1/agent-runs/{run_id}/events Accept: text/event-stream ``` 断流后使用同一个 `run_id` 查询结果;已完成运行返回完整结果,不依赖 Worker 内存,也不实现事件级续传。 ## 13. 错误处理 | HTTP | 错误码 | 处理建议 | |---:|---|---| | 400/422 | `VALIDATION_ERROR` | 修正请求或工具参数 | | 401 | `UNAUTHORIZED` | 检查 JWT | | 403 | `FORBIDDEN` | 检查角色、权限、入口和意图白名单 | | 404 | `AGENT_TYPE_NOT_FOUND` | 检查是否在 bootstrap 注册 | | 409 | `IDEMPOTENCY_CONFLICT` | 检查幂等键是否复用 | | 503 | `RECOVERABLE_ERROR` | 允许 Worker 重试,检查外部依赖 | 错误响应不得包含 SQL、堆栈、模型原文、供应商响应或密钥。 ## 14. 禁止清单 - 覆盖 `execute()`、`classify_intent()`、`generate_with_model()`、`call_tool()` 或绑定方法; - 直接创建 SQLAlchemy Session 或访问数据库 Model; - 直接访问 Redis、Milvus、Neo4j Driver; - 直接访问东方财富或其他供应商接口; - 代客下单、确认成交、修改持仓、审核方案、关闭风险预警; - 将场外流程写入场内表; - 重命名、删除或修改已有数据库表和字段; - 提交 `.env`、JWT 私钥、模型 API Key 或 Token。 ## 15. 测试、提交和交接 新增业务 Agent 至少测试: - 正常意图、低置信意图、非法模型输出; - 未授权角色、入口、权限、客户范围; - 工具白名单、参数错误、超时、外部失败; - 适当性通过、风险不匹配、测评过期; - 行情实时、缓存、降级、非交易时段; - 合规替换、号码脱敏、引用校验和持久化。 提交前执行: ```powershell .\.venv\Scripts\python.exe -m pytest -q -p no:cacheprovider .\.venv\Scripts\python.exe -m ruff check app tests tools alembic .\.venv\Scripts\python.exe -m mypy app .\.venv\Scripts\python.exe tools\check_authoritative_docs.py .\.venv\Scripts\python.exe tools\audit_schema.py ``` 当前全量测试基线(2026-09-11 实测):`1 failed, 779 passed, 2 skipped`;唯一失败 `tests/unit/repository/test_fund_readonly_contract.py` 属底座既有缺陷,与本手册的接入流程无关。 提交说明必须包括: ```text 修改内容: 修改文件: 测试命令: 测试结果: 数据库是否变化: 已知限制: ``` ## 16. 当前底座状态 当前已提供: - `BaseAgent`、`AgentFactory` 和统一 Bootstrap; - 自动意图分类; - ModelGateway 和受控 fallback; - ToolRegistry、ToolExecutor; - 4 个公共只读工具:`check_suitability`、`query_fund_quote`、`query_knowledge`、`query_customer_profile`; - 记忆、关系、配置、审计、Outbox、SSE 和恢复基础能力。 已注册的业务 Agent(`app/service/agent/bootstrap.py` 的 `register_business_agents()`,约 L218-225): `FundQueryDemoAgent`(`fund_query_demo`)与 `CustomerServiceAgent`(`customer_service`)。 业务 Agent 仍需自己完成:业务类、业务意图、注册、发布配置和业务测试。新增业务 Agent 未注册前 不能提交运行。本文不替代《05-接口文档.md》、数据库基线和具体业务流程文档。