2026-03-19 10:36:55 +08:00
|
|
|
|
"""
|
|
|
|
|
|
ProfileAgent:用户资料收集 Specialist
|
|
|
|
|
|
负责提取资料、资料追问、资料收集开场白,不负责 Redis 持久化(由 Orchestrator 统一处理)
|
|
|
|
|
|
"""
|
2026-03-19 14:36:14 +08:00
|
|
|
|
|
2026-04-02 12:00:00 +08:00
|
|
|
|
import time
|
2026-03-19 10:36:55 +08:00
|
|
|
|
from typing import Any, Dict, List, Optional
|
|
|
|
|
|
|
2026-04-02 12:00:00 +08:00
|
|
|
|
from langchain_core.messages import AIMessage, HumanMessage, SystemMessage
|
2026-03-19 10:36:55 +08:00
|
|
|
|
|
2026-04-02 12:00:00 +08:00
|
|
|
|
from app.agents.chat.helpers import format_history_string, get_history_with_window
|
2026-03-19 10:54:48 +08:00
|
|
|
|
from app.agents.chat.prompts_profile import (
|
2026-03-19 10:36:55 +08:00
|
|
|
|
get_profile_extraction_prompt,
|
|
|
|
|
|
get_profile_followup_prompt,
|
|
|
|
|
|
get_profile_greeting_prompt,
|
|
|
|
|
|
)
|
2026-04-08 15:37:09 +08:00
|
|
|
|
from app.agents.chat.reply_limits import (
|
|
|
|
|
|
nonempty_segments_or_fallback,
|
|
|
|
|
|
segments_from_llm_response,
|
|
|
|
|
|
truncate_chat_segments,
|
|
|
|
|
|
)
|
2026-04-03 13:34:27 +08:00
|
|
|
|
from app.agents.chat.schemas import ProfileExtractionOutput
|
2026-03-26 12:13:36 +08:00
|
|
|
|
from app.core.agent_logging import agent_span, log_agent_payload, log_agent_summary
|
|
|
|
|
|
from app.core.config import settings
|
2026-04-02 12:00:00 +08:00
|
|
|
|
from app.core.dependencies import get_llm_provider
|
2026-04-03 13:34:27 +08:00
|
|
|
|
from app.core.llm_call import allm_json_call
|
2026-03-20 15:15:35 +08:00
|
|
|
|
from app.core.logging import get_logger
|
2026-03-19 10:36:55 +08:00
|
|
|
|
|
|
|
|
|
|
logger = get_logger(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _get_langchain_llm():
|
|
|
|
|
|
try:
|
|
|
|
|
|
provider = get_llm_provider()
|
|
|
|
|
|
return getattr(provider, "langchain_llm", None)
|
|
|
|
|
|
except Exception:
|
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-04-02 12:00:00 +08:00
|
|
|
|
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
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-03-19 10:36:55 +08:00
|
|
|
|
class ProfileAgent:
|
|
|
|
|
|
"""用户资料收集 Specialist Agent"""
|
|
|
|
|
|
|
|
|
|
|
|
def __init__(self):
|
|
|
|
|
|
self.llm = _get_langchain_llm()
|
|
|
|
|
|
|
2026-04-03 13:34:27 +08:00
|
|
|
|
async def _invoke_chat(
|
|
|
|
|
|
self,
|
|
|
|
|
|
messages: List[Any],
|
|
|
|
|
|
*,
|
|
|
|
|
|
max_tokens: int,
|
|
|
|
|
|
conversation_id: Optional[str],
|
|
|
|
|
|
agent_name: str,
|
|
|
|
|
|
) -> str:
|
|
|
|
|
|
chat_llm = self.llm.bind(max_tokens=max_tokens)
|
|
|
|
|
|
llm_t0 = time.perf_counter()
|
|
|
|
|
|
with agent_span(
|
|
|
|
|
|
logger, f"{agent_name}.llm", conversation_id=conversation_id or ""
|
|
|
|
|
|
):
|
|
|
|
|
|
response = await chat_llm.ainvoke(messages)
|
|
|
|
|
|
logger.info(
|
|
|
|
|
|
"event=chat_llm_done agent={} response_latency_ms={:.2f}",
|
|
|
|
|
|
agent_name,
|
|
|
|
|
|
(time.perf_counter() - llm_t0) * 1000,
|
|
|
|
|
|
)
|
|
|
|
|
|
return (
|
|
|
|
|
|
response.content if hasattr(response, "content") else str(response)
|
|
|
|
|
|
) or ""
|
|
|
|
|
|
|
|
|
|
|
|
async def _segments_from_response(
|
|
|
|
|
|
self,
|
|
|
|
|
|
response_text: str,
|
|
|
|
|
|
*,
|
|
|
|
|
|
max_segments: int,
|
|
|
|
|
|
max_chars_per_segment: int,
|
|
|
|
|
|
fallback: str,
|
|
|
|
|
|
) -> List[str]:
|
|
|
|
|
|
log_agent_payload(
|
|
|
|
|
|
logger,
|
|
|
|
|
|
"ProfileAgent._segments_from_response.raw_response",
|
|
|
|
|
|
response_text,
|
|
|
|
|
|
)
|
|
|
|
|
|
raw_list = segments_from_llm_response(response_text, max_segments=max_segments)
|
|
|
|
|
|
if not raw_list:
|
|
|
|
|
|
raw_list = [response_text.strip()]
|
|
|
|
|
|
out = truncate_chat_segments(
|
|
|
|
|
|
raw_list,
|
|
|
|
|
|
max_segments=max_segments,
|
|
|
|
|
|
max_chars_per_segment=max_chars_per_segment,
|
|
|
|
|
|
)
|
|
|
|
|
|
segments = out if out else [response_text.strip()[:max_chars_per_segment]]
|
|
|
|
|
|
return nonempty_segments_or_fallback(segments, fallback=fallback)
|
|
|
|
|
|
|
2026-03-19 10:36:55 +08:00
|
|
|
|
async def extract_profile_from_message(
|
|
|
|
|
|
self,
|
|
|
|
|
|
user_message: str,
|
|
|
|
|
|
missing_fields: List[str],
|
|
|
|
|
|
conversation_id: Optional[str] = None,
|
|
|
|
|
|
) -> Dict[str, Any]:
|
|
|
|
|
|
"""从用户消息中提取资料字段,不持久化"""
|
|
|
|
|
|
if not self.llm or not missing_fields:
|
|
|
|
|
|
return {}
|
|
|
|
|
|
recent_dialogue = ""
|
|
|
|
|
|
if conversation_id:
|
2026-04-02 12:00:00 +08:00
|
|
|
|
hw = await get_history_with_window(
|
|
|
|
|
|
conversation_id,
|
|
|
|
|
|
max_pairs=settings.chat_history_max_pairs,
|
|
|
|
|
|
max_chars=settings.chat_history_max_chars,
|
2026-03-19 14:36:14 +08:00
|
|
|
|
)
|
2026-04-02 12:00:00 +08:00
|
|
|
|
recent = hw.window[-4:] if len(hw.window) > 4 else hw.window
|
2026-03-19 10:36:55 +08:00
|
|
|
|
parts = []
|
|
|
|
|
|
for msg in recent:
|
|
|
|
|
|
if isinstance(msg, HumanMessage):
|
|
|
|
|
|
parts.append(f"用户: {msg.content}")
|
|
|
|
|
|
elif isinstance(msg, AIMessage):
|
|
|
|
|
|
parts.append(f"助手: {msg.content}")
|
|
|
|
|
|
recent_dialogue = "\n".join(parts) if parts else ""
|
|
|
|
|
|
try:
|
|
|
|
|
|
prompt = get_profile_extraction_prompt(
|
|
|
|
|
|
user_message, missing_fields, recent_dialogue=recent_dialogue or None
|
|
|
|
|
|
)
|
2026-04-03 13:34:27 +08:00
|
|
|
|
parsed = await allm_json_call(
|
2026-03-26 12:13:36 +08:00
|
|
|
|
self.llm,
|
|
|
|
|
|
prompt,
|
2026-04-03 13:34:27 +08:00
|
|
|
|
ProfileExtractionOutput,
|
|
|
|
|
|
max_tokens=settings.chat_profile_extract_max_tokens,
|
2026-03-26 12:13:36 +08:00
|
|
|
|
agent="ProfileAgent.extract_profile_from_message",
|
2026-04-03 13:34:27 +08:00
|
|
|
|
fallback_factory=lambda: ProfileExtractionOutput(),
|
2026-03-26 12:13:36 +08:00
|
|
|
|
)
|
2026-03-19 10:36:55 +08:00
|
|
|
|
result = {}
|
2026-04-03 13:34:27 +08:00
|
|
|
|
if parsed.birth_year is not None:
|
|
|
|
|
|
raw = parsed.birth_year
|
2026-03-19 10:36:55 +08:00
|
|
|
|
if isinstance(raw, int) and 1900 <= raw <= 2100:
|
|
|
|
|
|
result["birth_year"] = raw
|
|
|
|
|
|
elif isinstance(raw, str) and raw.isdigit():
|
|
|
|
|
|
y = int(raw)
|
|
|
|
|
|
if y < 100:
|
|
|
|
|
|
y = 1900 + y if y >= 50 else 2000 + y
|
|
|
|
|
|
if 1900 <= y <= 2100:
|
|
|
|
|
|
result["birth_year"] = y
|
2026-04-03 13:34:27 +08:00
|
|
|
|
if parsed.birth_place:
|
|
|
|
|
|
result["birth_place"] = str(parsed.birth_place)
|
|
|
|
|
|
if parsed.grew_up_place:
|
|
|
|
|
|
result["grew_up_place"] = str(parsed.grew_up_place)
|
|
|
|
|
|
if parsed.occupation:
|
|
|
|
|
|
result["occupation"] = str(parsed.occupation)
|
2026-04-06 22:22:50 +08:00
|
|
|
|
bp = result.get("birth_place")
|
|
|
|
|
|
gp = result.get("grew_up_place")
|
|
|
|
|
|
if bp and not gp:
|
|
|
|
|
|
result["grew_up_place"] = bp
|
|
|
|
|
|
elif gp and not bp:
|
|
|
|
|
|
result["birth_place"] = gp
|
2026-03-19 10:36:55 +08:00
|
|
|
|
return result
|
2026-04-03 13:34:27 +08:00
|
|
|
|
except Exception as e:
|
2026-03-26 12:13:36 +08:00
|
|
|
|
logger.error("提取资料信息失败: {}", e)
|
2026-03-19 10:36:55 +08:00
|
|
|
|
return {}
|
|
|
|
|
|
|
|
|
|
|
|
async def generate_profile_followup(
|
|
|
|
|
|
self,
|
|
|
|
|
|
conversation_id: str,
|
|
|
|
|
|
user_message: str,
|
|
|
|
|
|
missing_fields: List[str],
|
|
|
|
|
|
filled_fields: Dict[str, str],
|
|
|
|
|
|
nickname: str = "",
|
2026-03-26 12:13:36 +08:00
|
|
|
|
interview_stage_hint: str = "",
|
2026-03-19 10:36:55 +08:00
|
|
|
|
) -> List[str]:
|
|
|
|
|
|
"""生成资料追问回复,不持久化(由 Orchestrator 负责)"""
|
|
|
|
|
|
if not self.llm:
|
|
|
|
|
|
return ["谢谢!还能告诉我更多吗?"]
|
|
|
|
|
|
try:
|
|
|
|
|
|
prompt = get_profile_followup_prompt(
|
2026-03-26 12:13:36 +08:00
|
|
|
|
missing_fields,
|
|
|
|
|
|
filled_fields,
|
|
|
|
|
|
nickname,
|
|
|
|
|
|
interview_stage_hint=interview_stage_hint,
|
2026-03-19 10:36:55 +08:00
|
|
|
|
)
|
2026-04-02 12:00:00 +08:00
|
|
|
|
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)
|
|
|
|
|
|
messages.append(HumanMessage(content=user_message))
|
|
|
|
|
|
log_agent_payload(
|
|
|
|
|
|
logger,
|
|
|
|
|
|
"ProfileAgent.followup.prompt",
|
2026-04-03 13:49:24 +08:00
|
|
|
|
format_history_string(
|
|
|
|
|
|
messages,
|
|
|
|
|
|
omit_system_body=settings.agent_log_omit_system_message_body,
|
|
|
|
|
|
),
|
2026-03-19 14:36:14 +08:00
|
|
|
|
)
|
2026-04-03 13:34:27 +08:00
|
|
|
|
prompt_chars = _message_contents_char_count(messages)
|
2026-04-02 12:00:00 +08:00
|
|
|
|
logger.info(
|
2026-04-03 13:34:27 +08:00
|
|
|
|
"event=chat_prompt_built agent=ProfileAgent.generate_profile_followup "
|
|
|
|
|
|
"prompt_chars={} history_pairs_total={} history_pairs_windowed={}",
|
|
|
|
|
|
prompt_chars,
|
|
|
|
|
|
hw.turn_total,
|
|
|
|
|
|
len(hw.window) // 2,
|
2026-03-19 14:36:14 +08:00
|
|
|
|
)
|
2026-04-03 13:34:27 +08:00
|
|
|
|
response_text = await self._invoke_chat(
|
|
|
|
|
|
messages,
|
|
|
|
|
|
max_tokens=settings.chat_profile_followup_max_tokens,
|
|
|
|
|
|
conversation_id=conversation_id,
|
|
|
|
|
|
agent_name="ProfileAgent.generate_profile_followup",
|
2026-03-26 12:13:36 +08:00
|
|
|
|
)
|
2026-04-03 13:34:27 +08:00
|
|
|
|
segments = await self._segments_from_response(
|
|
|
|
|
|
response_text,
|
2026-03-26 12:13:36 +08:00
|
|
|
|
max_segments=3,
|
|
|
|
|
|
max_chars_per_segment=settings.chat_interview_max_chars_per_segment,
|
2026-04-03 13:34:27 +08:00
|
|
|
|
fallback="谢谢分享!能再告诉我一些吗?",
|
2026-03-26 12:13:36 +08:00
|
|
|
|
)
|
|
|
|
|
|
log_agent_summary(
|
|
|
|
|
|
logger,
|
|
|
|
|
|
"ProfileAgent.followup segments={} conversation_id={}",
|
2026-04-03 13:34:27 +08:00
|
|
|
|
len(segments),
|
2026-03-26 12:13:36 +08:00
|
|
|
|
conversation_id,
|
|
|
|
|
|
)
|
2026-04-03 13:34:27 +08:00
|
|
|
|
return segments
|
2026-03-19 10:36:55 +08:00
|
|
|
|
except Exception as e:
|
2026-03-26 12:13:36 +08:00
|
|
|
|
logger.error("生成资料跟进回复失败: {}", e)
|
2026-03-19 10:36:55 +08:00
|
|
|
|
return ["谢谢分享!能再告诉我一些吗?"]
|
|
|
|
|
|
|
|
|
|
|
|
async def generate_profile_greeting(
|
|
|
|
|
|
self,
|
|
|
|
|
|
conversation_id: str,
|
|
|
|
|
|
missing_fields: List[str],
|
|
|
|
|
|
nickname: str = "",
|
|
|
|
|
|
) -> List[str]:
|
|
|
|
|
|
"""生成资料收集开场白,不持久化(由 Orchestrator 负责)"""
|
|
|
|
|
|
if not self.llm:
|
|
|
|
|
|
return ["你好!在开始之前,能告诉我你是哪一年出生的吗?"]
|
|
|
|
|
|
try:
|
|
|
|
|
|
prompt = get_profile_greeting_prompt(missing_fields, nickname)
|
2026-04-02 12:00:00 +08:00
|
|
|
|
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 hw.window:
|
|
|
|
|
|
messages.append(
|
|
|
|
|
|
HumanMessage(content="(请根据上文自然接话,继续资料收集开场。)")
|
|
|
|
|
|
)
|
|
|
|
|
|
else:
|
|
|
|
|
|
messages.append(HumanMessage(content="(请说出资料收集开场白。)"))
|
|
|
|
|
|
log_agent_payload(
|
2026-04-03 13:49:24 +08:00
|
|
|
|
logger,
|
|
|
|
|
|
"ProfileAgent.greeting.prompt",
|
|
|
|
|
|
format_history_string(
|
|
|
|
|
|
messages,
|
|
|
|
|
|
omit_system_body=settings.agent_log_omit_system_message_body,
|
|
|
|
|
|
),
|
2026-04-02 12:00:00 +08:00
|
|
|
|
)
|
2026-04-03 13:34:27 +08:00
|
|
|
|
prompt_chars = _message_contents_char_count(messages)
|
2026-04-02 12:00:00 +08:00
|
|
|
|
logger.info(
|
2026-04-03 13:34:27 +08:00
|
|
|
|
"event=chat_prompt_built agent=ProfileAgent.generate_profile_greeting "
|
|
|
|
|
|
"prompt_chars={} history_pairs_total={} history_pairs_windowed={}",
|
|
|
|
|
|
prompt_chars,
|
|
|
|
|
|
hw.turn_total,
|
|
|
|
|
|
len(hw.window) // 2,
|
2026-04-02 12:00:00 +08:00
|
|
|
|
)
|
2026-04-03 13:34:27 +08:00
|
|
|
|
response_text = await self._invoke_chat(
|
|
|
|
|
|
messages,
|
|
|
|
|
|
max_tokens=settings.chat_profile_followup_max_tokens,
|
|
|
|
|
|
conversation_id=conversation_id,
|
|
|
|
|
|
agent_name="ProfileAgent.generate_profile_greeting",
|
2026-03-26 12:13:36 +08:00
|
|
|
|
)
|
2026-04-03 13:34:27 +08:00
|
|
|
|
segments = await self._segments_from_response(
|
|
|
|
|
|
response_text,
|
2026-03-26 12:13:36 +08:00
|
|
|
|
max_segments=2,
|
|
|
|
|
|
max_chars_per_segment=settings.chat_interview_max_chars_per_segment,
|
2026-04-03 13:34:27 +08:00
|
|
|
|
fallback="你好!在开始之前,能告诉我你是哪一年出生的吗?",
|
2026-03-26 12:13:36 +08:00
|
|
|
|
)
|
|
|
|
|
|
log_agent_summary(
|
|
|
|
|
|
logger,
|
|
|
|
|
|
"ProfileAgent.greeting segments={} conversation_id={}",
|
2026-04-03 13:34:27 +08:00
|
|
|
|
len(segments),
|
2026-03-26 12:13:36 +08:00
|
|
|
|
conversation_id,
|
|
|
|
|
|
)
|
2026-04-03 13:34:27 +08:00
|
|
|
|
return segments
|
2026-03-19 10:36:55 +08:00
|
|
|
|
except Exception as e:
|
2026-03-26 12:13:36 +08:00
|
|
|
|
logger.error("生成资料收集开场白失败: {}", e)
|
2026-03-19 14:36:14 +08:00
|
|
|
|
return [
|
|
|
|
|
|
"你好!在我们开始聊人生故事之前,能先简单介绍一下你自己吗?比如你是哪一年出生的?"
|
|
|
|
|
|
]
|