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 与对话/长度行为。
This commit is contained in:
Kevin
2026-04-02 12:00:00 +08:00
parent 43ef260ae2
commit bb16d3a5c9
42 changed files with 894 additions and 580 deletions

View File

@@ -3,19 +3,19 @@ InterviewAgent正式访谈 Specialist
负责状态感知回复、开场白,不负责 Redis 持久化(由 Orchestrator 统一处理)
"""
import time
from typing import Any, List, Optional
from app.agents.chat.agent_turn import AgentChatTurn
from app.agents.chat.stage_detection import keyword_fallback_primary_stage
from app.core.dependencies import get_llm_provider
from app.core.logging import get_logger
from langchain_core.messages import HumanMessage, SystemMessage
from app.agents.chat.helpers import format_history_string, get_history_messages
from app.agents.chat.agent_turn import AgentChatTurn
from app.agents.chat.helpers import format_history_string, get_history_with_window
from app.agents.chat.personas import normalize_interview_persona
from app.agents.chat.prompt_context import ChatPromptContext
from app.agents.chat.stage_detection import keyword_fallback_primary_stage
from app.agents.chat.interview_reply_length import compute_reply_plan
from app.agents.chat.prompts_conversation import (
SLOT_NAME_MAP,
get_guided_conversation_prompt,
get_opening_prompt,
)
from app.agents.state_schema import MemoirStateSchema
@@ -30,6 +30,8 @@ from app.core.agent_logging import (
log_agent_summary,
)
from app.core.config import settings
from app.core.dependencies import get_llm_provider
from app.core.logging import get_logger
from app.features.conversation.input_normalize import normalize_chat_input_for_agent
logger = get_logger(__name__)
@@ -46,6 +48,15 @@ def _get_langchain_llm():
return None
def _message_contents_char_count(messages: List[Any]) -> int:
n = 0
for m in messages:
c = getattr(m, "content", None)
if isinstance(c, str):
n += len(c)
return n
class InterviewAgent:
"""正式访谈 Specialist Agent"""
@@ -120,11 +131,13 @@ class InterviewAgent:
du = detected_user_stage
else:
du = self._detect_user_stage(text_for_model)
history_messages = await get_history_messages(conversation_id)
conversation_turn = len(history_messages) // 2
same_topic_turns = self._estimate_same_topic_turns(
history_messages, filled_slots
hw = await get_history_with_window(
conversation_id,
max_pairs=settings.chat_history_max_pairs,
max_chars=settings.chat_history_max_chars,
)
conversation_turn_total = hw.turn_total
same_topic_turns = self._estimate_same_topic_turns(hw.window, filled_slots)
all_stages_coverage = memoir_state.all_stages_coverage()
persona = normalize_interview_persona(settings.chat_interview_persona)
reply_plan = compute_reply_plan(
@@ -132,12 +145,12 @@ class InterviewAgent:
background_voice=background_voice,
settings=settings,
)
system_prompt = get_guided_conversation_prompt(
ctx = ChatPromptContext(
current_stage=memoir_state.current_stage,
empty_slots=empty_slots,
filled_slots=filled_slots,
user_message=text_for_model,
conversation_turn=conversation_turn,
conversation_turn_total=conversation_turn_total,
same_topic_turns=same_topic_turns,
all_stages_coverage=all_stages_coverage,
detected_user_stage=du,
@@ -148,19 +161,46 @@ class InterviewAgent:
background_voice=background_voice,
occupation=occupation,
)
history_string = format_history_string(history_messages)
full_prompt = f"{system_prompt}\n\n{history_string}\n\nHuman: {text_for_model}\n\nAssistant:"
system_prompt = ctx.guided_system_prompt()
messages: List[Any] = [SystemMessage(content=system_prompt)]
messages.extend(hw.window)
messages.append(HumanMessage(content=text_for_model))
history_pairs_windowed = len(hw.window) // 2
window_chars = sum(len(getattr(m, "content", "") or "") for m in hw.window)
logger.info(
"event=history_window_applied total={} windowed={} chars={}",
conversation_turn_total,
history_pairs_windowed,
window_chars,
)
log_agent_payload(
logger, "InterviewAgent.generate_response.prompt", full_prompt
logger,
"InterviewAgent.generate_response.prompt",
format_history_string(messages),
)
chat_llm = self.llm.bind(max_tokens=reply_plan.max_tokens)
prompt_chars = _message_contents_char_count(messages)
llm_t0 = time.perf_counter()
with agent_span(
logger,
"InterviewAgent.generate_response.llm",
conversation_id=conversation_id,
stage=memoir_state.current_stage,
):
response = await chat_llm.ainvoke(full_prompt)
logger.info(
"event=chat_prompt_built agent=InterviewAgent.generate_response_with_state "
"prompt_chars={} history_pairs_total={} history_pairs_windowed={}",
prompt_chars,
conversation_turn_total,
history_pairs_windowed,
)
response = await chat_llm.ainvoke(messages)
response_ms = (time.perf_counter() - llm_t0) * 1000
logger.info(
"event=chat_llm_done agent=InterviewAgent.generate_response_with_state "
"response_latency_ms={:.2f}",
response_ms,
)
response_text = (
response.content if hasattr(response, "content") else str(response)
)
@@ -218,15 +258,47 @@ class InterviewAgent:
background_voice=background_voice,
occupation=occupation,
)
full_prompt = f"{prompt}\n\nAssistant:"
log_agent_payload(logger, "InterviewAgent.opening.prompt", full_prompt)
hw = await get_history_with_window(
conversation_id,
max_pairs=settings.chat_history_max_pairs,
max_chars=settings.chat_history_max_chars,
)
messages: List[Any] = [SystemMessage(content=prompt)]
messages.extend(hw.window)
if not hw.window:
messages.append(
HumanMessage(content="(对话刚开始,请自然地说出你的开场白。)")
)
else:
messages.append(
HumanMessage(content="(请根据上文,自然接续并说出你的开场白。)")
)
log_agent_payload(
logger,
"InterviewAgent.opening.prompt",
format_history_string(messages),
)
opening_llm = self.llm.bind(max_tokens=settings.chat_opening_max_tokens)
prompt_chars = _message_contents_char_count(messages)
llm_t0 = time.perf_counter()
with agent_span(
logger,
"InterviewAgent.opening.llm",
conversation_id=conversation_id,
):
response = await opening_llm.ainvoke(full_prompt)
logger.info(
"event=chat_prompt_built agent=InterviewAgent.generate_opening_message "
"prompt_chars={} history_pairs_total={} history_pairs_windowed={}",
prompt_chars,
hw.turn_total,
len(hw.window) // 2,
)
response = await opening_llm.ainvoke(messages)
logger.info(
"event=chat_llm_done agent=InterviewAgent.generate_opening_message "
"response_latency_ms={:.2f}",
(time.perf_counter() - llm_t0) * 1000,
)
response_text = (
response.content if hasattr(response, "content") else str(response)
)