fetch_agent.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  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, Dialog_STATSU_DELETE, Dialog_STATSU_ON
  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. para = {
  198. "user_input_form": [],
  199. "retriever_resource": {
  200. "enabled": True
  201. },
  202. "file_upload": {
  203. "enabled": False
  204. }
  205. }
  206. try:
  207. if names:
  208. query = db.query(Dialog.id, Dialog.name, Dialog.description, Dialog.status, Dialog.tenant_id) \
  209. .filter(Dialog.name.in_(names), Dialog.status == "1")
  210. else:
  211. query = db.query(Dialog.id, Dialog.name, Dialog.description, Dialog.status, Dialog.tenant_id).filter(
  212. Dialog.status == "1")
  213. results = query.all()
  214. formatted_results = [
  215. {"id": row[0], "name": row[1], "description": row[2], "status": "1" if row[3] == "1" else "2",
  216. "user_id": str(row[4]), "mode": "agent-dialog", "parameters": para} for row in results]
  217. return formatted_results
  218. finally:
  219. db.close()
  220. def get_data_from_dy_v2(names: List[str]) -> List[Dict]:
  221. db = SessionDify()
  222. try:
  223. if names:
  224. query = db.query(DfApps.id, DfApps.name, DfApps.description, DfApps.status, DfApps.tenant_id, DfApps.mode) \
  225. .filter(DfApps.name.in_(names))
  226. else:
  227. query = db.query(DfApps.id, DfApps.name, DfApps.description, DfApps.status, DfApps.tenant_id, DfApps.mode)
  228. results = query.all()
  229. formatted_results = [
  230. {"id": str(row[0]), "name": row[1], "description": row[2], "status": "1",
  231. "user_id": str(row[4]), "mode": row[5], "parameters": {}} for row in results]
  232. return formatted_results
  233. finally:
  234. db.close()
  235. def update_ids_in_local_v2(data: List[Dict], dialog_type: str):
  236. db = SessionLocal()
  237. agent_id_list = []
  238. type_dict = {"1": RAGFLOW, "2": BISHENG, "4": DIFY}
  239. try:
  240. for row in data:
  241. agent_id_list.append(row["id"])
  242. existing_agent = db.query(DialogModel).filter_by(id=row["id"]).first()
  243. if existing_agent:
  244. existing_agent.name = row["name"]
  245. existing_agent.description = row["description"]
  246. existing_agent.mode = row["mode"]
  247. if existing_agent.status == Dialog_STATSU_DELETE:
  248. existing_agent.status = Dialog_STATSU_ON
  249. if row["parameters"]:
  250. existing_agent.parameters = json.dumps(row["parameters"])
  251. else:
  252. existing = DialogModel(id=row["id"], status=row["status"], name=row["name"],
  253. description=row["description"],
  254. tenant_id=get_rag_user_id(db, row["user_id"], type_dict[dialog_type]),
  255. dialog_type=dialog_type, mode=row["mode"], parameters=json.dumps(row["parameters"]))
  256. db.add(existing)
  257. db.commit()
  258. for dialog in db.query(DialogModel).filter_by(dialog_type=dialog_type).all():
  259. if dialog.id not in agent_id_list:
  260. # print(dialog.id)
  261. db.query(DialogModel).filter_by(id=dialog.id).update({"status": Dialog_STATSU_DELETE})
  262. db.commit()
  263. except IntegrityError:
  264. db.rollback()
  265. raise
  266. finally:
  267. db.close()
  268. def get_data_from_ragflow_knowledge():
  269. db = SessionRagflow()
  270. try:
  271. results = db.query(RgKnowledge.id, RgKnowledge.name, RgKnowledge.description, RgKnowledge.status,
  272. RgKnowledge.tenant_id, RgKnowledge.doc_num, RgKnowledge.permission).all()
  273. formatted_results = [
  274. {"id": row[0], "name": row[1], "description": row[2], "status": str(row[3]),
  275. "user_id": str(row[4]), "doc_num": row[5], "permission": row[6]} for row in results]
  276. return formatted_results
  277. finally:
  278. db.close()
  279. def sync_agents_v2():
  280. db = SessionLocal()
  281. try:
  282. app_register = AppRegisterDao(db).get_apps()
  283. for app in app_register:
  284. if app["id"] == RAGFLOW:
  285. ragflow_data = get_data_from_ragflow_v2([])
  286. if ragflow_data:
  287. update_ids_in_local_v2(ragflow_data, "1")
  288. # elif app["id"] == BISHENG:
  289. # bisheng_data = get_data_from_bisheng_v2([])
  290. # if bisheng_data:
  291. # update_ids_in_local_v2(bisheng_data, "2")
  292. elif app["id"] == DIFY:
  293. dify_data = get_data_from_dy_v2([])
  294. if dify_data:
  295. update_ids_in_local_v2(dify_data, "4")
  296. print("v2 Agents synchronized successfully")
  297. except Exception as e:
  298. print(f"v2 Failed to sync agents: {str(e)}")
  299. finally:
  300. db.close()
  301. def update_ids_in_local_knowledge(data, klg_type):
  302. type_dict = {"1": RAGFLOW, "2": BISHENG, "4": DIFY}
  303. db = SessionLocal()
  304. agent_id_list = []
  305. try:
  306. for row in data:
  307. agent_id_list.append(row["id"])
  308. existing_agent = db.query(KnowledgeModel).filter_by(id=row["id"]).first()
  309. if existing_agent:
  310. existing_agent.name = row["name"]
  311. existing_agent.description = row["description"]
  312. # existing_agent.tenant_id = get_rag_user_id(db, row["user_id"], type_dict[klg_type])
  313. existing_agent.permission = row["permission"]
  314. existing_agent.documents = row["doc_num"]
  315. existing_agent.status = row["status"]
  316. else:
  317. existing = KnowledgeModel(id=row["id"], name=row["name"], description=row["description"],
  318. tenant_id=get_rag_user_id(db, row["user_id"], type_dict[klg_type]),
  319. status=row["status"],
  320. knowledge_type=1, permission=row["permission"], documents=row["doc_num"])
  321. db.add(existing)
  322. db.commit()
  323. for dialog in db.query(KnowledgeModel).filter_by(knowledge_type=klg_type).all():
  324. if dialog.id not in agent_id_list:
  325. db.query(KnowledgeModel).filter_by(id=dialog.id).delete()
  326. db.commit()
  327. except IntegrityError:
  328. db.rollback()
  329. raise
  330. finally:
  331. db.close()
  332. def get_one_from_ragflow_knowledge(klg_id):
  333. db = SessionRagflow()
  334. try:
  335. row = db.query(RgKnowledge.id, RgKnowledge.name, RgKnowledge.description, RgKnowledge.status,
  336. RgKnowledge.tenant_id, RgKnowledge.doc_num, RgKnowledge.permission).filter(
  337. RgKnowledge.id == klg_id).first()
  338. return {"id": row[0], "name": row[1], "description": row[2], "status": str(row[3]),
  339. "user_id": str(row[4]), "doc_num": row[5], "permission": row[6]} if row else {}
  340. finally:
  341. db.close()
  342. def sync_knowledge():
  343. db = SessionLocal()
  344. try:
  345. app_register = AppRegisterDao(db).get_apps()
  346. for app in app_register:
  347. if app["id"] == RAGFLOW:
  348. ragflow_data = get_data_from_ragflow_knowledge()
  349. if ragflow_data:
  350. update_ids_in_local_knowledge(ragflow_data, "1")
  351. # elif app["id"] == BISHENG:
  352. # bisheng_data = get_data_from_bisheng_v2([])
  353. # update_ids_in_local_v2(bisheng_data, "2")
  354. # elif app["id"] == DIFY:
  355. # dify_data = get_data_from_dify_v2([])
  356. # update_ids_in_local_v2(dify_data, "4")
  357. print("sync knowledge successfully")
  358. except Exception as e:
  359. print(f"Failed to sync knowledge: {str(e)}")
  360. finally:
  361. db.close()
  362. def update_ragflow_user_tenant(user_id: str):
  363. db = SessionRagflow()
  364. try:
  365. if user_id:
  366. db.query(RgUserTenant).filter(RgUserTenant.user_id == user_id, RgUserTenant.role == "invite").update(
  367. {"role": "normal"})
  368. db.query(RgUserTenant).filter(RgUserTenant.tenant_id == user_id, RgUserTenant.role == "invite").update(
  369. {"role": "normal"})
  370. else:
  371. db.query(RgUserTenant).filter(RgUserTenant.role == "invite").update({"role": "normal"})
  372. db.commit()
  373. finally:
  374. db.close()
  375. def import_type_table(session: Session, node: dict, parent=None):
  376. resource_type = ResourceTypeModel(
  377. id=node['id'],
  378. name=node['name'],
  379. description=node.get('description')
  380. )
  381. if parent:
  382. resource_type.parent = parent
  383. session.add(resource_type)
  384. session.commit()
  385. def import_tree(session: Session, node: dict, parent=None):
  386. resource = ResourceModel(
  387. id=node['id'],
  388. name=node['name'],
  389. url=node['url'],
  390. path=node.get('path'),
  391. perms=node['perms'],
  392. description=node.get('description'),
  393. icon=node.get('icon'),
  394. seq=node['seq'],
  395. target=node.get('target'),
  396. canbdeeleted=node.get('canbdeeleted'),
  397. resource_type_id=node['resource_type_id'],
  398. resource_id=node.get('resource_id'),
  399. status=node['status'],
  400. hidden=node.get('hidden')
  401. )
  402. if parent:
  403. resource.parent = parent
  404. session.add(resource)
  405. if 'children' in node:
  406. for child in node['children']:
  407. import_tree(session, child, parent=resource)
  408. session.commit()
  409. def sync_resources_from_json():
  410. db = SessionLocal()
  411. try:
  412. if db.query(ResourceTypeModel).count() == 0:
  413. with open(os.path.join(ENV_CONF_PATH, "resource_type.json"), 'r', encoding='utf-8') as file:
  414. type_json_data = json.load(file)
  415. db.query(ResourceTypeModel).delete()
  416. db.commit()
  417. for node in type_json_data:
  418. import_type_table(db, node)
  419. print("add resourceType record successfully")
  420. else:
  421. print("sync resourcesType successfully")
  422. if db.query(ResourceModel).count() == 0:
  423. with open(os.path.join(ENV_CONF_PATH, "resource.json"), 'r', encoding='utf-8') as file:
  424. json_data = json.load(file)
  425. db.query(ResourceModel).delete()
  426. db.commit()
  427. for node in json_data:
  428. import_tree(db, node)
  429. print("add resources record successfully")
  430. else:
  431. print("sync resources successfully")
  432. except Exception as e:
  433. print(f"Failed to sync resources or resource type: {str(e)}")
  434. finally:
  435. db.close()
  436. if __name__ == "__main__":
  437. # a = get_data_from_dify_v2([])
  438. # print(a)
  439. update_ragflow_user_tenant("")