1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
| from datetime import datetime from pathlib import Path from typing import Literal, Optional
from sqlalchemy import ( CheckConstraint, DateTime, ForeignKey, String, Text, create_engine, event, func, select, ) from sqlalchemy.orm import ( DeclarativeBase, Mapped, Session, mapped_column, relationship, )
BASE_DIR = Path(__file__).resolve().parent DB_PATH = BASE_DIR / "chat.db" DATABASE_URL = f"sqlite:///{DB_PATH}"
engine = create_engine( DATABASE_URL, echo=False, connect_args={"check_same_thread": False}, )
@event.listens_for(engine, "connect") def enable_sqlite_foreign_keys(dbapi_connection, connection_record): """ SQLite 默认不启用外键约束。
如果不打开 PRAGMA foreign_keys=ON, ForeignKey(..., ondelete="CASCADE") 在 SQLite 中可能不会真正生效。 """ cursor = dbapi_connection.cursor() cursor.execute("PRAGMA foreign_keys=ON") cursor.close()
class Base(DeclarativeBase): """SQLAlchemy ORM 基类。"""
pass
class ConversationORM(Base): """ 会话表 ORM 模型。
conversation_id 直接作为主键。 每条记录代表一个独立的聊天会话。 """
__tablename__ = "conversations"
conversation_id: Mapped[str] = mapped_column( String(100), primary_key=True, nullable=False, )
title: Mapped[Optional[str]] = mapped_column( String(200), nullable=True, )
created_at: Mapped[datetime] = mapped_column( DateTime, server_default=func.now(), nullable=False, )
updated_at: Mapped[datetime] = mapped_column( DateTime, server_default=func.now(), onupdate=func.now(), nullable=False, )
messages: Mapped[list["ChatMessageORM"]] = relationship( back_populates="conversation", cascade="all, delete-orphan", passive_deletes=True, order_by="ChatMessageORM.id", )
class ChatMessageORM(Base): """ 聊天消息表 ORM 模型。
每条消息属于一个会话。 """
__tablename__ = "chat_messages"
__table_args__ = ( CheckConstraint( "role IN ('system', 'user', 'assistant')", name="check_chat_message_role", ), )
id: Mapped[int] = mapped_column( primary_key=True, autoincrement=True, )
conversation_id: Mapped[str] = mapped_column( String(100), ForeignKey("conversations.conversation_id", ondelete="CASCADE"), index=True, nullable=False, )
role: Mapped[str] = mapped_column( String(20), nullable=False, )
content: Mapped[str] = mapped_column( Text, nullable=False, )
created_at: Mapped[datetime] = mapped_column( DateTime, server_default=func.now(), nullable=False, )
conversation: Mapped["ConversationORM"] = relationship( back_populates="messages", )
def conversation_to_dict(conversation: ConversationORM) -> dict: """ 将 ConversationORM 转成普通 dict。
避免 Session 关闭后返回 ORM 对象导致 DetachedInstanceError。 """ return { "conversation_id": conversation.conversation_id, "title": conversation.title, "created_at": conversation.created_at, "updated_at": conversation.updated_at, }
def message_to_dict(message: ChatMessageORM) -> dict: """ 将 ChatMessageORM 转成普通 dict。 """ return { "id": message.id, "conversation_id": message.conversation_id, "role": message.role, "content": message.content, "created_at": message.created_at, }
def init_db() -> None: """ 初始化数据库。
如果 chat.db 不存在,会自动创建。 如果 conversations / chat_messages 表不存在,也会自动创建。 """ Base.metadata.create_all(bind=engine)
def create_session() -> Session: """ 创建一个数据库 Session。
用法: with create_session() as session: ... """ return Session(engine)
def create_conversation( conversation_id: str, title: Optional[str] = None, ) -> dict: """ 创建一个新会话。
如果 conversation_id 已存在,会抛出 IntegrityError。 """ with create_session() as session: conversation = ConversationORM( conversation_id=conversation_id, title=title, ) session.add(conversation) session.commit() session.refresh(conversation)
return conversation_to_dict(conversation)
def get_conversation(conversation_id: str) -> Optional[dict]: """ 根据 conversation_id 获取会话。
如果不存在,返回 None。 """ with create_session() as session: stmt = select(ConversationORM).where( ConversationORM.conversation_id == conversation_id ) conversation = session.scalar(stmt)
if conversation is None: return None
return conversation_to_dict(conversation)
def get_or_create_conversation( conversation_id: str, title: Optional[str] = None, ) -> dict: """ 获取已有会话,不存在则自动创建。
适合首次发消息时自动建会话的场景。 """ with create_session() as session: stmt = select(ConversationORM).where( ConversationORM.conversation_id == conversation_id ) conversation = session.scalar(stmt)
if conversation is None: conversation = ConversationORM( conversation_id=conversation_id, title=title, ) session.add(conversation) session.commit() session.refresh(conversation)
return conversation_to_dict(conversation)
def update_conversation_title( conversation_id: str, title: str, ) -> Optional[dict]: """ 更新会话标题。
如果会话不存在,返回 None。 """ with create_session() as session: stmt = select(ConversationORM).where( ConversationORM.conversation_id == conversation_id ) conversation = session.scalar(stmt)
if conversation is None: return None
conversation.title = title session.commit() session.refresh(conversation)
return conversation_to_dict(conversation)
def list_conversations(limit: int = 50) -> list[dict]: """ 列出所有会话,按最近更新时间倒序。 """ with create_session() as session: stmt = ( select(ConversationORM) .order_by(ConversationORM.updated_at.desc()) .limit(limit) ) conversations = session.scalars(stmt).all()
return [ conversation_to_dict(conversation) for conversation in conversations ]
def delete_conversation(conversation_id: str) -> bool: """ 删除一个会话及其所有消息。
返回: True: 删除成功 False: 会话不存在 """ with create_session() as session: stmt = select(ConversationORM).where( ConversationORM.conversation_id == conversation_id ) conversation = session.scalar(stmt)
if conversation is None: return False
session.delete(conversation) session.commit()
return True
def save_message( conversation_id: str, role: Literal["system", "user", "assistant"], content: str, auto_create_conversation: bool = True, ) -> dict: """ 保存一条聊天消息。
参数: conversation_id: 会话 ID。
role: 消息角色,只允许 system / user / assistant。
content: 消息内容。
auto_create_conversation: 如果会话不存在,是否自动创建。 """ with create_session() as session: stmt = select(ConversationORM).where( ConversationORM.conversation_id == conversation_id ) conversation = session.scalar(stmt)
if conversation is None: if not auto_create_conversation: raise ValueError(f"会话 {conversation_id} 不存在")
conversation = ConversationORM( conversation_id=conversation_id, ) session.add(conversation) session.flush()
message = ChatMessageORM( conversation_id=conversation_id, role=role, content=content, ) session.add(message)
conversation.updated_at = func.now()
session.commit() session.refresh(message)
return message_to_dict(message)
def get_history( conversation_id: str, limit: int = 20, ) -> list[dict]: """ 获取某个会话最近的聊天历史。
返回格式兼容 OpenAI / LangChain messages:
[ {"role": "user", "content": "你好"}, {"role": "assistant", "content": "你好,有什么可以帮你?"} ] """ with create_session() as session: stmt = ( select(ChatMessageORM) .where(ChatMessageORM.conversation_id == conversation_id) .order_by(ChatMessageORM.id.desc()) .limit(limit) ) messages = session.scalars(stmt).all()
messages = list(reversed(messages))
return [ { "role": message.role, "content": message.content, } for message in messages ]
def get_messages( conversation_id: str, limit: int = 20, ) -> list[dict]: """ 获取某个会话最近的完整消息列表。
和 get_history 不同,这个函数会返回 message_id、created_at 等信息。 """ with create_session() as session: stmt = ( select(ChatMessageORM) .where(ChatMessageORM.conversation_id == conversation_id) .order_by(ChatMessageORM.id.desc()) .limit(limit) ) messages = session.scalars(stmt).all()
messages = list(reversed(messages))
return [ message_to_dict(message) for message in messages ]
def clear_messages(conversation_id: str) -> int: """ 清空某个会话下的所有消息,但不删除会话本身。
返回删除的消息数量。 """ with create_session() as session: stmt = select(ChatMessageORM).where( ChatMessageORM.conversation_id == conversation_id ) messages = session.scalars(stmt).all()
count = len(messages)
for message in messages: session.delete(message)
conversation_stmt = select(ConversationORM).where( ConversationORM.conversation_id == conversation_id ) conversation = session.scalar(conversation_stmt) if conversation is not None: conversation.updated_at = func.now()
session.commit()
return count
|