session.py 9.76 KB
"""会话、轮次、推理轨迹的读写与反馈。"""
from __future__ import annotations

import datetime as dt
import time
from typing import Any

from fastapi import HTTPException
from sqlalchemy import func, select

from ..core import identity
from ..core.dbx import iso, jdump, jload, new_id, now, session
from ..governance import audit
from .models import AskTrace, Conversation, Turn

EMPTY_LINKS = {"concepts": [], "instances": [], "time": None}
# 服务重启等原因留下的「running」轮次,超过这个时间就当作已中断显示
STALE_RUNNING = dt.timedelta(minutes=10)


def ensure_conversation(conv_id: str, question: str) -> str:
    actor = identity.current()
    with session() as s:
        if conv_id:
            c = s.get(Conversation, conv_id)
            if c is not None and c.workspace == actor.workspace:
                c.updated_at = now()
                s.commit()
                return c.id
        c = Conversation(id=new_id("cv"), workspace=actor.workspace, title=question[:60],
                         created_by=actor.id)
        s.add(c)
        s.commit()
        return c.id


def new_turn(conv_id: str, question: str) -> str:
    actor = identity.current()
    with session() as s:
        seq = (s.scalar(select(func.max(Turn.seq)).where(Turn.conversation_id == conv_id)) or 0) + 1
        turn = Turn(id=new_id("tn"), conversation_id=conv_id, seq=seq, question=question,
                    created_by=actor.id, links_json=jdump(EMPTY_LINKS))
        s.add(turn)
        s.commit()
        return turn.id


def history(conv_id: str, limit: int = 3) -> list[dict]:
    with session() as s:
        rows = s.scalars(select(Turn).where(Turn.conversation_id == conv_id,
                                            Turn.status == "done")
                         .order_by(Turn.seq.desc()).limit(limit)).all()
        return [{"question": t.question, "answer": (t.answer or "")[:500],
                 "plan": jload(t.plan_json, {})} for t in reversed(rows)]


def _links(raw: str) -> dict:
    v = jload(raw, {})
    if not isinstance(v, dict):
        v = {}
    return {"concepts": v.get("concepts") or [], "instances": v.get("instances") or [],
            "time": v.get("time")}


def _status(t: Turn) -> str:
    if t.status == "running" and t.created_at and now() - t.created_at > STALE_RUNNING:
        return "aborted"
    return t.status or "done"


def turn_dict(t: Turn) -> dict:
    return {"id": t.id, "conversation_id": t.conversation_id, "seq": t.seq,
            "question": t.question, "status": _status(t), "links": _links(t.links_json),
            "plan": jload(t.plan_json, {}) or {}, "steps": jload(t.steps_json, []) or [],
            "answer": t.answer or "", "citations": jload(t.citations_json, []) or [],
            "data_refs": jload(t.data_refs_json, []) or [], "actions": jload(t.actions_json, []) or [],
            "sops": jload(t.sops_json, []) or [], "rating": t.rating or 0, "feedback": t.feedback or "",
            "duration_ms": t.duration_ms or 0, "created_at": iso(t.created_at)}


def list_conversations(limit: int = 50) -> list[dict]:
    actor = identity.current()
    with session() as s:
        rows = s.scalars(select(Conversation).where(
            Conversation.workspace == actor.workspace, Conversation.created_by == actor.id)
            .order_by(Conversation.pinned.desc(), Conversation.updated_at.desc()).limit(limit)).all()
        counts = dict(s.execute(select(Turn.conversation_id, func.count(Turn.id))
                                .where(Turn.conversation_id.in_([r.id for r in rows] or ["-"]))
                                .group_by(Turn.conversation_id)).all())
        return [{"id": c.id, "title": c.title, "turns": int(counts.get(c.id, 0)), "pinned": bool(c.pinned),
                 "updated_at": iso(c.updated_at)} for c in rows]


def update_conversation(conv_id: str, *, title: str | None = None, pinned: bool | None = None) -> dict:
    """改名 / 置顶。只能动自己的对话。"""
    actor = identity.current()
    with session() as s:
        c = s.get(Conversation, conv_id)
        if c is None or c.workspace != actor.workspace or c.created_by != actor.id:
            raise HTTPException(404, "对话不存在")
        updated = c.updated_at
        if title is not None and title.strip():
            c.title = title.strip()[:255]
        if pinned is not None:
            c.pinned = 1 if pinned else 0
        c.updated_at = updated            # 改名、置顶不算「最近聊过」,不改变它在列表里的时间位置
        s.commit()
        return {"id": c.id, "title": c.title, "pinned": bool(c.pinned)}


