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

79 lines
2.3 KiB
Python
Raw Normal View History

2026-03-19 10:38:11 +08:00
"""
NarrativeAgent生成创意标题和叙事改写
对应现有逻辑get_creative_title_promptget_narrative_prompt
"""
from __future__ import annotations
from typing import Any, Dict, Optional
from app.core.logging import get_logger
from app.agents.memoir.prompts import (
2026-03-19 10:38:11 +08:00
get_creative_title_prompt,
get_narrative_prompt,
)
logger = get_logger(__name__)
class NarrativeAgent:
"""生成章节标题和叙事正文"""
def generate_title(
self,
stage: str,
emotion: str,
slots: Dict[str, str],
user_profile: str = "",
birth_year: Optional[int] = None,
llm: Any = None,
) -> str:
"""生成创意标题。若无 LLM 则返回默认标题"""
if not llm:
return f"{stage} 回忆"
try:
prompt = get_creative_title_prompt(
stage=stage,
emotion=emotion,
slots=slots,
user_profile=user_profile,
birth_year=birth_year,
)
response = llm.invoke(prompt)
return (response.content or "").strip().strip('"')
except Exception as e:
logger.warning("NarrativeAgent 生成标题失败: %s", e)
return f"{stage} 回忆"
def generate_narrative(
self,
stage: str,
slots: Dict[str, str],
new_content: str,
existing_content: str = "",
user_profile: str = "",
birth_year: Optional[int] = None,
llm: Any = None,
) -> str:
"""将新对话改写为叙述。若无 LLM 则直接拼接"""
if not llm:
if existing_content:
return f"{existing_content}\n\n{new_content}"
return new_content
try:
prompt = get_narrative_prompt(
stage=stage,
slots=slots,
new_content=new_content,
existing_content=existing_content,
user_profile=user_profile,
birth_year=birth_year,
)
response = llm.invoke(prompt)
return (response.content or "").strip()
except Exception as e:
logger.warning("NarrativeAgent 生成叙事失败: %s", e)
if existing_content:
return f"{existing_content}\n\n{new_content}"
return new_content