session_model.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. import json
  2. import pytz
  3. from datetime import datetime
  4. from sqlalchemy.orm import Session
  5. from typing import Optional, Type
  6. from pydantic import BaseModel
  7. from sqlalchemy import Column, String, Integer, DateTime, JSON, TEXT, Index
  8. from Log import logger
  9. from app.models.agent_model import AgentType
  10. from app.models.base_model import Base
  11. def current_time():
  12. tz = pytz.timezone('Asia/Shanghai')
  13. return datetime.now(tz)
  14. class ChatSessionModel(Base):
  15. __tablename__ = "chat_sessions"
  16. # __table_args__ = (
  17. # Index('idx_username', 'username'),
  18. # )
  19. id = Column(String(36), primary_key=True)
  20. name = Column(String(255))
  21. agent_id = Column(String(255))
  22. agent_type = Column(Integer) # 目前只存basic的,ragflow和bisheng的调接口获取
  23. create_date = Column(DateTime, default=current_time) # 创建时间,默认值为当前时区时间
  24. update_date = Column(DateTime, default=current_time, onupdate=current_time, index=True) # 更新时间,默认值为当前时区时间,更新时自动更新
  25. tenant_id = Column(Integer, index=True) # 创建人
  26. message = Column(TEXT)
  27. reference = Column(TEXT)
  28. conversation_id = Column(String(36), index=True)
  29. event_type = Column(String(16))
  30. # to_dict 方法
  31. def to_dict(self):
  32. return {
  33. 'id': self.id,
  34. 'name': self.name,
  35. 'agent_type': self.agent_type,
  36. 'agent_id': self.agent_id,
  37. 'create_date': self.create_date.strftime("%Y-%m-%d %H:%M:%S"),
  38. 'update_date': self.update_date.strftime("%Y-%m-%d %H:%M:%S"),
  39. }
  40. def log_to_json(self):
  41. return {
  42. 'id': self.id,
  43. 'name': self.name,
  44. 'agent_type': self.agent_type,
  45. 'agent_id': self.agent_id,
  46. 'create_date': self.create_date.strftime("%Y-%m-%d %H:%M:%S"),
  47. 'update_date': self.update_date.strftime("%Y-%m-%d %H:%M:%S"),
  48. 'message': json.loads(self.message)
  49. }
  50. def add_message(self, message: dict):
  51. if self.message is None:
  52. self.message = '[]'
  53. try:
  54. msg = json.loads(self.message)
  55. msg.append(message)
  56. except Exception as e:
  57. print(e)
  58. return
  59. self.message = json.dumps(msg)
  60. class ChatDialogData(BaseModel):
  61. sessionId: Optional[str] = ""
  62. question: str
  63. chatId: str
  64. class ChatSessionDao:
  65. def __init__(self, db: Session):
  66. self.db = db
  67. async def create_session(self, session_id: str, **kwargs) -> ChatSessionModel:
  68. new_session = ChatSessionModel(
  69. id=session_id,
  70. create_date=current_time(),
  71. update_date=current_time(),
  72. **kwargs
  73. )
  74. new_session.message = json.dumps([new_session.message])
  75. self.db.add(new_session)
  76. self.db.commit()
  77. self.db.refresh(new_session)
  78. return new_session
  79. async def get_session_by_id(self, session_id: str) -> ChatSessionModel | None:
  80. session = self.db.query(ChatSessionModel).filter_by(id=session_id).first()
  81. return session
  82. async def update_session_by_id(self, session_id: str, session, message: dict) -> ChatSessionModel | None:
  83. if not session:
  84. session = await self.get_session_by_id(session_id)
  85. if session:
  86. try:
  87. session.add_message(message)
  88. session.update_date = current_time()
  89. self.db.commit()
  90. self.db.refresh(session)
  91. except Exception as e:
  92. logger.error(e)
  93. self.db.rollback()
  94. return session
  95. async def update_or_insert_by_id(self, session_id: str, **kwargs) -> ChatSessionModel:
  96. existing_session = await self.get_session_by_id(session_id)
  97. if existing_session:
  98. return await self.update_session_by_id(session_id, existing_session, kwargs.get("message"))
  99. existing_session = await self.create_session(session_id, **kwargs)
  100. return existing_session
  101. async def delete_session(self, session_id: str) -> None:
  102. session = await self.get_session_by_id(session_id)
  103. if session:
  104. self.db.delete(session)
  105. self.db.commit()