rasa人机对话脚本生成

models.py 7.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. import logging
  2. import json
  3. from datetime import datetime
  4. from sqlalchemy import Column, Integer, String, Text, DateTime, ForeignKey, Boolean, UniqueConstraint, Index
  5. from sqlalchemy.ext.declarative import declarative_base
  6. from sqlalchemy.orm import relationship
  7. from sqlalchemy.exc import SQLAlchemyError
  8. # 初始化日志
  9. logger = logging.getLogger(__name__)
  10. Base = declarative_base()
  11. class Intent(Base):
  12. """意图表模型"""
  13. __tablename__ = 'intent'
  14. id = Column(Integer, primary_key=True, autoincrement=True, comment='意图ID')
  15. name = Column(String(100), nullable=False, unique=True, comment='意图名称')
  16. description = Column(String(500), comment='意图描述')
  17. created_time = Column(DateTime, default=datetime.now, nullable=False, comment='创建时间')
  18. updated_time = Column(DateTime, default=datetime.now, onupdate=datetime.now, nullable=False, comment='更新时间')
  19. examples = relationship('IntentExample', backref='intent', cascade='all, delete-orphan')
  20. __table_args__ = {'comment': '存储Rasa意图定义'}
  21. class IntentExample(Base):
  22. """意图样本表模型"""
  23. __tablename__ = 'intent_example'
  24. id = Column(Integer, primary_key=True, autoincrement=True, comment='样本ID')
  25. intent_id = Column(Integer, ForeignKey('intent.id'), nullable=False, comment='意图ID')
  26. text = Column(String(1000), nullable=False, comment='样本文本')
  27. created_time = Column(DateTime, default=datetime.now, nullable=False, comment='创建时间')
  28. updated_time = Column(DateTime, default=datetime.now, onupdate=datetime.now, nullable=False, comment='更新时间')
  29. __table_args__ = {'comment': '存储意图对应的用户输入示例'}
  30. class Story(Base):
  31. """故事表模型"""
  32. __tablename__ = 'story'
  33. id = Column(Integer, primary_key=True, autoincrement=True, comment='故事ID')
  34. name = Column(String(200), nullable=False, unique=True, comment='故事名称')
  35. description = Column(String(500), comment='故事描述')
  36. created_time = Column(DateTime, default=datetime.now, nullable=False, comment='创建时间')
  37. updated_time = Column(DateTime, default=datetime.now, onupdate=datetime.now, nullable=False, comment='更新时间')
  38. # 关联关系
  39. steps = relationship('StoryStep', backref='story', cascade='all, delete-orphan')
  40. __table_args__ = {'comment': '存储Rasa对话流程定义'}
  41. class StoryStep(Base):
  42. """故事步骤表模型"""
  43. __tablename__ = 'story_step'
  44. id = Column(Integer, primary_key=True, autoincrement=True, comment='步骤ID')
  45. story_id = Column(Integer, ForeignKey('story.id'), nullable=False, comment='故事ID')
  46. step_order = Column(Integer, nullable=False, comment='步骤顺序')
  47. step_type = Column(String(20), nullable=False, comment='步骤类型')
  48. content = Column(Text, nullable=False, comment='步骤内容(JSON)')
  49. created_time = Column(DateTime, default=datetime.now, nullable=False, comment='创建时间')
  50. updated_time = Column(DateTime, default=datetime.now, onupdate=datetime.now, nullable=False, comment='更新时间')
  51. @property
  52. def content_dict(self):
  53. """将JSON字符串转换为字典"""
  54. try:
  55. if not self.content:
  56. return {}
  57. return json.loads(self.content)
  58. except json.JSONDecodeError as e:
  59. logger.error(f"解析StoryStep内容失败: {str(e)}, 内容: {self.content}")
  60. return {}
  61. __table_args__ = {'comment': '存储故事的具体步骤'}
  62. class CustomAction(Base):
  63. """自定义动作表模型"""
  64. __tablename__ = 'custom_action'
  65. id = Column(Integer, primary_key=True, autoincrement=True, comment='动作ID')
  66. name = Column(String(100), nullable=False, unique=True, comment='动作名称')
  67. description = Column(String(500), comment='动作描述')
  68. http_method = Column(String(10), nullable=False, comment='HTTP方法')
  69. api_url = Column(String(500), nullable=False, comment='API地址')
  70. token = Column(String(500), comment='鉴权Token')
  71. headers = Column(Text, comment='请求头(JSON)')
  72. request_body = Column(Text, comment='请求体(JSON)')
  73. response_mapping = Column(Text, comment='响应映射规则(JSON)')
  74. created_time = Column(DateTime, default=datetime.now, nullable=False, comment='创建时间')
  75. updated_time = Column(DateTime, default=datetime.now, onupdate=datetime.now, nullable=False, comment='更新时间')
  76. @property
  77. def headers_dict(self):
  78. """将请求头JSON转换为字典"""
  79. try:
  80. if not self.headers:
  81. return {}
  82. return json.loads(self.headers)
  83. except json.JSONDecodeError as e:
  84. logger.error(f"解析CustomAction请求头失败: {str(e)}, 内容: {self.headers}")
  85. return {}
  86. @property
  87. def request_body_dict(self):
  88. """将请求体JSON转换为字典"""
  89. try:
  90. if not self.request_body:
  91. return {}
  92. return json.loads(self.request_body)
  93. except json.JSONDecodeError as e:
  94. logger.error(f"解析CustomAction请求体失败: {str(e)}, 内容: {self.request_body}")
  95. return {}
  96. @property
  97. def response_mapping_dict(self):
  98. """将响应映射JSON转换为字典"""
  99. try:
  100. if not self.response_mapping:
  101. return {}
  102. return json.loads(self.response_mapping)
  103. except json.JSONDecodeError as e:
  104. logger.error(f"解析CustomAction响应映射失败: {str(e)}, 内容: {self.response_mapping}")
  105. return {}
  106. __table_args__ = {'comment': '存储对接第三方API的自定义动作配置'}
  107. class SystemConfig(Base):
  108. """系统配置表模型"""
  109. __tablename__ = 'system_config'
  110. id = Column(Integer, primary_key=True, autoincrement=True, comment='配置ID')
  111. config_key = Column(String(100), nullable=False, unique=True, comment='配置键')
  112. config_value = Column(String(500), nullable=False, comment='配置值')
  113. description = Column(String(500), comment='配置描述')
  114. updated_by = Column(String(100), comment='更新人')
  115. updated_time = Column(DateTime, default=datetime.now, onupdate=datetime.now, nullable=False, comment='更新时间')
  116. __table_args__ = {'comment': '存储系统配置信息'}
  117. @classmethod
  118. def get_value(cls, session, key, default=None):
  119. """
  120. 获取配置值
  121. Args:
  122. session: 数据库会话
  123. key: 配置键
  124. default: 默认值
  125. Returns:
  126. 配置值或默认值
  127. """
  128. try:
  129. config = session.query(cls).filter_by(config_key=key).first()
  130. return config.config_value if config else default
  131. except SQLAlchemyError as e:
  132. logger.error(f"获取系统配置 {key} 失败: {str(e)}")
  133. return default
  134. @classmethod
  135. def set_value(cls, session, key, value, user=None):
  136. """
  137. 设置配置值
  138. Args:
  139. session: 数据库会话
  140. key: 配置键
  141. value: 配置值
  142. user: 操作人
  143. Returns:
  144. 配置对象
  145. """
  146. try:
  147. config = session.query(cls).filter_by(config_key=key).first()
  148. if config:
  149. config.config_value = value
  150. config.updated_by = user
  151. else:
  152. config = cls(
  153. config_key=key,
  154. config_value=value,
  155. updated_by=user
  156. )
  157. session.add(config)
  158. session.commit()
  159. return config
  160. except SQLAlchemyError as e:
  161. session.rollback()
  162. logger.error(f"设置系统配置 {key} 失败: {str(e)}")
  163. raise Exception(f"设置系统配置失败: {str(e)}")