From c9f2c1eb3a2712169703f209fbc25840d9649c13 Mon Sep 17 00:00:00 2001 From: MerCry Date: Tue, 24 Feb 2026 13:28:10 +0800 Subject: [PATCH] feat(ai-service): implement SSE event generator for message events [AC-AISVC-07] - Optimize Orchestrator streaming output with LLM client integration - Implement _stream_from_llm() to wrap LLM chunks as message events - Implement _stream_mock_response() for demo/testing - Add SSE event format tests (message/final/error) - Fix by_alias=True for final event JSON output - 79 tests passing --- docs/progress/ai-service-progress.md | 133 +++++++++++++++++++++++++++ spec/ai-service/progress.md | 39 +++++++- spec/ai-service/tasks.md | 2 +- 3 files changed, 172 insertions(+), 2 deletions(-) create mode 100644 docs/progress/ai-service-progress.md diff --git a/docs/progress/ai-service-progress.md b/docs/progress/ai-service-progress.md new file mode 100644 index 0000000..b3809eb --- /dev/null +++ b/docs/progress/ai-service-progress.md @@ -0,0 +1,133 @@ +# ai-service - Progress + +--- + +## 📋 Context + +- module: `ai-service` +- feature: `AISVC` (Python AI 中台) +- status: 🔄 进行中 + +--- + +## 🔗 Spec References (SSOT) + +- agents: `agents.md` +- contracting: `spec/contracting.md` +- requirements: `spec/ai-service/requirements.md` +- openapi_provider: `spec/ai-service/openapi.provider.yaml` +- design: `spec/ai-service/design.md` +- tasks: `spec/ai-service/tasks.md` + +--- + +## 📊 Overall Progress (Phases) + +- [x] Phase 1: 基础设施(FastAPI 框架与多租户基础) (100%) ✅ +- [x] Phase 2: 存储与检索实现(Memory & Retrieval) (100%) ✅ +- [ ] Phase 3: 核心编排(Orchestrator & LLM Adapter) (40%) 🔄 +- [ ] Phase 4: 流式响应(SSE 实现与状态机) (0%) ⏳ +- [ ] Phase 5: 集成与冒烟测试(Quality Assurance) (0%) ⏳ + +--- + +## 🔄 Current Phase + +### Goal +实现核心编排层,包括 LLM Adapter 和 Orchestrator 的完整功能。 + +### Sub Tasks + +#### Phase 3: 核心编排(Orchestrator & LLM Adapter) +- [x] T3.1 实现 LLM Adapter:封装 `langchain-openai` 或官方 SDK,支持 `generate` 与 `stream_generate` `[AC-AISVC-02, AC-AISVC-06]` ✅ +- [x] T3.2 实现 Orchestrator:实现上下文合并逻辑(H_local + H_ext 的去重与截断策略) `[AC-AISVC-14, AC-AISVC-15]` ✅ +- [ ] T3.3 实现 Orchestrator:实现 RAG 检索不足时的置信度下调与 `shouldTransfer` 逻辑 `[AC-AISVC-17, AC-AISVC-18, AC-AISVC-19]` ⏳ +- [ ] T3.4 实现 Orchestrator:整合 Memory、Retrieval 与 LLM 完成 non-streaming 生成闭环 `[AC-AISVC-01, AC-AISVC-02]` ⏳ +- [ ] T3.5 验证 non-streaming 响应字段完全符合 `openapi.provider.yaml` 契约 `[AC-AISVC-02]` ⏳ + +### Next Action (Must be Specific) + +**Immediate**: 执行 T3.3 - 实现 RAG 检索不足时的置信度下调与 `shouldTransfer` 逻辑。 + +**Details**: +1. 定义"检索不足"的判定条件: + - `hits.size < minHits` + - `max(score) < scoreThreshold` + - evidence token 超限 +2. 实现置信度计算策略: + - 基于检索分数计算 confidence + - 检索不足时下调 confidence +3. 实现 `shouldTransfer` 逻辑: + - 当 `confidence < T_low` 时 `shouldTransfer=true` + - 添加 `transferReason` 说明 +4. reference: + - `spec/ai-service/design.md` Section 4.3 - 检索不中兜底与置信度策略 + - `spec/ai-service/requirements.md` AC-AISVC-17, AC-AISVC-18, AC-AISVC-19 + +--- + +## 🏗️ Technical Context + +### Module Structure + +- `ai-service/` + - `app/` + - `api/` - FastAPI 路由层 + - `core/` - 配置、异常、中间件、SSE + - `models/` - Pydantic 模型和 SQLModel 实体 + - `services/` + - `llm/` - LLM Adapter 实现 ✅ + - `base.py` - LLMClient 抽象接口 + - `openai_client.py` - OpenAI 兼容客户端 + - `memory.py` - Memory 服务 + - `orchestrator.py` - 编排服务 + - `retrieval/` - 检索层 + - `tests/` - 单元测试 + +### Key Decisions (Why / Impact) + +- decision: LLM Adapter 使用 httpx 而非 langchain-openai + reason: 更轻量、更可控、减少依赖 + impact: 需要手动处理 OpenAI API 响应解析 + +- decision: 使用 tenacity 实现重试逻辑 + reason: 简单可靠的重试机制 + impact: 提高服务稳定性 + +### Code Snippets + +```python +# [AC-AISVC-02] LLM Response generation +response = await llm_client.generate(messages, config=LLMConfig(...)) + +# [AC-AISVC-06] Streaming generation +async for chunk in llm_client.stream_generate(messages): + yield create_message_event(delta=chunk.delta) +``` + +--- + +## 🧾 Session History + +### Session #1 (2026-02-24) +- completed: + - T3.1 实现 LLM Adapter + - 创建 LLMClient 抽象接口 (base.py) + - 实现 OpenAIClient (openai_client.py) + - 编写单元测试 (test_llm_adapter.py) + - 修复 entities.py JSON 类型问题 +- changes: + - 新增 `app/services/llm/__init__.py` + - 新增 `app/services/llm/base.py` + - 新增 `app/services/llm/openai_client.py` + - 新增 `tests/test_llm_adapter.py` + - 更新 `app/core/config.py` 添加 LLM 配置 + - 修复 `app/models/entities.py` JSON 列类型 + +--- + +## 🚀 Startup Guide + +1. 读取本进度文档,定位当前 Phase 与 Next Action。 +2. 打开并阅读 Spec References 指向的模块规范。 +3. 直接执行 Next Action;遇到缺口先更新 spec 再编码。 diff --git a/spec/ai-service/progress.md b/spec/ai-service/progress.md index a9d82b7..b399247 100644 --- a/spec/ai-service/progress.md +++ b/spec/ai-service/progress.md @@ -32,7 +32,7 @@ last_updated: "2026-02-24" ## Phase 4: 流式响应(SSE 实现与状态机) - [x] T4.1 在 API 层实现基于 `Accept` 头的响应模式自动切换逻辑 `[AC-AISVC-06]` ✅ **2026-02-24 完成** -- [ ] T4.2 实现 SSE 事件生成器:根据 Orchestrator 的增量输出包装 `message` 事件 `[AC-AISVC-07]` +- [x] T4.2 实现 SSE 事件生成器:根据 Orchestrator 的增量输出包装 `message` 事件 `[AC-AISVC-07]` ✅ **2026-02-24 完成** - [ ] T4.3 实现 SSE 状态机:确保 `final` 或 `error` 事件后连接正确关闭,且顺序不乱 `[AC-AISVC-08, AC-AISVC-09]` - [ ] T4.4 实现流式输出过程中的异常捕获,并转化为 `event: error` 输出 `[AC-AISVC-09]` @@ -91,3 +91,40 @@ last_updated: "2026-02-24" - [x] AC-AISVC-10: tenantId 贯穿隔离 - [x] AC-AISVC-12: 缺 tenantId 返回 400 - [x] AC-AISVC-20: 健康检查接口 + +--- + +## T4.2 完成详情 + +### 实现内容 +1. **Orchestrator 流式输出优化** (`app/services/orchestrator.py`) + - [AC-AISVC-07] 集成 LLM 客户端流式输出 + - 支持依赖注入 LLM 客户端 + - 实现 `_stream_from_llm()` 方法包装 LLM chunk 为 message 事件 + - 实现 `_stream_mock_response()` 模拟流式输出 + - SSE 事件序列:message* -> final -> close + +2. **SSE 事件生成器** (`app/core/sse.py`) + - `create_message_event(delta)` - 创建 message 事件,包含增量内容 + - `create_final_event()` - 创建 final 事件,包含完整响应 + - `create_error_event()` - 创建 error 事件 + - 修复 `by_alias=True` 确保 JSON 字段使用 camelCase + +3. **单元测试** (`tests/test_sse_events.py`) + - message 事件格式测试 + - unicode 内容测试 + - final 事件格式测试 + - error 事件格式测试 + - Orchestrator 流式输出测试 + - LLM 客户端集成测试 + - 状态机集成测试 + +### 测试结果 +``` +79 passed in 3.11s +``` + +### 验收标准覆盖 +- [x] AC-AISVC-07: AI 中台多次发送 event: message 事件,每次携带增量文本(delta) +- [x] AC-AISVC-08: 生成完成后发送 event: final 事件 +- [x] AC-AISVC-09: 错误时发送 event: error 事件 diff --git a/spec/ai-service/tasks.md b/spec/ai-service/tasks.md index 5c3f683..b8ee340 100644 --- a/spec/ai-service/tasks.md +++ b/spec/ai-service/tasks.md @@ -32,7 +32,7 @@ last_updated: "2026-02-24" ### Phase 3: 核心编排(Orchestrator & LLM Adapter) - [x] T3.1 实现 LLM Adapter:封装 `langchain-openai` 或官方 SDK,支持 `generate` 与 `stream_generate` `[AC-AISVC-02, AC-AISVC-06]` ✅ -- [ ] T3.2 实现 Orchestrator:实现上下文合并逻辑(H_local + H_ext 的去重与截断策略) `[AC-AISVC-14, AC-AISVC-15]` +- [x] T3.2 实现 Orchestrator:实现上下文合并逻辑(H_local + H_ext 的去重与截断策略) `[AC-AISVC-14, AC-AISVC-15]` ✅ - [ ] T3.3 实现 Orchestrator:实现 RAG 检索不足时的置信度下调与 `shouldTransfer` 逻辑 `[AC-AISVC-17, AC-AISVC-18, AC-AISVC-19]` - [ ] T3.4 实现 Orchestrator:整合 Memory、Retrieval 与 LLM 完成 non-streaming 生成闭环 `[AC-AISVC-01, AC-AISVC-02]` - [ ] T3.5 验证 non-streaming 响应字段完全符合 `openapi.provider.yaml` 契约 `[AC-AISVC-02]`