fetch_agent.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. import json
  2. import os
  3. from pickle import PROTO
  4. from typing import Dict, List, Tuple
  5. from sqlalchemy import create_engine, Column, String, Integer, Text
  6. from sqlalchemy.exc import IntegrityError
  7. from sqlalchemy.orm import sessionmaker, Session
  8. from app.config.config import settings
  9. from app.config.const import RAGFLOW, BISHENG, DIFY, ENV_CONF_PATH
  10. from app.models import KnowledgeModel
  11. from app.models.dialog_model import DialogModel
  12. from app.models.user_model import UserAppModel
  13. from app.models.agent_model import AgentModel
  14. from app.models.base_model import SessionLocal, Base
  15. from app.models.resource_model import ResourceModel, ResourceTypeModel
  16. from app.service.v2.app_register import AppRegisterDao
  17. # 创建数据库引擎和会话工厂
  18. engine_bisheng = create_engine(settings.sgb_db_url)
  19. engine_ragflow = create_engine(settings.fwr_db_url)
  20. engine_dify = create_engine(settings.dify_database_url)
  21. SessionBisheng = sessionmaker(autocommit=False, autoflush=False, bind=engine_bisheng)
  22. SessionRagflow = sessionmaker(autocommit=False, autoflush=False, bind=engine_ragflow)
  23. SessionDify = sessionmaker(autocommit=False, autoflush=False, bind=engine_dify)
  24. class Flow(Base):
  25. __tablename__ = 'flow'
  26. id = Column(String(255), primary_key=True)
  27. name = Column(String(255), nullable=False)
  28. status = Column(Integer, nullable=False)
  29. description = Column(String(255), nullable=False)
  30. user_id = Column(Integer, nullable=False)
  31. class Dialog(Base):
  32. __tablename__ = 'dialog'
  33. id = Column(String(255), primary_key=True)
  34. name = Column(String(255), nullable=False)
  35. status = Column(String(1), nullable=False)
  36. description = Column(String(255), nullable=False)
  37. tenant_id = Column(String(36), nullable=False)
  38. class DfApps(Base):
  39. __tablename__ = 'apps'
  40. id = Column(String(36), primary_key=True)
  41. name = Column(String(255), nullable=False)
  42. status = Column(String(16), nullable=False)
  43. description = Column(Text, nullable=False)
  44. tenant_id = Column(String(36), nullable=False)
  45. mode = Column(String(36), nullable=False)
  46. class RgKnowledge(Base):
  47. __tablename__ = 'knowledgebase'
  48. id = Column(String(36), primary_key=True) # id
  49. name = Column(String(128)) # 名称
  50. permission = Column(String(32), default="me")
  51. tenant_id = Column(String(32)) # 创建人id
  52. description = Column(Text) # 说明
  53. status = Column(String(1)) # 状态
  54. doc_num = Column(Integer) # 文档
  55. class RgUserTenant(Base):
  56. __tablename__ = 'user_tenant'
  57. id = Column(String(36), primary_key=True) # id
  58. tenant_id = Column(String(32)) # 名称
  59. user_id = Column(String(32))
  60. role = Column(String(32)) # 创建人id
  61. # 解析名字
  62. def parse_names(names_str: str) -> List[str]:
  63. return [name.strip() for name in names_str.split(',')]
  64. BISHENG_NAMES_TO_SYNC = parse_names(settings.fetch_sgb_agent)
  65. RAGFLOW_NAMES_TO_SYNC = parse_names(settings.fetch_fwr_agent)
  66. def get_data_from_bisheng(names: List[str]) -> List[Tuple]:
  67. db = SessionBisheng()
  68. try:
  69. if names:
  70. query = db.query(Flow.id, Flow.name) \
  71. .filter(Flow.status == 2, Flow.name.in_(names))
  72. else:
  73. query = db.query(Flow.id, Flow.name) \
  74. .filter(Flow.status == 2)
  75. results = query.all()
  76. print(f"Executing query: {query}")
  77. # 格式化id为UUID
  78. formatted_results = [(format_uuid(row[0]), row[1]) for row in results]
  79. return formatted_results
  80. finally:
  81. db.close()
  82. def format_uuid(uuid_str: str) -> str:
  83. # 确保输入字符串长度为32
  84. if len(uuid_str) != 32:
  85. raise ValueError("Input string must be 32 characters long")
  86. # 插入连字符
  87. formatted_uuid = f"{uuid_str[:8]}-{uuid_str[8:12]}-{uuid_str[12:16]}-{uuid_str[16:20]}-{uuid_str[20:]}"
  88. return formatted_uuid
  89. def get_data_from_ragflow(names: List[str]) -> List[Tuple]:
  90. db = SessionRagflow()
  91. try:
  92. if names:
  93. query = db.query(Dialog.id, Dialog.name) \
  94. .filter(Dialog.status == 1, Dialog.name.in_(names))
  95. else:
  96. query = db.query(Dialog.id, Dialog.name) \
  97. .filter(Dialog.status == 1)
  98. results = query.all()
  99. print(f"Executing query: {query}")
  100. return results
  101. finally:
  102. db.close()
  103. def update_ids_in_local(data: List[Tuple]):
  104. db = SessionLocal()
  105. try:
  106. for row in data:
  107. name = row[1]
  108. new_id = row[0]
  109. existing_agent = db.query(AgentModel).filter_by(name=name).first()
  110. if existing_agent:
  111. existing_agent.id = new_id
  112. db.add(existing_agent)
  113. db.commit()
  114. except IntegrityError:
  115. db.rollback()
  116. raise
  117. finally:
  118. db.close()
  119. def initialize_agents():
  120. db = SessionLocal()
  121. try:
  122. count = db.query(AgentModel).count()
  123. if count > 0:
  124. result = db.query(AgentModel).delete()
  125. db.commit() # 提交事务
  126. initial_agents = [
  127. # ('80ee430a-e396-48c4-a12c-7c7cdf5eda51', 1, '报告生成', 'DIFY', 'report'),
  128. ('basic_excel_merge', 2, '报表合并', 'BASIC', 'excelMerge'),
  129. ('7638f00638a24c21a68ec6c49b304a35', 4, '文档智能', 'DIFY', 'documentIa'),
  130. ('da3451da89d911efb9490242ac190006', 3, '知识问答', 'RAGFLOW', 'knowledgeQA'),
  131. ('e96eb7a589db11ef87d20242ac190006', 5, '智能问答', 'RAGFLOW', 'chat'),
  132. ('basic_excel_talk', 6, '智能数据', 'BASIC', 'excelTalk'),
  133. ('basic_question_talk', 7, '出题组卷', 'BASIC', 'questionTalk'),
  134. ('9d75142a-66eb-4e23-b7d4-03efe4584915', 8, '小数绘图', 'DIFY', 'imageTalk'),
  135. ('2f6ddf93-7ba6-4b2d-b991-d96421404600', 9, '文档出卷', 'DIFY', 'paperTalk'),
  136. ('basic_report_clean', 10, '文档报告', 'DIFY', 'reportWorkflow')
  137. ]
  138. for agent in initial_agents:
  139. agent_id = format_uuid(agent[0]) if len(agent[0]) == 32 else agent[0]
  140. db.add(AgentModel(id=agent_id, sort=agent[1], name=agent[2], agent_type=agent[3], type=agent[4]))
  141. db.commit()
  142. print("Initial agents inserted successfully")
  143. except IntegrityError:
  144. db.rollback()
  145. raise
  146. finally:
  147. db.close()
  148. def sync_agents():
  149. try:
  150. # bisheng_data = get_data_from_bisheng(BISHENG_NAMES_TO_SYNC)
  151. ragflow_data = get_data_from_ragflow(RAGFLOW_NAMES_TO_SYNC)
  152. # update_ids_in_local(bisheng_data)
  153. update_ids_in_local(ragflow_data)
  154. print("Agents synchronized successfully")
  155. except Exception as e:
  156. print(f"Failed to sync agents: {str(e)}")
  157. def update_ids_in_local(data: List[Tuple]):
  158. db = SessionLocal()
  159. try:
  160. for row in data:
  161. name = row[1]
  162. new_id = row[0]
  163. existing_agent = db.query(AgentModel).filter_by(name=name).first()
  164. if existing_agent:
  165. existing_agent.id = new_id
  166. db.add(existing_agent)
  167. db.commit()
  168. except IntegrityError:
  169. db.rollback()
  170. raise
  171. finally:
  172. db.close()
  173. def get_rag_user_id(db, tenant_id, app_type):
  174. user = db.query(UserAppModel).filter(UserAppModel.app_type == app_type, UserAppModel.app_id == tenant_id).first()
  175. if user:
  176. return user.user_id
  177. return tenant_id
  178. def get_data_from_bisheng_v2(names: List[str]) -> List[Dict]:
  179. db = SessionBisheng()
  180. try:
  181. if names:
  182. query = db.query(Flow.id, Flow.name, Flow.description, Flow.status, Flow.user_id) \
  183. .filter(Flow.name.in_(names), Flow.status == "1")
  184. else:
  185. query = db.query(Flow.id, Flow.name, Flow.description, Flow.status, Flow.user_id).filter(Flow.status == "1")
  186. results = query.all()
  187. # print(f"Executing query: {query}")
  188. # 格式化id为UUID
  189. formatted_results = [
  190. {"id": row[0], "name": row[1], "description": row[2], "status": row[3], "user_id": str(row[4]),
  191. "mode": "agent-dialog"} for row in results]
  192. return formatted_results
  193. finally:
  194. db.close()
  195. def get_data_from_ragflow_v2(names: List[str]) -> List[Dict]:
  196. db = SessionRagflow()
  197. try:
  198. if names:
  199. query = db.query(Dialog.id, Dialog.name, Dialog.description, Dialog.status, Dialog.tenant_id) \
  200. .filter(Dialog.name.in_(names), Dialog.status == "1")
  201. else:
  202. query = db.query(Dialog.id, Dialog.name, Dialog.description, Dialog.status, Dialog.tenant_id).filter(
  203. Dialog.status == "1")
  204. results = query.all()
  205. formatted_results = [
  206. {"id": row[0], "name": row[1], "description": row[2], "status": "1" if row[3] == "1" else "2",
  207. "user_id": str(row[4]), "mode": "agent-dialog"} for row in results]
  208. return formatted_results
  209. finally:
  210. db.close()
  211. def get_data_from_dify_v2(names: List[str]) -> List[Dict]:
  212. db = SessionDify()
  213. try:
  214. if names:
  215. query = db.query(DfApps.id, DfApps.name, DfApps.description, DfApps.status, DfApps.tenant_id, DfApps.mode) \
  216. .filter(DfApps.name.in_(names))
  217. else:
  218. query = db.query(DfApps.id, DfApps.name, DfApps.description, DfApps.status, DfApps.tenant_id, DfApps.mode)
  219. results = query.all()
  220. formatted_results = [
  221. {"id": str(row[0]), "name": row[1], "description": row[2], "status": "1",
  222. "user_id": str(row[4]), "mode": row[5]} for row in results]
  223. return formatted_results
  224. finally:
  225. db.close()
  226. def update_ids_in_local_v2(data: List[Dict], dialog_type: str):
  227. db = SessionLocal()
  228. agent_id_list = []
  229. type_dict = {"1": RAGFLOW, "2": BISHENG, "4": DIFY}
  230. try:
  231. for row in data:
  232. agent_id_list.append(row["id"])
  233. existing_agent = db.query(DialogModel).filter_by(id=row["id"]).first()
  234. if existing_agent:
  235. existing_agent.name = row["name"]
  236. existing_agent.description = row["description"]
  237. # existing_agent.status = row["status"]
  238. existing_agent.mode = row["mode"]
  239. # existing_agent.tenant_id = get_rag_user_id(db, row["user_id"], type_dict[dialog_type])
  240. else:
  241. existing = DialogModel(id=row["id"], status=row["status"], name=row["name"],
  242. description=row["description"],
  243. tenant_id=get_rag_user_id(db, row["user_id"], type_dict[dialog_type]),
  244. dialog_type=dialog_type, mode=row["mode"])
  245. db.add(existing)
  246. db.commit()
  247. for dialog in db.query(DialogModel).filter_by(dialog_type=dialog_type).all():
  248. if dialog.id not in agent_id_list:
  249. # print(dialog.id)
  250. db.query(DialogModel).filter_by(id=dialog.id).update({"status": "2"})
  251. db.commit()
  252. except IntegrityError:
  253. db.rollback()
  254. raise
  255. finally:
  256. db.close()
  257. def get_data_from_ragflow_knowledge():
  258. db = SessionRagflow()
  259. try:
  260. results = db.query(RgKnowledge.id, RgKnowledge.name, RgKnowledge.description, RgKnowledge.status,
  261. RgKnowledge.tenant_id, RgKnowledge.doc_num, RgKnowledge.permission).all()
  262. formatted_results = [
  263. {"id": row[0], "name": row[1], "description": row[2], "status": str(row[3]),
  264. "user_id": str(row[4]), "doc_num": row[5], "permission": row[6]} for row in results]
  265. return formatted_results
  266. finally:
  267. db.close()
  268. def sync_agents_v2():
  269. db = SessionLocal()
  270. try:
  271. app_register = AppRegisterDao(db).get_apps()
  272. for app in app_register:
  273. if app["id"] == RAGFLOW:
  274. ragflow_data = get_data_from_ragflow_v2([])
  275. if ragflow_data:
  276. update_ids_in_local_v2(ragflow_data, "1")
  277. elif app["id"] == BISHENG:
  278. bisheng_data = get_data_from_bisheng_v2([])
  279. if bisheng_data:
  280. update_ids_in_local_v2(bisheng_data, "2")
  281. elif app["id"] == DIFY:
  282. dify_data = get_data_from_dify_v2([])
  283. if dify_data:
  284. update_ids_in_local_v2(dify_data, "4")
  285. print("v2 Agents synchronized successfully")
  286. except Exception as e:
  287. print(f"v2 Failed to sync agents: {str(e)}")
  288. finally:
  289. db.close()
  290. def update_ids_in_local_knowledge(data, klg_type):
  291. type_dict = {"1": RAGFLOW, "2": BISHENG, "4": DIFY}
  292. db = SessionLocal()
  293. agent_id_list = []
  294. try:
  295. for row in data:
  296. agent_id_list.append(row["id"])
  297. existing_agent = db.query(KnowledgeModel).filter_by(id=row["id"]).first()
  298. if existing_agent:
  299. existing_agent.name = row["name"]
  300. existing_agent.description = row["description"]
  301. # existing_agent.tenant_id = get_rag_user_id(db, row["user_id"], type_dict[klg_type])
  302. existing_agent.permission = row["permission"]
  303. existing_agent.documents = row["doc_num"]
  304. existing_agent.status = row["status"]
  305. else:
  306. existing = KnowledgeModel(id=row["id"], name=row["name"], description=row["description"],
  307. tenant_id=get_rag_user_id(db, row["user_id"], type_dict[klg_type]),
  308. status=row["status"],
  309. knowledge_type=1, permission=row["permission"], documents=row["doc_num"])
  310. db.add(existing)
  311. db.commit()
  312. for dialog in db.query(KnowledgeModel).filter_by(knowledge_type=klg_type).all():
  313. if dialog.id not in agent_id_list:
  314. db.query(KnowledgeModel).filter_by(id=dialog.id).delete()
  315. db.commit()
  316. except IntegrityError:
  317. db.rollback()
  318. raise
  319. finally:
  320. db.close()
  321. def get_one_from_ragflow_knowledge(klg_id):
  322. db = SessionRagflow()
  323. try:
  324. row = db.query(RgKnowledge.id, RgKnowledge.name, RgKnowledge.description, RgKnowledge.status,
  325. RgKnowledge.tenant_id, RgKnowledge.doc_num, RgKnowledge.permission).filter(
  326. RgKnowledge.id == klg_id).first()
  327. return {"id": row[0], "name": row[1], "description": row[2], "status": str(row[3]),
  328. "user_id": str(row[4]), "doc_num": row[5], "permission": row[6]} if row else {}
  329. finally:
  330. db.close()
  331. def sync_knowledge():
  332. db = SessionLocal()
  333. try:
  334. app_register = AppRegisterDao(db).get_apps()
  335. for app in app_register:
  336. if app["id"] == RAGFLOW:
  337. ragflow_data = get_data_from_ragflow_knowledge()
  338. if ragflow_data:
  339. update_ids_in_local_knowledge(ragflow_data, "1")
  340. # elif app["id"] == BISHENG:
  341. # bisheng_data = get_data_from_bisheng_v2([])
  342. # update_ids_in_local_v2(bisheng_data, "2")
  343. # elif app["id"] == DIFY:
  344. # dify_data = get_data_from_dify_v2([])
  345. # update_ids_in_local_v2(dify_data, "4")
  346. print("sync knowledge successfully")
  347. except Exception as e:
  348. print(f"Failed to sync knowledge: {str(e)}")
  349. finally:
  350. db.close()
  351. def update_ragflow_user_tenant(user_id: str):
  352. db = SessionRagflow()
  353. try:
  354. if user_id:
  355. db.query(RgUserTenant).filter(RgUserTenant.user_id == user_id, RgUserTenant.role == "invite").update(
  356. {"role": "normal"})
  357. db.query(RgUserTenant).filter(RgUserTenant.tenant_id == user_id, RgUserTenant.role == "invite").update(
  358. {"role": "normal"})
  359. else:
  360. db.query(RgUserTenant).filter(RgUserTenant.role == "invite").update({"role": "normal"})
  361. db.commit()
  362. finally:
  363. db.close()
  364. def import_type_table(session: Session, node: dict, parent=None):
  365. resource_type = ResourceTypeModel(
  366. id=node['id'],
  367. name=node['name'],
  368. description=node.get('description')
  369. )
  370. if parent:
  371. resource_type.parent = parent
  372. session.add(resource_type)
  373. session.commit()
  374. def import_tree(session: Session, node: dict, parent=None):
  375. resource = ResourceModel(
  376. id=node['id'],
  377. name=node['name'],
  378. url=node['url'],
  379. path=node.get('path'),
  380. perms=node['perms'],
  381. description=node.get('description'),
  382. icon=node.get('icon'),
  383. seq=node['seq'],
  384. target=node.get('target'),
  385. canbdeeleted=node.get('canbdeeleted'),
  386. resource_type_id=node['resource_type_id'],
  387. resource_id=node.get('resource_id'),
  388. status=node['status'],
  389. hidden=node.get('hidden')
  390. )
  391. if parent:
  392. resource.parent = parent
  393. session.add(resource)
  394. if 'children' in node:
  395. for child in node['children']:
  396. import_tree(session, child, parent=resource)
  397. session.commit()
  398. def sync_resources_from_json():
  399. db = SessionLocal()
  400. try:
  401. if db.query(ResourceTypeModel).count() == 0:
  402. with open(os.path.join(ENV_CONF_PATH, "resource_type.json"), 'r', encoding='utf-8') as file:
  403. type_json_data = json.load(file)
  404. db.query(ResourceTypeModel).delete()
  405. db.commit()
  406. for node in type_json_data:
  407. import_type_table(db, node)
  408. print("add resourceType record successfully")
  409. else:
  410. print("sync resourcesType successfully")
  411. if db.query(ResourceModel).count() == 0:
  412. with open(os.path.join(ENV_CONF_PATH, "resource.json"), 'r', encoding='utf-8') as file:
  413. json_data = json.load(file)
  414. db.query(ResourceModel).delete()
  415. db.commit()
  416. for node in json_data:
  417. import_tree(db, node)
  418. print("add resources record successfully")
  419. else:
  420. print("sync resources successfully")
  421. except Exception as e:
  422. print(f"Failed to sync resources or resource type: {str(e)}")
  423. finally:
  424. db.close()
  425. if __name__ == "__main__":
  426. # a = get_data_from_dify_v2([])
  427. # print(a)
  428. update_ragflow_user_tenant("")