backfill_episodic.py 3.13 KB
"""存量回填:把历史会话消息批量写入情景向量库(Qdrant `wiki_episodic_memory`)。

情景检索上线后,老对话不会自动进索引;跑一次本脚本把存量补齐,之后新对话由
`_persist_turn → episodic.index_turn` 增量维护。

- 只回填未删除会话(status != 'deleted')的消息;空正文跳过。
- point id 由 (session_id, seq) 确定性生成,**可重复运行**(重复只覆盖,不产生重复点)。
- 仅写向量 + 指针,不存原文(原文权威源仍是 wiki_session_messages)。

用法:
  python -m scripts.backfill_episodic            # 全量回填
  python -m scripts.backfill_episodic --batch 128
"""
from __future__ import annotations

import argparse
import asyncio
import logging
import os
import sys

from sqlalchemy import select

sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))

from src.database.models import WikiSession, WikiSessionMessage  # noqa: E402
from src.database.session import AsyncSessionLocal  # noqa: E402
from src.services.memory import episodic  # noqa: E402

logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logger = logging.getLogger("backfill_episodic")


async def _collect_rows() -> list[dict]:
    """取所有未删除会话的消息,组装成 episodic.upsert_rows 需要的行。"""
    async with AsyncSessionLocal() as session:
        alive_ids = (
            await session.execute(
                select(WikiSession.id).where(WikiSession.status != "deleted")
            )
        ).scalars().all()
        if not alive_ids:
            return []
        msgs = (
            await session.execute(
                select(WikiSessionMessage)
                .where(WikiSessionMessage.session_id.in_(list(alive_ids)))
                .order_by(WikiSessionMessage.session_id, WikiSessionMessage.seq)
            )
        ).scalars().all()

    rows = [
        {
            "user_id": m.user_id,
            "session_id": m.session_id,
            "seq": m.seq,
            "role": m.role,
            "content": m.content or "",
            "ts": m.created_at.isoformat() if m.created_at else None,
        }
        for m in msgs
        if (m.content or "").strip()
    ]
    return rows


async def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--batch", type=int, default=128, help="每批嵌入/写入的消息条数")
    args = parser.parse_args()

    rows = await _collect_rows()
    if not rows:
        logger.info("没有可回填的消息(无未删除会话或消息为空)。")
        return

    total = 0
    for start in range(0, len(rows), args.batch):
        batch = rows[start : start + args.batch]
        # upsert_rows 是同步的(embed + qdrant),放线程池避免阻塞事件循环
        written = await asyncio.to_thread(episodic.upsert_rows, batch)
        total += written
        logger.info("已回填 %d/%d 条", min(start + args.batch, len(rows)), len(rows))

    logger.info("回填完成:共写入 %d 个情景点(覆盖 %d 条消息)。", total, len(rows))


if __name__ == "__main__":
    asyncio.run(main())