def get_conversation(conv_id: str) -> dict:
    with session() as s:
        c = s.get(Conversation, conv_id)
        if c is None or c.workspace != identity.current().workspace:
            raise HTTPException(404, "会话不存在")
        rows = s.scalars(select(Turn).where(Turn.conversation_id == conv_id).order_by(Turn.seq)).all()
        stats = {r.turn_id: jload(r.stats_json, {}) for r in s.scalars(
            select(AskTrace).where(AskTrace.turn_id.in_([t.id for t in rows] or ["-"]))).all()}
        turns = []
        for t in rows:
            d = turn_dict(t)
            d["stats"] = stats.get(t.id) or {}
            d["has_trace"] = t.id in stats
            turns.append(d)
        return {"id": c.id, "title": c.title, "turns": turns}


def delete_conversation(conv_id: str) -> None:
    get_conversation(conv_id)
    with session() as s:
        for t in s.scalars(select(Turn).where(Turn.conversation_id == conv_id)).all():
            tr = s.get(AskTrace, t.id)
            if tr is not None:
                s.delete(tr)
            s.delete(t)
        s.delete(s.get(Conversation, conv_id))
        s.commit()


def get_turn(turn_id: str) -> dict:
    with session() as s:
        t = s.get(Turn, turn_id)
        if t is None:
            raise HTTPException(404, "记录不存在")
        return turn_dict(t)


def mark_card(turn_id: str, kind: str, index: int, ref: str) -> dict:
    """记下「这张卡已经提交 / 已经确认发起」:刷新页面、换个设备回来看,都不会再让人点第二次。
    kind: action(ref = 审批单编号)/ sop(ref = 流程运行编号)。同一张卡只认第一次。"""
    actor = identity.current()
    with session() as s:
        t = s.get(Turn, turn_id)
        if t is None:
            raise HTTPException(404, "记录不存在")
        cards = jload(t.sops_json if kind == "sop" else t.actions_json, []) or []
        if not 0 <= index < len(cards):
            raise HTTPException(404, "这张卡片不存在")
        if not cards[index].get("submitted"):
            cards[index]["submitted"] = {"ref": ref, "by": actor.id, "at": iso(now())}
            if kind == "sop":
                t.sops_json = jdump(cards)
            else:
                t.actions_json = jdump(cards)
            s.commit()
        return cards[index]


def get_trace(turn_id: str) -> dict:
    get_turn(turn_id)
    with session() as s:
        tr = s.get(AskTrace, turn_id)
        if tr is None:
            return {"turn_id": turn_id, "events": [], "stats": {}, "memory": {}}
        return {"turn_id": turn_id, "events": jload(tr.events_json, []) or [],
                "stats": jload(tr.stats_json, {}) or {}, "memory": jload(tr.memory_json, {}) or {}}


def save_turn(turn_id: str, status: str, *, links: dict | None = None, plan: dict | None = None,
              steps: list | None = None, answer: str | None = None, citations: list | None = None,
              data_refs: list | None = None, cards: list | None = None, sops: list | None = None,
              started: float | None = None) -> None:
    with session() as s:
        t = s.get(Turn, turn_id)
        if t is None:
            return
        t.status = status
        if links is not None:
            t.links_json = jdump({**EMPTY_LINKS, **links})
        if plan is not None:
            t.plan_json = jdump(plan)
        if steps is not None:
            t.steps_json = jdump(steps)
        if answer is not None:
            t.answer = answer
        if citations is not None:
            t.citations_json = jdump(citations)
        if data_refs is not None:
            t.data_refs_json = jdump(data_refs)
        if cards is not None:
            t.actions_json = jdump(cards)
        if sops is not None:
            t.sops_json = jdump(sops)
        if started is not None:
            t.duration_ms = int((time.time() - started) * 1000)
        s.commit()


def save_trace(turn_id: str, events: list[dict], stats: dict, memory: dict | None = None) -> None:
    with session() as s:
        tr = s.get(AskTrace, turn_id)
        if tr is None:
            tr = AskTrace(turn_id=turn_id)
            s.add(tr)
        tr.events_json = jdump(events)
        tr.stats_json = jdump(stats)
        tr.memory_json = jdump(memory or {})
        s.commit()


def feedback(turn_id: str, rating: int, comment: str = "", correction: str = "") -> dict:
    from ..governance import review
    from ..memory import service as memory
    t = get_turn(turn_id)
    with session() as s:
        row = s.get(Turn, turn_id)
        row.rating = 1 if rating > 0 else -1 if rating < 0 else 0
        row.feedback = (comment or "")[:4000]
        s.commit()
    audit.record("ask.feedback", "turn", turn_id, f"{'👍' if rating > 0 else '👎'} {comment[:200]}")
    learned: dict[str, Any] = memory.on_feedback(turn_id, rating, comment, correction)
    item = None
    if rating < 0 or correction:
        item = review.propose("feedback", f"答案纠错:{t['question'][:80]}", {
            "turn_id": turn_id, "question": t["question"], "answer": t["answer"][:3000],
            "comment": comment, "correction": correction,
            "plan": t["plan"], "links": t["links"]}, source="feedback", target_ref=turn_id)
    return {"ok": True, "review_item": item, "learned": learned}