session_model.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  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. session_type = Column(String(16))
  31. # to_dict 方法
  32. def to_dict(self):
  33. return {
  34. 'session_id': self.id,
  35. 'name': self.name,
  36. 'agent_type': self.agent_type,
  37. 'agent_id': self.agent_id,
  38. 'event_type': self.event_type,
  39. 'session_type': self.session_type,
  40. 'create_date': self.create_date.strftime("%Y-%m-%d %H:%M:%S"),
  41. 'update_date': self.update_date.strftime("%Y-%m-%d %H:%M:%S"),
  42. }
  43. def log_to_json(self):
  44. return {
  45. 'id': self.id,
  46. 'name': self.name,
  47. 'agent_type': self.agent_type,
  48. 'agent_id': self.agent_id,
  49. 'create_date': self.create_date.strftime("%Y-%m-%d %H:%M:%S"),
  50. 'update_date': self.update_date.strftime("%Y-%m-%d %H:%M:%S"),
  51. 'message': json.loads(self.message)
  52. }
  53. def add_message(self, message: dict):
  54. if self.message is None:
  55. self.message = '[]'
  56. try:
  57. msg = json.loads(self.message)
  58. msg.append(message)
  59. except Exception as e:
  60. print(e)
  61. return
  62. self.message = json.dumps(msg)
  63. class ChatData(BaseModel):
  64. sessionId: Optional[str] = ""
  65. class Config:
  66. extra = 'allow' # 允许其他动态字段
  67. class ChatSessionDao:
  68. def __init__(self, db: Session):
  69. self.db = db
  70. async def create_session(self, session_id: str, **kwargs) -> ChatSessionModel:
  71. new_session = ChatSessionModel(
  72. id=session_id,
  73. create_date=current_time(),
  74. update_date=current_time(),
  75. **kwargs
  76. )
  77. new_session.message = json.dumps([new_session.message])
  78. self.db.add(new_session)
  79. self.db.commit()
  80. self.db.refresh(new_session)
  81. return new_session
  82. async def get_session_by_id(self, session_id: str) -> ChatSessionModel | None:
  83. session = self.db.query(ChatSessionModel).filter_by(id=session_id).first()
  84. return session
  85. async def update_session_by_id(self, session_id: str, session, message: dict, conversation_id=None) -> ChatSessionModel | None:
  86. print(message)
  87. if not session:
  88. session = await self.get_session_by_id(session_id)
  89. if session:
  90. try:
  91. if conversation_id:
  92. session.conversation_id=conversation_id
  93. session.add_message(message)
  94. session.update_date = current_time()
  95. self.db.commit()
  96. self.db.refresh(session)
  97. except Exception as e:
  98. # logger.error(e)
  99. self.db.rollback()
  100. return session
  101. async def update_or_insert_by_id(self, session_id: str, **kwargs) -> ChatSessionModel:
  102. existing_session = await self.get_session_by_id(session_id)
  103. if existing_session:
  104. return await self.update_session_by_id(session_id, existing_session, kwargs.get("message"))
  105. existing_session = await self.create_session(session_id, **kwargs)
  106. return existing_session
  107. async def delete_session(self, session_id: str) -> None:
  108. session = await self.get_session_by_id(session_id)
  109. if session:
  110. self.db.delete(session)
  111. self.db.commit()