2026-03-19 10:38:11 +08:00
|
|
|
|
"""
|
|
|
|
|
|
MemoirOrchestrator:按 segment 编排流水线,调用各 Specialist Agent。
|
|
|
|
|
|
负责:遍历 segments、按 category 聚合、调用 Specialist、更新 state;
|
|
|
|
|
|
持久化与章节生成由 process_category 回调完成。
|
|
|
|
|
|
"""
|
2026-03-19 14:36:14 +08:00
|
|
|
|
|
2026-03-19 10:38:11 +08:00
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
2026-03-26 12:13:36 +08:00
|
|
|
|
import time
|
2026-03-22 16:45:57 +08:00
|
|
|
|
from dataclasses import dataclass
|
2026-03-19 10:38:11 +08:00
|
|
|
|
from typing import Any, Callable, Dict, List, Set, Tuple
|
|
|
|
|
|
|
|
|
|
|
|
from app.agents.memoir.classification_agent import (
|
|
|
|
|
|
ClassificationAgent,
|
2026-03-22 16:45:57 +08:00
|
|
|
|
)
|
|
|
|
|
|
from app.agents.memoir.classification_agent import (
|
2026-03-19 10:38:11 +08:00
|
|
|
|
_detect_stage as detect_stage_from_keywords,
|
|
|
|
|
|
)
|
2026-03-22 16:45:57 +08:00
|
|
|
|
from app.agents.memoir.extraction_agent import ExtractionAgent, ExtractionResult
|
|
|
|
|
|
from app.agents.state_schema import MemoirStateSchema
|
2026-03-26 12:13:36 +08:00
|
|
|
|
from app.core.agent_logging import agent_span, agent_summary_enabled, log_agent_detail
|
2026-03-22 16:45:57 +08:00
|
|
|
|
from app.core.logging import get_logger
|
|
|
|
|
|
from app.features.conversation.models import Segment
|
2026-03-19 10:38:11 +08:00
|
|
|
|
|
|
|
|
|
|
logger = get_logger(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-03-22 16:45:57 +08:00
|
|
|
|
@dataclass
|
|
|
|
|
|
class PreparedMemoirBatches:
|
|
|
|
|
|
"""Explicit batching result: updated state + segments grouped by chapter category."""
|
|
|
|
|
|
|
|
|
|
|
|
state: MemoirStateSchema
|
|
|
|
|
|
category_to_segments: Dict[str, List[Segment]]
|
2026-03-31 23:55:26 +08:00
|
|
|
|
#: segment id 在「LLM 判 none 且 extraction slots 为空」时加入;batch 级短路见 memoir_tasks
|
|
|
|
|
|
segment_skip_story_ids: Set[str]
|
2026-03-22 16:45:57 +08:00
|
|
|
|
|
|
|
|
|
|
|
2026-03-19 10:38:11 +08:00
|
|
|
|
class MemoirOrchestrator:
|
|
|
|
|
|
"""
|
|
|
|
|
|
回忆录生成编排器。
|
|
|
|
|
|
遍历 segments → ExtractionAgent → ClassificationAgent → 按 category 聚合 →
|
|
|
|
|
|
调用 process_category 生成叙事并持久化。
|
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
|
|
def __init__(self) -> None:
|
|
|
|
|
|
self.extraction_agent = ExtractionAgent()
|
|
|
|
|
|
self.classification_agent = ClassificationAgent()
|
|
|
|
|
|
|
2026-03-22 16:45:57 +08:00
|
|
|
|
def prepare_batches(
|
2026-03-19 10:38:11 +08:00
|
|
|
|
self,
|
|
|
|
|
|
*,
|
|
|
|
|
|
segments: List[Segment],
|
|
|
|
|
|
llm: Any,
|
|
|
|
|
|
get_or_create_state: Callable[[], MemoirStateSchema],
|
2026-03-19 14:36:14 +08:00
|
|
|
|
update_slot: Callable[[str, str, str, List[str]], MemoirStateSchema],
|
2026-04-02 12:00:00 +08:00
|
|
|
|
llm_fast: Any | None = None,
|
2026-03-22 16:45:57 +08:00
|
|
|
|
) -> PreparedMemoirBatches:
|
2026-03-19 10:38:11 +08:00
|
|
|
|
"""
|
2026-03-22 16:45:57 +08:00
|
|
|
|
遍历 segments:Extraction → slot 更新 → Classification → 按 category 分桶。
|
|
|
|
|
|
不含锁与写章节/故事(由调用方显式执行)。
|
2026-04-02 12:00:00 +08:00
|
|
|
|
|
|
|
|
|
|
``llm_fast``:分类与抽取专用;未传时与 ``llm`` 相同(叙事/路由仍用 ``llm``)。
|
2026-03-19 10:38:11 +08:00
|
|
|
|
"""
|
|
|
|
|
|
state = get_or_create_state()
|
|
|
|
|
|
category_to_segments: Dict[str, List[Segment]] = {}
|
2026-03-31 23:55:26 +08:00
|
|
|
|
segment_skip_story_ids: Set[str] = set()
|
2026-04-02 12:00:00 +08:00
|
|
|
|
classify_extract_llm = llm_fast if llm_fast is not None else llm
|
2026-03-19 10:38:11 +08:00
|
|
|
|
|
|
|
|
|
|
for segment in segments:
|
2026-03-26 12:13:36 +08:00
|
|
|
|
text = segment.user_input_text or ""
|
|
|
|
|
|
seg_t0 = time.perf_counter()
|
2026-03-19 10:38:11 +08:00
|
|
|
|
initial_stage = detect_stage_from_keywords(
|
|
|
|
|
|
text, state.current_stage or "childhood"
|
|
|
|
|
|
)
|
|
|
|
|
|
stage_slots_raw = state.slots.get(initial_stage, {}) or {}
|
|
|
|
|
|
|
2026-03-26 12:13:36 +08:00
|
|
|
|
with agent_span(
|
|
|
|
|
|
logger,
|
|
|
|
|
|
"MemoirOrchestrator.ExtractionAgent.extract",
|
|
|
|
|
|
segment_id=segment.id,
|
|
|
|
|
|
):
|
|
|
|
|
|
result: ExtractionResult = self.extraction_agent.extract(
|
|
|
|
|
|
user_message=text,
|
|
|
|
|
|
current_stage=state.current_stage or "childhood",
|
|
|
|
|
|
stage_slots=stage_slots_raw,
|
2026-04-02 12:00:00 +08:00
|
|
|
|
llm=classify_extract_llm,
|
2026-03-26 12:13:36 +08:00
|
|
|
|
)
|
2026-03-19 10:38:11 +08:00
|
|
|
|
detected_stage = result.detected_stage
|
|
|
|
|
|
for slot_name, snippet in result.slots.items():
|
|
|
|
|
|
state = update_slot(detected_stage, slot_name, snippet, [segment.id])
|
|
|
|
|
|
|
2026-03-26 12:13:36 +08:00
|
|
|
|
with agent_span(
|
|
|
|
|
|
logger,
|
|
|
|
|
|
"MemoirOrchestrator.ClassificationAgent.classify",
|
|
|
|
|
|
segment_id=segment.id,
|
|
|
|
|
|
):
|
2026-03-31 23:55:26 +08:00
|
|
|
|
classify_result = self.classification_agent.classify(
|
2026-03-26 12:13:36 +08:00
|
|
|
|
text=text,
|
|
|
|
|
|
fallback_stage=detected_stage,
|
2026-04-02 12:00:00 +08:00
|
|
|
|
llm=classify_extract_llm,
|
2026-03-27 16:01:28 +08:00
|
|
|
|
segment_id=segment.id,
|
2026-03-26 12:13:36 +08:00
|
|
|
|
)
|
2026-03-31 23:55:26 +08:00
|
|
|
|
chapter_category = classify_result.category
|
|
|
|
|
|
if (not result.slots) and classify_result.llm_said_none:
|
|
|
|
|
|
segment_skip_story_ids.add(str(segment.id))
|
|
|
|
|
|
|
2026-03-26 12:13:36 +08:00
|
|
|
|
if agent_summary_enabled():
|
|
|
|
|
|
logger.info(
|
|
|
|
|
|
"MemoirOrchestrator.segment segment_id={} text_len={} "
|
|
|
|
|
|
"detected_stage={} category={} segment_total_ms={:.2f}",
|
|
|
|
|
|
segment.id,
|
|
|
|
|
|
len(text),
|
|
|
|
|
|
detected_stage,
|
|
|
|
|
|
chapter_category,
|
|
|
|
|
|
(time.perf_counter() - seg_t0) * 1000,
|
|
|
|
|
|
)
|
|
|
|
|
|
log_agent_detail(
|
|
|
|
|
|
logger,
|
|
|
|
|
|
"MemoirOrchestrator.segment_done segment_id={} slots={}",
|
|
|
|
|
|
segment.id,
|
|
|
|
|
|
list((result.slots or {}).keys()),
|
2026-03-19 10:38:11 +08:00
|
|
|
|
)
|
|
|
|
|
|
category_to_segments.setdefault(chapter_category, []).append(segment)
|
|
|
|
|
|
|
2026-03-22 16:45:57 +08:00
|
|
|
|
return PreparedMemoirBatches(
|
|
|
|
|
|
state=state,
|
|
|
|
|
|
category_to_segments=category_to_segments,
|
2026-03-31 23:55:26 +08:00
|
|
|
|
segment_skip_story_ids=segment_skip_story_ids,
|
2026-03-22 16:45:57 +08:00
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
def run(
|
|
|
|
|
|
self,
|
|
|
|
|
|
*,
|
|
|
|
|
|
segments: List[Segment],
|
|
|
|
|
|
llm: Any,
|
|
|
|
|
|
user_profile: str = "",
|
|
|
|
|
|
user_birth_year: Any = None,
|
|
|
|
|
|
get_or_create_state: Callable[[], MemoirStateSchema],
|
|
|
|
|
|
update_slot: Callable[[str, str, str, List[str]], MemoirStateSchema],
|
|
|
|
|
|
acquire_lock: Callable[[str], bool],
|
|
|
|
|
|
release_lock: Callable[[str], None],
|
|
|
|
|
|
process_category: Callable[
|
|
|
|
|
|
[
|
|
|
|
|
|
str,
|
|
|
|
|
|
List[Segment],
|
|
|
|
|
|
MemoirStateSchema,
|
|
|
|
|
|
str,
|
|
|
|
|
|
Any,
|
|
|
|
|
|
Any,
|
|
|
|
|
|
],
|
|
|
|
|
|
Tuple[Any, bool],
|
|
|
|
|
|
],
|
|
|
|
|
|
raise_retry: Callable[[], None],
|
2026-04-02 12:00:00 +08:00
|
|
|
|
llm_fast: Any | None = None,
|
2026-03-22 16:45:57 +08:00
|
|
|
|
) -> Tuple[Set[str], int]:
|
|
|
|
|
|
"""
|
|
|
|
|
|
执行回忆录流水线。
|
|
|
|
|
|
process_category(category, segments, state, user_profile, user_birth_year, llm)
|
|
|
|
|
|
返回 (chapter, has_images_to_generate)。
|
|
|
|
|
|
返回 (chapters_to_enqueue, processed_count)。
|
|
|
|
|
|
raise_retry 用于锁竞争时抛出 Celery retry。
|
|
|
|
|
|
"""
|
|
|
|
|
|
prepared = self.prepare_batches(
|
|
|
|
|
|
segments=segments,
|
|
|
|
|
|
llm=llm,
|
2026-04-02 12:00:00 +08:00
|
|
|
|
llm_fast=llm_fast,
|
2026-03-22 16:45:57 +08:00
|
|
|
|
get_or_create_state=get_or_create_state,
|
|
|
|
|
|
update_slot=update_slot,
|
|
|
|
|
|
)
|
|
|
|
|
|
state = prepared.state
|
|
|
|
|
|
chapters_to_enqueue: Set[str] = set()
|
|
|
|
|
|
category_to_segments = prepared.category_to_segments
|
|
|
|
|
|
|
|
|
|
|
|
# 按 category 调用 process_category:叙事生成、持久化、封面入队标记
|
2026-03-19 10:38:11 +08:00
|
|
|
|
for chapter_category, category_segments in category_to_segments.items():
|
|
|
|
|
|
if not acquire_lock(chapter_category):
|
|
|
|
|
|
logger.warning(
|
2026-03-26 12:13:36 +08:00
|
|
|
|
"章节锁竞争: category={}, 延迟重试",
|
2026-03-19 10:38:11 +08:00
|
|
|
|
chapter_category,
|
|
|
|
|
|
)
|
|
|
|
|
|
raise_retry()
|
|
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
|
chapter, has_images = process_category(
|
|
|
|
|
|
chapter_category,
|
|
|
|
|
|
category_segments,
|
|
|
|
|
|
state,
|
|
|
|
|
|
user_profile,
|
|
|
|
|
|
user_birth_year,
|
|
|
|
|
|
llm,
|
|
|
|
|
|
)
|
|
|
|
|
|
if chapter and has_images:
|
|
|
|
|
|
chapters_to_enqueue.add(chapter.id)
|
|
|
|
|
|
finally:
|
|
|
|
|
|
release_lock(chapter_category)
|
|
|
|
|
|
|
|
|
|
|
|
return chapters_to_enqueue, len(segments)
|