feat(M4.1): 多会话骨架——conversations表+API(列表/创建/继承/历史);messages加conversation_id(幂等ALTER);chat按会话隔离(历史/分界/入库/活跃);公告全局流conv=0
这个提交包含在:
+28
-12
@@ -20,6 +20,7 @@ class ChatBody(BaseModel):
|
|||||||
mode: str = "learning"
|
mode: str = "learning"
|
||||||
problem_id: int | None = None
|
problem_id: int | None = None
|
||||||
kind: str = "text" # text / code / latex / explain
|
kind: str = "text" # text / code / latex / explain
|
||||||
|
conversation_id: int = 0 # 学科窗口会话 id(0=默认/无会话)
|
||||||
|
|
||||||
|
|
||||||
class ExplainBody(BaseModel):
|
class ExplainBody(BaseModel):
|
||||||
@@ -59,15 +60,16 @@ def _course_prompt(session: Session, course_code: str) -> str:
|
|||||||
SEP_MSGS = 40
|
SEP_MSGS = 40
|
||||||
|
|
||||||
|
|
||||||
def _insert_sep(session: Session, user_id: int) -> None:
|
def _insert_sep(session: Session, user_id: int, conversation_id: int = 0) -> None:
|
||||||
"""插入会话分界消息(kind=sep,落库)。分界前已归档可上翻复盘,分界后算新一轮。"""
|
"""插入会话分界消息(kind=sep,落库,按会话维度)。分界前已归档可上翻复盘,分界后算新一轮。"""
|
||||||
n = MessageRepo(session).count_since_sep(user_id) # 含本次,>阈值时序号 = n//40
|
n = MessageRepo(session).count_since_sep(user_id, conversation_id) # 含本次,>阈值时序号 = n//40
|
||||||
seq = max(1, n // SEP_MSGS + (1 if n % SEP_MSGS else 0))
|
seq = max(1, n // SEP_MSGS + (1 if n % SEP_MSGS else 0))
|
||||||
MessageRepo(session).add(
|
MessageRepo(session).add(
|
||||||
user_id, "sys",
|
user_id, "sys",
|
||||||
f"—— 📑 会话分界 #{seq} ——\n此前对话已归档(向上滚动仍可复盘);本轮开始为新一轮对话。",
|
f"—— 📑 会话分界 #{seq} ——\n此前对话已归档(向上滚动仍可复盘);本轮开始为新一轮对话。",
|
||||||
kind="sep",
|
kind="sep",
|
||||||
meta={"session_sep": seq},
|
meta={"session_sep": seq},
|
||||||
|
conversation_id=conversation_id,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -75,8 +77,9 @@ def _insert_sep(session: Session, user_id: int) -> None:
|
|||||||
async def chat(body: ChatBody, authorization: str | None = Header(None), session: Session = Depends(get_session)):
|
async def chat(body: ChatBody, authorization: str | None = Header(None), session: Session = Depends(get_session)):
|
||||||
user = _current_user(_bearer(authorization), session)
|
user = _current_user(_bearer(authorization), session)
|
||||||
user_id = user["id"] if user else None
|
user_id = user["id"] if user else None
|
||||||
|
conv_id = body.conversation_id if user else 0
|
||||||
|
|
||||||
# 1) 用户消息入库
|
# 1) 用户消息入库(按会话)
|
||||||
last_user = body.messages[-1] if body.messages else None
|
last_user = body.messages[-1] if body.messages else None
|
||||||
saved = None
|
saved = None
|
||||||
if last_user and last_user.get("role") == "user":
|
if last_user and last_user.get("role") == "user":
|
||||||
@@ -84,6 +87,7 @@ async def chat(body: ChatBody, authorization: str | None = Header(None), session
|
|||||||
user_id, "user", last_user.get("content", ""),
|
user_id, "user", last_user.get("content", ""),
|
||||||
kind=body.kind or "text",
|
kind=body.kind or "text",
|
||||||
meta={"problem_id": body.problem_id, "mode": body.mode},
|
meta={"problem_id": body.problem_id, "mode": body.mode},
|
||||||
|
conversation_id=conv_id,
|
||||||
)
|
)
|
||||||
|
|
||||||
svc = AIService()
|
svc = AIService()
|
||||||
@@ -95,12 +99,19 @@ async def chat(body: ChatBody, authorization: str | None = Header(None), session
|
|||||||
context_md = prob.statement_md
|
context_md = prob.statement_md
|
||||||
course_prompt = _course_prompt(session, prob.course)
|
course_prompt = _course_prompt(session, prob.course)
|
||||||
if not course_prompt and user:
|
if not course_prompt and user:
|
||||||
# 纯闲聊:按用户注册学科给提示词(同一用户前缀稳定)
|
# 纯闲聊:按会话学科给提示词;无会话则用注册学科(同一用户前缀稳定)
|
||||||
course_prompt = _course_prompt(session, user.get("course", ""))
|
ccode = ""
|
||||||
|
if conv_id:
|
||||||
|
from app.repositories.conversation_repo import ConversationRepo
|
||||||
|
c = ConversationRepo(session).get(conv_id)
|
||||||
|
ccode = c.course if c else ""
|
||||||
|
if not ccode:
|
||||||
|
ccode = user.get("course", "")
|
||||||
|
course_prompt = _course_prompt(session, ccode)
|
||||||
|
|
||||||
# AI 上下文 = 最近分界后的历史消息(含刚入库的当前轮;judge/sys/sep 不进上下文)
|
# AI 上下文 = 该会话最近分界后的历史消息(含刚入库的当前轮;judge/sys/sep 不进上下文)
|
||||||
if user:
|
if user:
|
||||||
msgs = MessageRepo(session).list_since_sep(user["id"])
|
msgs = MessageRepo(session).list_since_sep(user["id"], conversation_id=conv_id)
|
||||||
history = [{"role": m.role, "content": m.content}
|
history = [{"role": m.role, "content": m.content}
|
||||||
for m in msgs if m.role in ("user", "assistant")]
|
for m in msgs if m.role in ("user", "assistant")]
|
||||||
if not history and body.messages:
|
if not history and body.messages:
|
||||||
@@ -112,13 +123,17 @@ async def chat(body: ChatBody, authorization: str | None = Header(None), session
|
|||||||
except RuntimeError as e:
|
except RuntimeError as e:
|
||||||
raise HTTPException(502, str(e))
|
raise HTTPException(502, str(e))
|
||||||
|
|
||||||
# 会话分界:分段内 user/assistant ≥ 阈值 → 插入分界(下轮起为新一轮,全量仍可复盘)
|
# 会话分界:该会话分段内 user/assistant ≥ 阈值 → 插入分界(下轮起为新一轮,全量仍可复盘)
|
||||||
if user:
|
if user:
|
||||||
sep_n = MessageRepo(session).count_since_sep(user["id"])
|
sep_n = MessageRepo(session).count_since_sep(user["id"], conversation_id=conv_id)
|
||||||
if sep_n >= 40:
|
if sep_n >= 40:
|
||||||
_insert_sep(session, user["id"])
|
_insert_sep(session, user["id"], conv_id)
|
||||||
|
# 会话活跃度刷新
|
||||||
|
from app.repositories.conversation_repo import ConversationRepo
|
||||||
|
if conv_id:
|
||||||
|
ConversationRepo(session).touch(conv_id)
|
||||||
|
|
||||||
# 2) AI 回复入库(含 token 用量)
|
# 2) AI 回复入库(含 token 用量,按会话)
|
||||||
ai_meta = {}
|
ai_meta = {}
|
||||||
usage = getattr(svc, "last_usage", None)
|
usage = getattr(svc, "last_usage", None)
|
||||||
if usage:
|
if usage:
|
||||||
@@ -126,6 +141,7 @@ async def chat(body: ChatBody, authorization: str | None = Header(None), session
|
|||||||
ai_msg = MessageRepo(session).add(
|
ai_msg = MessageRepo(session).add(
|
||||||
user_id, "assistant", reply, kind="text",
|
user_id, "assistant", reply, kind="text",
|
||||||
meta={"problem_id": body.problem_id, "mode": body.mode, **ai_meta},
|
meta={"problem_id": body.problem_id, "mode": body.mode, **ai_meta},
|
||||||
|
conversation_id=conv_id,
|
||||||
)
|
)
|
||||||
return {
|
return {
|
||||||
"reply": reply,
|
"reply": reply,
|
||||||
|
|||||||
@@ -0,0 +1,74 @@
|
|||||||
|
"""会话 API:学科窗口(列表/创建/继承/历史)。"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, Header, HTTPException
|
||||||
|
from pydantic import BaseModel
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from app.core.db import get_session
|
||||||
|
from app.repositories.conversation_repo import ConversationRepo
|
||||||
|
from app.repositories.message_repo import MessageRepo
|
||||||
|
from app.services.auth_service import AuthService
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/conversations", tags=["conversations"])
|
||||||
|
|
||||||
|
|
||||||
|
def _user(authorization: str | None, session: Session) -> dict:
|
||||||
|
if not authorization or not authorization.lower().startswith("bearer "):
|
||||||
|
raise HTTPException(401, "未登录")
|
||||||
|
try:
|
||||||
|
return AuthService(session).me(authorization[7:].strip())
|
||||||
|
except Exception as e:
|
||||||
|
raise HTTPException(401, str(e))
|
||||||
|
|
||||||
|
|
||||||
|
class ConvBody(BaseModel):
|
||||||
|
course: str = "ap-csa"
|
||||||
|
title: str = ""
|
||||||
|
inherit_from: int = 0
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("")
|
||||||
|
async def list_conversations(authorization: str | None = Header(None), session: Session = Depends(get_session)):
|
||||||
|
"""当前用户全部会话(学科窗口,按活跃倒序)。"""
|
||||||
|
u = _user(authorization, session)
|
||||||
|
convs = ConversationRepo(session).list_by_user(u["id"])
|
||||||
|
out = []
|
||||||
|
for c in convs:
|
||||||
|
d = c.to_dict()
|
||||||
|
d["msg_count"] = len(MessageRepo(session).list_by_user(u["id"], limit=500, conversation_id=c.id))
|
||||||
|
out.append(d)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("")
|
||||||
|
async def create_conversation(body: ConvBody, authorization: str | None = Header(None),
|
||||||
|
session: Session = Depends(get_session)):
|
||||||
|
"""新建会话(学科窗口)。inherit_from>0 时继承源会话学科与标题。"""
|
||||||
|
u = _user(authorization, session)
|
||||||
|
repo = ConversationRepo(session)
|
||||||
|
course, title, inherit = body.course, body.title, body.inherit_from
|
||||||
|
if inherit > 0:
|
||||||
|
src = repo.get(inherit)
|
||||||
|
if src and src.user_id == u["id"]:
|
||||||
|
course = src.course
|
||||||
|
if not title:
|
||||||
|
title = src.title or "续接 · " + course
|
||||||
|
if not title:
|
||||||
|
title = course
|
||||||
|
c = repo.create(u["id"], course=course, title=title, inherit_from=inherit)
|
||||||
|
return c.to_dict()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{conv_id}/messages")
|
||||||
|
async def conversation_messages(conv_id: int, limit: int = 300,
|
||||||
|
authorization: str | None = Header(None),
|
||||||
|
session: Session = Depends(get_session)):
|
||||||
|
"""某会话的完整消息流(含分界符/公告,上翻复盘)。"""
|
||||||
|
u = _user(authorization, session)
|
||||||
|
repo = ConversationRepo(session)
|
||||||
|
c = repo.get(conv_id)
|
||||||
|
if not c or c.user_id != u["id"]:
|
||||||
|
raise HTTPException(404, "会话不存在")
|
||||||
|
msgs = MessageRepo(session).list_by_user(u["id"], limit=min(limit, 500), conversation_id=conv_id)
|
||||||
|
return {"conversation": c.to_dict(), "messages": [m.to_dict() for m in msgs]}
|
||||||
+5
-2
@@ -29,7 +29,7 @@ def get_session():
|
|||||||
|
|
||||||
def init_db(url: str | None = None) -> None:
|
def init_db(url: str | None = None) -> None:
|
||||||
"""建表(启动时调用)。"""
|
"""建表(启动时调用)。"""
|
||||||
from app.models import klass, message, problem, progress, submission, user # noqa: F401 确保模型注册
|
from app.models import conversation, klass, message, problem, progress, submission, user # noqa: F401 确保模型注册
|
||||||
|
|
||||||
global engine, SessionLocal
|
global engine, SessionLocal
|
||||||
if url and url != settings.database_url:
|
if url and url != settings.database_url:
|
||||||
@@ -43,7 +43,7 @@ def init_db(url: str | None = None) -> None:
|
|||||||
|
|
||||||
|
|
||||||
def _migrate() -> None:
|
def _migrate() -> None:
|
||||||
"""小步迁移:老库加列(is_admin)。幂等:列已存在时忽略。"""
|
"""小步迁移:老库加列。幂等:列已存在时忽略。"""
|
||||||
if not settings.database_url.startswith("sqlite"):
|
if not settings.database_url.startswith("sqlite"):
|
||||||
return
|
return
|
||||||
from sqlalchemy import text
|
from sqlalchemy import text
|
||||||
@@ -52,3 +52,6 @@ def _migrate() -> None:
|
|||||||
cols = {r[1] for r in conn.execute(text("PRAGMA table_info(users)"))}
|
cols = {r[1] for r in conn.execute(text("PRAGMA table_info(users)"))}
|
||||||
if "is_admin" not in cols:
|
if "is_admin" not in cols:
|
||||||
conn.execute(text("ALTER TABLE users ADD COLUMN is_admin INTEGER DEFAULT 0"))
|
conn.execute(text("ALTER TABLE users ADD COLUMN is_admin INTEGER DEFAULT 0"))
|
||||||
|
mcols = {r[1] for r in conn.execute(text("PRAGMA table_info(messages)"))}
|
||||||
|
if "conversation_id" not in mcols:
|
||||||
|
conn.execute(text("ALTER TABLE messages ADD COLUMN conversation_id INTEGER DEFAULT 0"))
|
||||||
|
|||||||
+2
-1
@@ -9,7 +9,7 @@ from fastapi import FastAPI
|
|||||||
from fastapi.middleware.cors import CORSMiddleware
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
from fastapi.staticfiles import StaticFiles
|
from fastapi.staticfiles import StaticFiles
|
||||||
|
|
||||||
from app.api.routes import admin, auth, chat, courses, health, judge, latex, lsp, problems, progress, usage
|
from app.api.routes import admin, auth, chat, conversations, courses, health, judge, latex, lsp, problems, progress, usage
|
||||||
from app.core.config import settings
|
from app.core.config import settings
|
||||||
from app.core.db import SessionLocal, init_db
|
from app.core.db import SessionLocal, init_db
|
||||||
|
|
||||||
@@ -52,6 +52,7 @@ app.include_router(chat.router, prefix="/api")
|
|||||||
app.include_router(progress.router, prefix="/api")
|
app.include_router(progress.router, prefix="/api")
|
||||||
app.include_router(usage.router, prefix="/api")
|
app.include_router(usage.router, prefix="/api")
|
||||||
app.include_router(courses.router, prefix="/api")
|
app.include_router(courses.router, prefix="/api")
|
||||||
|
app.include_router(conversations.router, prefix="/api")
|
||||||
app.include_router(lsp.router, prefix="/api")
|
app.include_router(lsp.router, prefix="/api")
|
||||||
app.include_router(latex.router, prefix="/api")
|
app.include_router(latex.router, prefix="/api")
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
"""ORM 模型:题目、提交记录、学习进度、用户、对话消息、班级、学科配置。"""
|
"""ORM 模型:题目、提交记录、学习进度、用户、对话消息、班级、学科配置。"""
|
||||||
|
from app.models.conversation import Conversation
|
||||||
from app.models.course import Course
|
from app.models.course import Course
|
||||||
from app.models.klass import Class, ClassMember
|
from app.models.klass import Class, ClassMember
|
||||||
from app.models.message import Message
|
from app.models.message import Message
|
||||||
@@ -7,4 +8,4 @@ from app.models.progress import Progress
|
|||||||
from app.models.submission import Submission
|
from app.models.submission import Submission
|
||||||
from app.models.user import User
|
from app.models.user import User
|
||||||
|
|
||||||
__all__ = ["Class", "ClassMember", "Course", "Message", "Problem", "Progress", "Submission", "User"]
|
__all__ = ["Class", "ClassMember", "Conversation", "Course", "Message", "Problem", "Progress", "Submission", "User"]
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
"""会话表:学科窗口(每个会话一个学科,侧边栏列表;可继承源会话续接)。"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from sqlalchemy import DateTime, Integer, String, func
|
||||||
|
from sqlalchemy.orm import Mapped, mapped_column
|
||||||
|
|
||||||
|
from app.core.db import Base
|
||||||
|
|
||||||
|
|
||||||
|
class Conversation(Base):
|
||||||
|
__tablename__ = "conversations"
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||||
|
user_id: Mapped[int] = mapped_column(Integer, index=True)
|
||||||
|
course: Mapped[str] = mapped_column(String(32), default="ap-csa") # 学科窗口
|
||||||
|
title: Mapped[str] = mapped_column(String(64), default="") # 默认学科名
|
||||||
|
inherit_from: Mapped[int] = mapped_column(Integer, default=0) # 继承源会话 id(0=无)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())
|
||||||
|
last_active_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())
|
||||||
|
|
||||||
|
def to_dict(self) -> dict:
|
||||||
|
return {
|
||||||
|
"id": self.id,
|
||||||
|
"user_id": self.user_id,
|
||||||
|
"course": self.course,
|
||||||
|
"title": self.title,
|
||||||
|
"inherit_from": self.inherit_from,
|
||||||
|
"created_at": self.created_at.isoformat() if self.created_at else None,
|
||||||
|
"last_active_at": self.last_active_at.isoformat() if self.last_active_at else None,
|
||||||
|
}
|
||||||
@@ -16,6 +16,8 @@ class Message(Base):
|
|||||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||||
# 关联用户(未登录 guest 为 NULL)
|
# 关联用户(未登录 guest 为 NULL)
|
||||||
user_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"), nullable=True, index=True)
|
user_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"), nullable=True, index=True)
|
||||||
|
# 会话(学科窗口):0=全局/公告流
|
||||||
|
conversation_id: Mapped[int] = mapped_column(Integer, default=0, index=True)
|
||||||
# user / assistant / judge / sys
|
# user / assistant / judge / sys
|
||||||
role: Mapped[str] = mapped_column(String(16), index=True)
|
role: Mapped[str] = mapped_column(String(16), index=True)
|
||||||
# text / code / latex / explain / judge(内容形态)
|
# text / code / latex / explain / judge(内容形态)
|
||||||
@@ -35,6 +37,7 @@ class Message(Base):
|
|||||||
return {
|
return {
|
||||||
"id": self.id,
|
"id": self.id,
|
||||||
"user_id": self.user_id,
|
"user_id": self.user_id,
|
||||||
|
"conversation_id": self.conversation_id,
|
||||||
"role": self.role,
|
"role": self.role,
|
||||||
"kind": self.kind,
|
"kind": self.kind,
|
||||||
"content": self.content,
|
"content": self.content,
|
||||||
|
|||||||
@@ -0,0 +1,39 @@
|
|||||||
|
"""会话仓库:学科窗口的创建/列表/活跃更新。"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from sqlalchemy import func, select
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from app.models.conversation import Conversation
|
||||||
|
|
||||||
|
|
||||||
|
class ConversationRepo:
|
||||||
|
def __init__(self, session: Session):
|
||||||
|
self.session = session
|
||||||
|
|
||||||
|
def list_by_user(self, user_id: int) -> list[Conversation]:
|
||||||
|
stmt = (
|
||||||
|
select(Conversation)
|
||||||
|
.where(Conversation.user_id == user_id)
|
||||||
|
.order_by(Conversation.last_active_at.desc())
|
||||||
|
)
|
||||||
|
return list(self.session.scalars(stmt))
|
||||||
|
|
||||||
|
def get(self, conv_id: int) -> Conversation | None:
|
||||||
|
return self.session.get(Conversation, conv_id)
|
||||||
|
|
||||||
|
def create(self, user_id: int, course: str = "ap-csa", title: str = "",
|
||||||
|
inherit_from: int = 0) -> Conversation:
|
||||||
|
c = Conversation(user_id=user_id, course=course, title=title, inherit_from=inherit_from)
|
||||||
|
self.session.add(c)
|
||||||
|
self.session.commit()
|
||||||
|
self.session.refresh(c)
|
||||||
|
return c
|
||||||
|
|
||||||
|
def touch(self, conv_id: int) -> None:
|
||||||
|
c = self.get(conv_id)
|
||||||
|
if c:
|
||||||
|
c.last_active_at = datetime.now()
|
||||||
|
self.session.commit()
|
||||||
@@ -13,9 +13,11 @@ class MessageRepo:
|
|||||||
def __init__(self, session: Session):
|
def __init__(self, session: Session):
|
||||||
self.session = session
|
self.session = session
|
||||||
|
|
||||||
def add(self, user_id: int | None, role: str, content: str, kind: str = "text", meta: dict | None = None) -> Message:
|
def add(self, user_id: int | None, role: str, content: str, kind: str = "text", meta: dict | None = None,
|
||||||
|
conversation_id: int = 0) -> Message:
|
||||||
msg = Message(
|
msg = Message(
|
||||||
user_id=user_id,
|
user_id=user_id,
|
||||||
|
conversation_id=conversation_id,
|
||||||
role=role,
|
role=role,
|
||||||
kind=kind,
|
kind=kind,
|
||||||
content=content,
|
content=content,
|
||||||
@@ -41,13 +43,13 @@ class MessageRepo:
|
|||||||
self.session.commit()
|
self.session.commit()
|
||||||
return objs
|
return objs
|
||||||
|
|
||||||
def list_by_user(self, user_id: int, limit: int = 200) -> list[Message]:
|
def list_by_user(self, user_id: int, limit: int = 200, conversation_id: int | None = None) -> list[Message]:
|
||||||
|
stmt = select(Message).where(Message.user_id == user_id)
|
||||||
|
if conversation_id is not None:
|
||||||
|
stmt = stmt.where(Message.conversation_id == conversation_id)
|
||||||
return list(
|
return list(
|
||||||
self.session.execute(
|
self.session.execute(
|
||||||
select(Message)
|
stmt.order_by(Message.created_at.asc(), Message.id.asc()).limit(limit)
|
||||||
.where(Message.user_id == user_id)
|
|
||||||
.order_by(Message.created_at.asc(), Message.id.asc())
|
|
||||||
.limit(limit)
|
|
||||||
).scalars()
|
).scalars()
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -97,34 +99,43 @@ class MessageRepo:
|
|||||||
return [self.session.get(Message, r[0]) for r in rows if self.session.get(Message, r[0])]
|
return [self.session.get(Message, r[0]) for r in rows if self.session.get(Message, r[0])]
|
||||||
|
|
||||||
# ---------- 会话分界(P7.1):对话流内插入分界符,分界后算新一轮;全量仍可复盘 ----------
|
# ---------- 会话分界(P7.1):对话流内插入分界符,分界后算新一轮;全量仍可复盘 ----------
|
||||||
def last_sep_id(self, user_id: int) -> int:
|
def last_sep_id(self, user_id: int, conversation_id: int = 0) -> int:
|
||||||
"""最近一次会话分界的消息 id(无分界返回 0)。"""
|
"""最近一次会话分界的消息 id(无分界返回 0)。按会话维度。"""
|
||||||
from sqlalchemy import func
|
from sqlalchemy import func
|
||||||
|
|
||||||
last = self.session.scalar(
|
last = self.session.scalar(
|
||||||
select(func.max(Message.id)).where(Message.user_id == user_id, Message.kind == "sep")
|
select(func.max(Message.id)).where(
|
||||||
|
Message.user_id == user_id,
|
||||||
|
Message.conversation_id == conversation_id,
|
||||||
|
Message.kind == "sep",
|
||||||
|
)
|
||||||
)
|
)
|
||||||
return last or 0
|
return last or 0
|
||||||
|
|
||||||
def count_since_sep(self, user_id: int) -> int:
|
def count_since_sep(self, user_id: int, conversation_id: int = 0) -> int:
|
||||||
"""最近分界之后 user/assistant 消息数(判断是否该分界)。"""
|
"""最近分界之后 user/assistant 消息数(判断是否该分界)。"""
|
||||||
from sqlalchemy import func
|
from sqlalchemy import func
|
||||||
|
|
||||||
base = self.last_sep_id(user_id)
|
base = self.last_sep_id(user_id, conversation_id)
|
||||||
return self.session.scalar(
|
return self.session.scalar(
|
||||||
select(func.count()).where(
|
select(func.count()).where(
|
||||||
Message.user_id == user_id,
|
Message.user_id == user_id,
|
||||||
|
Message.conversation_id == conversation_id,
|
||||||
Message.id > base,
|
Message.id > base,
|
||||||
Message.role.in_(("user", "assistant")),
|
Message.role.in_(("user", "assistant")),
|
||||||
)
|
)
|
||||||
) or 0
|
) or 0
|
||||||
|
|
||||||
def list_since_sep(self, user_id: int, limit: int = 100) -> list[Message]:
|
def list_since_sep(self, user_id: int, conversation_id: int = 0, limit: int = 100) -> list[Message]:
|
||||||
"""最近分界之后的全部消息(AI 上下文只取这段;历史上翻仍可复盘)。"""
|
"""最近分界之后的全部消息(AI 上下文只取这段;历史上翻仍可复盘)。"""
|
||||||
base = self.last_sep_id(user_id)
|
base = self.last_sep_id(user_id, conversation_id)
|
||||||
stmt = (
|
stmt = (
|
||||||
select(Message)
|
select(Message)
|
||||||
.where(Message.user_id == user_id, Message.id > base)
|
.where(
|
||||||
|
Message.user_id == user_id,
|
||||||
|
Message.conversation_id == conversation_id,
|
||||||
|
Message.id > base,
|
||||||
|
)
|
||||||
.order_by(Message.id.asc())
|
.order_by(Message.id.asc())
|
||||||
.limit(limit)
|
.limit(limit)
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
# M4 计划:多会话(学科窗口)+ 继承 + 提示词围栏
|
||||||
|
|
||||||
|
> 2026-10-14 拟定。用户核心哲学:**核心功能 = 普通 AI 工具**(会话/侧边栏/自由对话),
|
||||||
|
> 学习体验与限制全部通过**提示词注入**(不系统内置);分界符方案保留(体验流畅 + 控制 AI 负担)。
|
||||||
|
|
||||||
|
## 设计:两级维度划分
|
||||||
|
1. **会话(学科窗口)**:侧边栏列表;每个会话 = 一个学科(course 决定提示词/LaTeX/题库路由)。
|
||||||
|
新会话可**继承**源会话(course + 接续上下文),无需重新调教、从原进度继续。
|
||||||
|
2. **分界符(同会话内)**:P7.1 机制保留,按**会话维度**生效(轮数 ≥40 插分界,AI 上下文只取最近分界后)。
|
||||||
|
|
||||||
|
## 任务分解
|
||||||
|
### M4.1 会话骨架(先做)
|
||||||
|
- `conversations` 表(user_id/course/title/inherit_from/时间);messages 加 `conversation_id` 列(SQLite ALTER 幂等迁移)
|
||||||
|
- API:GET /api/conversations(列表含活跃度)、POST /api/conversations(建新会话,可 inherit_from)、GET /api/conversations/{id}/messages
|
||||||
|
- chat 带 conversation_id:历史/分界/入库按会话;公告 conversation_id=0(全局流,所有会话可见)
|
||||||
|
### M4.2 前端侧边栏
|
||||||
|
- 左侧会话栏:列表(学科徽标 + 标题 + 最后活跃)、新建(选学科 + 继承源会话下拉)、切换加载历史
|
||||||
|
- 分界符渲染保留(P7.1 已上线)
|
||||||
|
### M4.3 继承增强
|
||||||
|
- 新会话继承 = course 复制 + 源会话"接续摘要"注入 system(分界前折叠摘要 + 最近分界后尾部消息),从原进度继续
|
||||||
|
### M4.4 学习路径提示词注入(不内置)
|
||||||
|
- 潘洪波(洪水的洪)《小学 C++/小学信奥》教程结构、朋友题单(Hydro 数据接入待评估)→ 作为学科提示词/题库路由配置(course.problem_route + prompt 扩展),不写死系统
|
||||||
|
- 学生发散自由 + 提示词"围栏"(安全探索边界)
|
||||||
|
|
||||||
|
## 执行顺序
|
||||||
|
M4.1 → M4.2 → M4.3(继承)→ M4.4(题单接入,先调研朋友 Hydro 数据形态)
|
||||||
|
|
||||||
|
## 待调研
|
||||||
|
- 朋友小学信息化题单:Hydro 服务器地址/API/数据格式(连接方式评估)
|
||||||
|
- 潘洪波教程结构 → 学习路径提示词化
|
||||||
在新工单中引用
屏蔽一个用户