Files
life-echo/api/app/agents/memoir/extraction_agent.py

86 lines
2.8 KiB
Python
Raw Normal View History

2026-03-19 10:38:11 +08:00
"""
ExtractionAgent从用户消息中提取 5-stage 状态与 slots
对应现有逻辑get_state_extraction_prompt + JSON 解析
"""
2026-03-19 14:36:14 +08:00
2026-03-19 10:38:11 +08:00
from __future__ import annotations
import json
from dataclasses import dataclass
from typing import Any, Dict
2026-03-20 15:15:35 +08:00
from app.agents.memoir.prompts import get_state_extraction_prompt
from app.agents.stage_constants import normalize_chat_stage
from app.core.langchain_llm import invoke_json_object
2026-03-19 10:38:11 +08:00
from app.core.logging import get_logger
refactor(agents): 抽取阶段常量与对话上下文;快档 LLM;图片 prompt 可禁止回退 访谈与阶段 - 新增 app/agents/stage_constants.py:集中 CHAT_STAGES、章节分类/顺序、阶段到默认 memoir 类别等,与 MemoirState 默认槽位顺序对齐;减少散落在 prompts 内的重复常量。 - 新增 app/agents/chat/prompt_context.py:以 ChatPromptContext 汇总 guided 系统提示所需字段(阶段、槽位、轮次、人设、记忆证据、回复长度模式、背景声线、职业等),统一走 get_guided_conversation_prompt。 - 大幅收敛 app/agents/chat/prompts_conversation.py;调整 prompts.py、stage_prompts.py、stage_detection.py;同步 interview_agent、profile_agent、helpers 与 state_schema,使对话侧构造提示的方式一致、可测。 回忆录流水线 - memoir/prompts.py 删除已迁至 stage_constants / 独立模板的大段常量与图片占位相关逻辑;classification / extraction / fidelity / narrative agents 与 orchest(全量历史仍可用于计数,注入模型时按轮次与字符上限截断)、image_prompt_fallback_disabled。 - dependencies 增加 get_llm_provider_fast(LRU 缓存,可与默认共用密钥与 base_url)。 任务与编排 - memoir_tasks:prepare_batches 注入 llm_fast;开启独立快档模型时打结构化日志。 - chapter_cover_tasks、story_image_tasks:与图片 prompt / JSON 工具路径或策略变更对齐(import 与行为一致)。 - story_pipeline_sync 等小处同步。 其它核心 - langchain_llm、text_normalize 随上述调用链微调。 开发者体验 - .cursor/settings.json:启用 redis-development、postman 插件。 测试 - 新增 test_image_prompt_policy:覆盖「禁止回退」等图片 prompt 策略。 - 更新 test_interview_prompts、test_interview_reply_length、test_experience_regressions、test_json_and_memory_utils,匹配新常量位置、json_utils 与对话/长度行为。
2026-04-02 12:00:00 +08:00
from app.core.json_utils import extract_json_payload
2026-03-19 10:38:11 +08:00
logger = get_logger(__name__)
@dataclass
class ExtractionResult:
"""状态提取结果"""
2026-03-19 14:36:14 +08:00
2026-03-19 10:38:11 +08:00
detected_stage: str
slots: Dict[str, str]
class ExtractionAgent:
"""从用户消息中提取 detected_stage 和 slots"""
def extract(
self,
user_message: str,
current_stage: str,
stage_slots: Dict[str, Any],
llm: Any,
) -> ExtractionResult:
"""
提取结构化信息并判断阶段
llm 需支持 .invoke(prompt) 同步调用Celery 任务内使用
"""
detected_stage = current_stage
extracted_slots: Dict[str, str] = {}
if not llm:
2026-03-19 14:36:14 +08:00
return ExtractionResult(
detected_stage=detected_stage, slots=extracted_slots
)
2026-03-19 10:38:11 +08:00
try:
prompt = get_state_extraction_prompt(
user_message=user_message,
current_stage=current_stage,
stage_slots={
k: v.model_dump() if hasattr(v, "model_dump") else v
for k, v in (stage_slots or {}).items()
},
)
raw = invoke_json_object(
llm,
prompt,
max_tokens=1024,
agent="ExtractionAgent.extract",
)
parsed = json.loads(extract_json_payload(raw))
2026-03-19 10:38:11 +08:00
raw_slots = parsed.get("slots", {}) or {}
extracted_slots = {
2026-03-19 14:36:14 +08:00
k: v if isinstance(v, str) else str(v) for k, v in raw_slots.items()
2026-03-19 10:38:11 +08:00
}
if not extracted_slots:
# 无实质 slot 时不推断阶段,避免元话语被标成任意 childhood 等(与服务端护栏一致)
detected_stage = normalize_chat_stage(
current_stage, fallback=current_stage
)
else:
raw_detected = parsed.get("detected_stage", current_stage)
detected_stage = normalize_chat_stage(
str(raw_detected) if raw_detected is not None else None,
fallback=current_stage,
)
2026-03-19 10:38:11 +08:00
except (json.JSONDecodeError, Exception) as e:
logger.warning("ExtractionAgent LLM 解析失败: {}", e)
2026-03-19 10:38:11 +08:00
return ExtractionResult(detected_stage=detected_stage, slots=extracted_slots)