session.py 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. import json
  2. from typing import Type
  3. from sqlalchemy.orm import Session
  4. from Log import logger
  5. from app.models import AgentType, current_time
  6. from app.models.session_model import SessionModel
  7. class SessionService:
  8. def __init__(self, db: Session):
  9. self.db = db
  10. def create_session(self, session_id: str, name: str, agent_id: str, agent_type: AgentType, user_id: int) -> Type[
  11. SessionModel] | SessionModel:
  12. """
  13. 创建一个新的会话记录。
  14. 参数:
  15. session_id (str): 会话ID。
  16. name (str): 会话名称。
  17. agent_id (str): 代理ID。
  18. agent_type (AgentType): 代理类型。
  19. 返回:
  20. SessionModel: 新创建的会话模型实例,如果会话ID已存在则返回None。
  21. """
  22. existing_session = self.get_session_by_id(session_id)
  23. if existing_session:
  24. existing_session.add_message({"role": "user", "content": name})
  25. existing_session.update_date = current_time()
  26. self.db.commit()
  27. self.db.refresh(existing_session)
  28. return existing_session
  29. new_session = SessionModel(
  30. id=session_id,
  31. name=name[0:50],
  32. agent_id=agent_id,
  33. agent_type=agent_type,
  34. tenant_id=user_id,
  35. message=json.dumps([{"role": "user", "content": name}])
  36. )
  37. self.db.add(new_session)
  38. self.db.commit()
  39. self.db.refresh(new_session)
  40. return new_session
  41. def get_session_by_id(self, session_id: str) -> Type[SessionModel] | None:
  42. """
  43. 根据会话ID获取会话记录。
  44. 参数:
  45. session_id (str): 会话ID。
  46. 返回:
  47. SessionModel: 查找到的会话模型实例,如果未找到则返回None。
  48. """
  49. session = self.db.query(SessionModel).filter_by(id=session_id).first()
  50. if session and session.message is None:
  51. session.message = '[]'
  52. return session
  53. def update_session(self, session_id: str, **kwargs) -> Type[SessionModel] | None:
  54. """
  55. 更新会话记录。
  56. 参数:
  57. session_id (str): 会话ID。
  58. kwargs: 需要更新的字段及其值。
  59. 返回:
  60. SessionModel: 更新后的会话模型实例。
  61. """
  62. logger.error("更新数据---------------------------")
  63. self.db.commit()
  64. session = self.get_session_by_id(session_id)
  65. if session:
  66. if "message" in kwargs:
  67. session.add_message(kwargs["message"])
  68. # 替换其他字段
  69. for key, value in kwargs.items():
  70. if key != "message":
  71. setattr(session, key, value)
  72. session.update_date = current_time()
  73. try:
  74. self.db.commit()
  75. self.db.refresh(session)
  76. except Exception as e:
  77. self.db.rollback()
  78. return session
  79. def delete_session(self, session_id: str) -> None:
  80. """
  81. 删除会话记录。
  82. 参数:
  83. session_id (str): 会话ID。
  84. """
  85. session = self.get_session_by_id(session_id)
  86. if session:
  87. self.db.delete(session)
  88. self.db.commit()