fetch_agent.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. from pickle import PROTO
  2. from typing import Dict, List, Tuple
  3. from sqlalchemy import create_engine, Column, String, Integer, Text
  4. from sqlalchemy.exc import IntegrityError
  5. from sqlalchemy.orm import sessionmaker
  6. from app.config.config import settings
  7. from app.config.const import RAGFLOW, BISHENG, DIFY
  8. from app.models import DialogModel
  9. from app.models.agent_model import AgentModel
  10. from app.models.base_model import SessionLocal, Base
  11. from app.service.v2.app_register import AppRegisterDao
  12. # 创建数据库引擎和会话工厂
  13. engine_bisheng = create_engine(settings.sgb_db_url)
  14. engine_ragflow = create_engine(settings.fwr_db_url)
  15. engine_dify = create_engine(settings.dify_database_url)
  16. SessionBisheng = sessionmaker(autocommit=False, autoflush=False, bind=engine_bisheng)
  17. SessionRagflow = sessionmaker(autocommit=False, autoflush=False, bind=engine_ragflow)
  18. SessionDify = sessionmaker(autocommit=False, autoflush=False, bind=engine_dify)
  19. class Flow(Base):
  20. __tablename__ = 'flow'
  21. id = Column(String(255), primary_key=True)
  22. name = Column(String(255), nullable=False)
  23. status = Column(Integer, nullable=False)
  24. description = Column(String(255), nullable=False)
  25. user_id = Column(Integer, nullable=False)
  26. class Dialog(Base):
  27. __tablename__ = 'dialog'
  28. id = Column(String(255), primary_key=True)
  29. name = Column(String(255), nullable=False)
  30. status = Column(String(1), nullable=False)
  31. description = Column(String(255), nullable=False)
  32. tenant_id = Column(String(36), nullable=False)
  33. class DfApps(Base):
  34. __tablename__ = 'apps'
  35. id = Column(String(36), primary_key=True)
  36. name = Column(String(255), nullable=False)
  37. status = Column(String(16), nullable=False)
  38. description = Column(Text, nullable=False)
  39. tenant_id = Column(String(36), nullable=False)
  40. # 解析名字
  41. def parse_names(names_str: str) -> List[str]:
  42. return [name.strip() for name in names_str.split(',')]
  43. BISHENG_NAMES_TO_SYNC = parse_names(settings.fetch_sgb_agent)
  44. RAGFLOW_NAMES_TO_SYNC = parse_names(settings.fetch_fwr_agent)
  45. def get_data_from_bisheng(names: List[str]) -> List[Tuple]:
  46. db = SessionBisheng()
  47. try:
  48. if names:
  49. query = db.query(Flow.id, Flow.name) \
  50. .filter(Flow.status == 2, Flow.name.in_(names))
  51. else:
  52. query = db.query(Flow.id, Flow.name) \
  53. .filter(Flow.status == 2)
  54. results = query.all()
  55. print(f"Executing query: {query}")
  56. # 格式化id为UUID
  57. formatted_results = [(format_uuid(row[0]), row[1]) for row in results]
  58. return formatted_results
  59. finally:
  60. db.close()
  61. def format_uuid(uuid_str: str) -> str:
  62. # 确保输入字符串长度为32
  63. if len(uuid_str) != 32:
  64. raise ValueError("Input string must be 32 characters long")
  65. # 插入连字符
  66. formatted_uuid = f"{uuid_str[:8]}-{uuid_str[8:12]}-{uuid_str[12:16]}-{uuid_str[16:20]}-{uuid_str[20:]}"
  67. return formatted_uuid
  68. def get_data_from_ragflow(names: List[str]) -> List[Tuple]:
  69. db = SessionRagflow()
  70. try:
  71. if names:
  72. query = db.query(Dialog.id, Dialog.name) \
  73. .filter(Dialog.status == 1, Dialog.name.in_(names))
  74. else:
  75. query = db.query(Dialog.id, Dialog.name) \
  76. .filter(Dialog.status == 1)
  77. results = query.all()
  78. print(f"Executing query: {query}")
  79. return results
  80. finally:
  81. db.close()
  82. def update_ids_in_local(data: List[Tuple]):
  83. db = SessionLocal()
  84. try:
  85. for row in data:
  86. name = row[1]
  87. new_id = row[0]
  88. existing_agent = db.query(AgentModel).filter_by(name=name).first()
  89. if existing_agent:
  90. existing_agent.id = new_id
  91. db.add(existing_agent)
  92. db.commit()
  93. except IntegrityError:
  94. db.rollback()
  95. raise
  96. finally:
  97. db.close()
  98. def initialize_agents():
  99. db = SessionLocal()
  100. try:
  101. count = db.query(AgentModel).count()
  102. if count > 0:
  103. result = db.query(AgentModel).delete()
  104. db.commit() # 提交事务
  105. initial_agents = [
  106. ('80ee430a-e396-48c4-a12c-7c7cdf5eda51', 1, '报告生成', 'BISHENG', 'report'),
  107. ('basic_excel_merge', 2, '报表合并', 'BASIC', 'excelMerge'),
  108. ('bfd090d589d811efb3630242ac190006', 4, '文档智能', 'BISHENG', 'report'),
  109. ('da3451da89d911efb9490242ac190006', 3, '知识问答', 'RAGFLOW', 'knowledgeQA'),
  110. ('e96eb7a589db11ef87d20242ac190006', 5, '智能问答', 'RAGFLOW', 'chat'),
  111. ('basic_excel_talk', 6, '智能数据', 'BASIC', 'excelTalk'),
  112. ('basic_question_talk', 7, '出题组卷', 'BASIC', 'questionTalk'),
  113. ('9d75142a-66eb-4e23-b7d4-03efe4584915', 8, '小数绘图', 'DIFY', 'imageTalk'),
  114. ('basic_paper_talk', 8, '文档出卷', 'BASIC', 'paperTalk'),
  115. ('basic_report_clean', 10, '文档报告', 'DIFY', 'reportWorkflow')
  116. ]
  117. for agent in initial_agents:
  118. agent_id = format_uuid(agent[0]) if len(agent[0]) == 32 else agent[0]
  119. db.add(AgentModel(id=agent_id, sort=agent[1], name=agent[2], agent_type=agent[3], type=agent[4]))
  120. db.commit()
  121. print("Initial agents inserted successfully")
  122. except IntegrityError:
  123. db.rollback()
  124. raise
  125. finally:
  126. db.close()
  127. def sync_agents():
  128. try:
  129. bisheng_data = get_data_from_bisheng(BISHENG_NAMES_TO_SYNC)
  130. ragflow_data = get_data_from_ragflow(RAGFLOW_NAMES_TO_SYNC)
  131. update_ids_in_local(bisheng_data)
  132. update_ids_in_local(ragflow_data)
  133. print("Agents synchronized successfully")
  134. except Exception as e:
  135. print(f"Failed to sync agents: {str(e)}")
  136. def update_ids_in_local(data: List[Tuple]):
  137. db = SessionLocal()
  138. try:
  139. for row in data:
  140. name = row[1]
  141. new_id = row[0]
  142. existing_agent = db.query(AgentModel).filter_by(name=name).first()
  143. if existing_agent:
  144. existing_agent.id = new_id
  145. db.add(existing_agent)
  146. db.commit()
  147. except IntegrityError:
  148. db.rollback()
  149. raise
  150. finally:
  151. db.close()
  152. def get_data_from_bisheng_v2(names: List[str]) -> List[Dict]:
  153. db = SessionBisheng()
  154. try:
  155. if names:
  156. query = db.query(Flow.id, Flow.name, Flow.description, Flow.status, Flow.user_id) \
  157. .filter(Flow.name.in_(names), Flow.status==2)
  158. else:
  159. query = db.query(Flow.id, Flow.name, Flow.description, Flow.status, Flow.user_id).filter(Flow.status==2)
  160. results = query.all()
  161. # print(f"Executing query: {query}")
  162. # 格式化id为UUID
  163. formatted_results = [{"id":format_uuid(row[0]), "name": row[1], "description": row[2], "status": str(row[3]-1), "user_id": str(row[4])} for row in results]
  164. return formatted_results
  165. finally:
  166. db.close()
  167. def get_data_from_ragflow_v2(names: List[str]) -> List[Dict]:
  168. db = SessionRagflow()
  169. try:
  170. if names:
  171. query = db.query(Dialog.id, Dialog.name, Dialog.description, Dialog.status, Dialog.tenant_id) \
  172. .filter( Dialog.name.in_(names))
  173. else:
  174. query = db.query(Dialog.id, Dialog.name, Dialog.description, Dialog.status, Dialog.tenant_id)
  175. results = query.all()
  176. formatted_results = [
  177. {"id": format_uuid(row[0]), "name": row[1], "description": row[2], "status": str(row[3]),
  178. "user_id": str(row[4])} for row in results]
  179. return formatted_results
  180. finally:
  181. db.close()
  182. def get_data_from_dify_v2(names: List[str]) -> List[Dict]:
  183. db = SessionDify()
  184. try:
  185. if names:
  186. query = db.query(DfApps.id, DfApps.name, DfApps.description, DfApps.status, DfApps.tenant_id) \
  187. .filter( DfApps.name.in_(names))
  188. else:
  189. query = db.query(DfApps.id, DfApps.name, DfApps.description, DfApps.status, DfApps.tenant_id)
  190. results = query.all()
  191. formatted_results = [
  192. {"id": str(row[0]), "name": row[1], "description": row[2], "status": "1",
  193. "user_id": str(row[4])} for row in results]
  194. return formatted_results
  195. finally:
  196. db.close()
  197. def update_ids_in_local_v2(data: List[Dict], dialog_type:str):
  198. db = SessionLocal()
  199. agent_id_list = []
  200. print("----------------------------------------")
  201. print(data)
  202. print("*********************************************")
  203. try:
  204. for row in data:
  205. agent_id_list.append(row["id"])
  206. existing_agent = db.query(DialogModel).filter_by(id=row["id"]).first()
  207. if existing_agent:
  208. existing_agent.name = row["name"]
  209. existing_agent.description = row["description"]
  210. else:
  211. existing = DialogModel(id=row["id"], name=row["name"], description=row["description"], tenant_id=row["user_id"], dialog_type=dialog_type)
  212. db.add(existing)
  213. db.commit()
  214. for dialog in db.query(DialogModel).filter_by(dialog_type=dialog_type).all():
  215. if dialog.id not in agent_id_list:
  216. db.query(DialogModel).filter_by(id=dialog.id).delete()
  217. db.commit()
  218. except IntegrityError:
  219. db.rollback()
  220. raise
  221. finally:
  222. db.close()
  223. def get_data_from_ragflow_knowledge():
  224. ...
  225. def sync_agents_v2():
  226. db = SessionLocal()
  227. try:
  228. app_register = AppRegisterDao(db).get_apps()
  229. for app in app_register:
  230. if app["id"] == RAGFLOW:
  231. ragflow_data = get_data_from_ragflow_v2([])
  232. update_ids_in_local_v2(ragflow_data, "1")
  233. elif app["id"] == BISHENG:
  234. bisheng_data = get_data_from_bisheng_v2([])
  235. update_ids_in_local_v2(bisheng_data, "2")
  236. elif app["id"] == DIFY:
  237. dify_data = get_data_from_dify_v2([])
  238. update_ids_in_local_v2(dify_data, "4")
  239. print("Agents synchronized successfully")
  240. except Exception as e:
  241. print(f"Failed to sync agents: {str(e)}")
  242. def sync_knowledge():
  243. db = SessionLocal()
  244. try:
  245. app_register = AppRegisterDao(db).get_apps()
  246. for app in app_register:
  247. if app["id"] == RAGFLOW:
  248. ragflow_data = get_data_from_ragflow_knowledge([])
  249. update_ids_in_local_v2(ragflow_data, "1")
  250. # elif app["id"] == BISHENG:
  251. # bisheng_data = get_data_from_bisheng_v2([])
  252. # update_ids_in_local_v2(bisheng_data, "2")
  253. # elif app["id"] == DIFY:
  254. # dify_data = get_data_from_dify_v2([])
  255. # update_ids_in_local_v2(dify_data, "4")
  256. print("Agents synchronized successfully")
  257. except Exception as e:
  258. print(f"Failed to sync agents: {str(e)}")
  259. if __name__ == "__main__":
  260. a = get_data_from_dify_v2([])
  261. print(a)