fetch_agent.py 18 KB

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