fetch_agent.py 19 KB

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