Files
QuestionProject/ai_knowledge_base_v2/apps/backend/app/models/chat.py
Nelson 61db0aa9b8 feat: 对话摘要+段落按需读取+think标签解析修复
- chat.py: ChatSession 新增 summary/summary_up_to_message_id 字段
- rag_service.py: Prompt 支持历史摘要+最近5轮原文拼接
- model_service.py: 新增 summarize() 方法,复用已启用模型生成摘要
- chat_service.py: 集成对话历史传递,8轮后触发摘要生成
- feishu_service.py: 段落级按需读取,按标题匹配+关键词打分+top5文档

摘要策略:
- 保留最近5轮原文保证追问连续性
- 更早历史由模型压缩成摘要(<=300字)
- 摘要失败不阻断主流程

飞书读取优化:
- 每个知识库最多读5个相关文档
- 每文档提取top10相关段落
- 按原文顺序拼接,不截断

Fix: _extract_openai_answer 重命名为 _extract_gemini_answer
避免同名函数覆盖导致MiniMax模型被错误解析为Gemini响应
2026-07-08 17:49:52 +08:00

43 lines
2.2 KiB
Python

from __future__ import annotations
from datetime import datetime
from sqlalchemy import BigInteger, DateTime, ForeignKey, Integer, String, Text, func
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base, TimestampMixin
class ChatSession(Base, TimestampMixin):
__tablename__ = "sys_chat_session"
id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
user_id: Mapped[int] = mapped_column(ForeignKey("sys_user.id"), index=True, nullable=False)
title: Mapped[str] = mapped_column(String(100), nullable=False)
summary: Mapped[str | None] = mapped_column(Text, nullable=True)
summary_up_to_message_id: Mapped[int | None] = mapped_column(BigInteger, nullable=True)
message_count: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
last_message_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
is_deleted: Mapped[int] = mapped_column(default=0, nullable=False)
user: Mapped["User"] = relationship("User", back_populates="chat_sessions")
messages: Mapped[list["ChatMessage"]] = relationship("ChatMessage", back_populates="session")
class ChatMessage(Base):
__tablename__ = "sys_chat_message"
id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
session_id: Mapped[int] = mapped_column(ForeignKey("sys_chat_session.id"), index=True, nullable=False)
user_id: Mapped[int] = mapped_column(ForeignKey("sys_user.id"), index=True, nullable=False)
role: Mapped[str] = mapped_column(String(20), nullable=False)
content: Mapped[str] = mapped_column(Text, nullable=False)
message_status: Mapped[str] = mapped_column(String(20), default="FINISHED", nullable=False)
token_input: Mapped[int | None] = mapped_column(Integer, nullable=True)
token_output: Mapped[int | None] = mapped_column(Integer, nullable=True)
response_time_ms: Mapped[int | None] = mapped_column(Integer, nullable=True)
model_id: Mapped[int | None] = mapped_column(ForeignKey("sys_model.id"), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now(), nullable=False)
session: Mapped[ChatSession] = relationship("ChatSession", back_populates="messages")