fetch_agent.py 12 KB

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