From e6c5e89f09637b8d9ebca6895d781663f12646d6 Mon Sep 17 00:00:00 2001
From: zhaoqingang <zhaoqg0118@163.com>
Date: 星期二, 17 十二月 2024 16:43:55 +0800
Subject: [PATCH] dify 文档智能

---
 app/api/role.py                  |    2 
 env_conf/menu_conf.json          |   74 ++++++++--
 app/models/organization_model.py |   16 ++
 app/api/chat.py                  |  138 +++++++++++++++++++
 app/service/user.py              |   19 ++
 env_conf/app_register_conf.json  |    2 
 app/service/difyService.py       |   12 -
 app/api/user.py                  |   18 ++
 app/api/auth.py                  |   24 +-
 app/models/user.py               |    5 
 app/models/role_model.py         |   10 
 app/service/dialog.py            |    4 
 app/config/const.py              |    1 
 app/task/fetch_agent.py          |   37 +++-
 app/service/role.py              |    9 
 app/models/dialog_model.py       |    2 
 16 files changed, 303 insertions(+), 70 deletions(-)

diff --git a/app/api/auth.py b/app/api/auth.py
index faad16d..d95e473 100644
--- a/app/api/auth.py
+++ b/app/api/auth.py
@@ -35,14 +35,14 @@
     if db_user:
         return Response(code=200, msg="Username already registered")
 
-    bisheng_service = BishengService(settings.sgb_base_url)
+    # bisheng_service = BishengService(settings.sgb_base_url)
     ragflow_service = RagflowService(settings.fwr_base_url)
 
     # 娉ㄥ唽鍒版瘯鏄�
-    try:
-        bisheng_info = await bisheng_service.register(user.username, user.password)
-    except Exception as e:
-        return Response(code=500, msg=f"Failed to register with Bisheng: {str(e)}")
+    # try:
+    #     bisheng_info = await bisheng_service.register(user.username, user.password)
+    # except Exception as e:
+    #     return Response(code=500, msg=f"Failed to register with Bisheng: {str(e)}")
 
     # 娉ㄥ唽鍒皉agflow
     try:
@@ -52,7 +52,7 @@
 
     # 瀛樺偍鐢ㄦ埛淇℃伅
     hashed_password = pwd_context.hash(user.password)
-    db_user = UserModel(username=user.username, hashed_password=hashed_password, email=ragflow_info.get("email",  f"{user.username}@example.com"),ragflow_id=ragflow_info.get("id"),bisheng_id=bisheng_info.get("user_id"))
+    db_user = UserModel(username=user.username, hashed_password=hashed_password, email=ragflow_info.get("email",  f"{user.username}@example.com"),ragflow_id=ragflow_info.get("id"),bisheng_id="")
     db_user.password = db_user.encrypted_password(user.password)
     db.add(db_user)
     db.commit()
@@ -66,14 +66,14 @@
     if not user:
         return Response(code=400, msg="Incorrect username or password")
 
-    bisheng_service = BishengService(settings.sgb_base_url)
+    # bisheng_service = BishengService(settings.sgb_base_url)
     ragflow_service = RagflowService(settings.fwr_base_url)
 
     # 鐧诲綍鍒版瘯鏄�
-    try:
-        bisheng_token = await bisheng_service.login(login_data.username, login_data.password)
-    except Exception as e:
-        return Response(code=500, msg=f"Failed to login with Bisheng: {str(e)}")
+    # try:
+    #     bisheng_token = await bisheng_service.login(login_data.username, login_data.password)
+    # except Exception as e:
+    #     return Response(code=500, msg=f"Failed to login with Bisheng: {str(e)}")
 
     # 鐧诲綍鍒皉agflow
     try:
@@ -84,7 +84,7 @@
     # 鍒涘缓鏈湴token
     access_token = create_access_token(data={"sub": user.username, "user_id": user.id})
 
-    upsert_token(db, user.id, access_token, bisheng_token, ragflow_token)
+    upsert_token(db, user.id, access_token, "bisheng_token", ragflow_token)
     # print(111)
     return Response(code=200, msg="Login successful", data={
         "access_token": access_token,
diff --git a/app/api/chat.py b/app/api/chat.py
index ecae273..57438be 100644
--- a/app/api/chat.py
+++ b/app/api/chat.py
@@ -10,7 +10,7 @@
 from Log import logger
 from app.api import get_current_user_websocket
 from app.config.config import settings
-from app.config.const import IMAGE_TO_TEXT, DOCUMENT_TO_REPORT, DOCUMENT_TO_CLEANING
+from app.config.const import IMAGE_TO_TEXT, DOCUMENT_TO_REPORT, DOCUMENT_TO_CLEANING, DOCUMENT_IA_QUESTIONS
 from app.models import MenuCapacityModel
 from app.models.agent_model import AgentModel, AgentType
 from app.models.base_model import get_db
@@ -44,6 +44,8 @@
     else:
         agent_type = agent.capacity_type
         chat_type = agent.chat_type
+    # print(agent_type)
+    # print(chat_type)
     if not agent:
         ret = {"message": "Agent not found", "type": "close"}
         await websocket.send_json(ret)
@@ -348,7 +350,15 @@
                         # complete_response = ""
 
                         answer_str = ""
-                        async for rag_response in dify_service.chat(token, current_user.id, question, upload_file_id,
+                        files = []
+                        if upload_file_id:
+                            files.append({
+                                "type": "image",
+                                "transfer_method": "local_file",
+                                "url": "",
+                                "upload_file_id": upload_file_id
+                            })
+                        async for rag_response in dify_service.chat(token, current_user.id, question, files,
                                                                     conversation_id):
                             # print(rag_response)
                             try:
@@ -537,6 +547,130 @@
                                 result = {"message": f"鍐呴儴閿欒锛� {e2}", "type": "close"}
                                 await websocket.send_json(result)
                                 print(f"Error process message of ragflow: {e2}")
+                elif chat_type == "documentIa":
+                    # print(122112)
+                    token = DfTokenDao(db).get_token_by_id(DOCUMENT_IA_QUESTIONS)
+                    # print(token)
+                    if not token:
+                        await websocket.send_json({"message": "Invalid token", "type": "error"})
+
+                    while True:
+                        conversation_id = ""
+                        # print(4343)
+                        receive_message = await websocket.receive_json()
+                        print(f"Received from client {chat_id}: {receive_message}")
+                        upload_file_id = receive_message.get('upload_file_id', [])
+                        question = receive_message.get('message', "")
+                        if not question and not image_url:
+                            await websocket.send_json({"message": "Invalid request", "type": "error"})
+                            continue
+                        try:
+                            session = SessionService(db).create_session(
+                                chat_id,
+                                question,
+                                agent_id,
+                                AgentType.DIFY,
+                                current_user.id
+                            )
+                            conversation_id = session.conversation_id
+                        except Exception as e:
+                            logger.error(e)
+                        # complete_response = ""
+                        files = []
+                        for fileId in upload_file_id:
+                            files.append({
+                                "type": "document",
+                                "transfer_method": "local_file",
+                                "url": "",
+                                "upload_file_id": fileId
+                            })
+
+                        answer_str = ""
+                        complete_response = ""
+                        async for rag_response in dify_service.chat(token, current_user.id, question, files,
+                                                                    conversation_id):
+                            # print(rag_response)
+                            try:
+                                if rag_response[:5] == "data:":
+                                    # 濡傛灉鏄紝鍒欐埅鍙栨帀鍓�5涓瓧绗︼紝骞跺幓闄ら灏剧┖鐧界
+                                    complete_response = rag_response[5:].strip()
+                                elif "event: ping" in rag_response:
+                                    continue
+                                else:
+                                    # 鍚﹀垯锛屼繚鎸佸師鏍�
+                                    complete_response += rag_response
+                                try:
+                                    data = json.loads(complete_response)
+                                    if data.get("event") == "node_started" or data.get(
+                                            "event") == "node_finished":  # "event": "message_end"
+                                        if "data" not in data or not data["data"]:  # 淇℃伅杩囨护
+                                            logger.error("闈炴硶鏁版嵁--------------------")
+                                            logger.error(data)
+                                            continue
+                                        else:  # 姝e父杈撳嚭
+                                            answer = data.get("data", "")
+                                            if isinstance(answer, str):
+                                                logger.error("----------------鏈煡鏁版嵁--------------------")
+                                                logger.error(data)
+                                                continue
+                                            elif isinstance(answer, dict):
+
+                                                message = answer.get("title", "")
+
+                                            result = {"message": message, "type": "system"}
+                                            continue
+                                    elif data.get("event") == "message":  # "event": "message_end"
+                                         # 姝e父杈撳嚭
+                                        answer = data.get("answer", "")
+                                        result = {"message": answer, "type": "message"}
+                                    elif data.get("event") == "workflow_finished":
+                                        answer = data.get("data", "")
+                                        if isinstance(answer, str):
+                                            logger.error("----------------鏈煡鏁版嵁--------------------")
+                                            logger.error(data)
+                                            result = {"message": "", "type": "close", "download_url": ""}
+                                        elif isinstance(answer, dict):
+                                            download_url = ""
+                                            outputs = answer.get("outputs", {})
+                                            if outputs:
+                                                message = outputs.get("answer", "")
+                                                # download_url = outputs.get("download_url", "")
+                                            else:
+                                                message = answer.get("error", "")
+
+                                            # result = {"message": message, "type": "message",
+                                            #           "download_url": download_url}
+                                            try:
+                                                SessionService(db).update_session(chat_id,
+                                                                                  message={"role": "assistant",
+                                                                                           "content": {
+                                                                                               "answer": message,
+                                                                                               "download_url": download_url}},
+                                                                                  conversation_id=data.get(
+                                                                                      "conversation_id"))
+                                            except Exception as e:
+                                                logger.error("淇濆瓨dify鐨勪細璇濆紓甯革紒")
+                                                logger.error(e)
+                                            # await websocket.send_json(result)
+                                        continue
+                                    elif data.get("event") == "message_end":
+                                        result = {"message": "", "type": "close"}
+
+                                    else:
+                                        continue
+                                    try:
+                                        await websocket.send_json(result)
+                                    except Exception as e:
+                                        logger.error(e)
+                                        logger.error("杩斿洖瀹㈡埛绔秷鎭紓甯�!")
+                                    complete_response = ""
+                                except json.JSONDecodeError as e:
+                                    print(f"Error decoding JSON: {e}")
+                                    # print(f"Response text: {text}")
+                            except Exception as e2:
+                                result = {"message": f"鍐呴儴閿欒锛� {e2}", "type": "close"}
+                                await websocket.send_json(result)
+                                print(f"Error process message of ragflow: {e2}")
 
             # 鍚姩浠诲姟澶勭悊瀹㈡埛绔秷鎭�
             tasks = [
diff --git a/app/api/role.py b/app/api/role.py
index ad5e78d..5ddeef9 100644
--- a/app/api/role.py
+++ b/app/api/role.py
@@ -66,7 +66,7 @@
         db_role = db.query(RoleModel).filter(RoleModel.name == role.roleName).first()
         if db_role and db_role.id != role.roleId:
             return Response(code=200, msg="role already created")
-    is_edit = await edit_role_resource(db, role.roleId,role.roleName, role.remark, role.roleKey, role.dataScope, role.resources, role.editType)
+    is_edit = await edit_role_resource(db, role.roleId,role.roleName, role.remark, role.roleKey, role.dataScope, role.resources, role.editType, role.depts)
     if not is_edit:
         return Response(code=500, msg="role edit failure", data={})
     return Response(code=200, msg="role edit successfully", data={})
\ No newline at end of file
diff --git a/app/api/user.py b/app/api/user.py
index 78666b4..efd0ada 100644
--- a/app/api/user.py
+++ b/app/api/user.py
@@ -1,12 +1,12 @@
 from fastapi import APIRouter, Depends
 from app.api import Response, pwd_context, get_current_user, ResponseList
 from app.models.base_model import get_db
-from app.models.user import PageParameter, UserStatus, UserInfo, LoginData, UserPassword
+from app.models.user import PageParameter, UserStatus, UserInfo, LoginData, UserPassword, UserDept
 from app.models.user_model import UserModel
 from app.service.auth import is_valid_password, verify_password
 from app.service.user import get_user_list, edit_user_status, delete_user_data, create_user, edit_user_data, \
     edit_user_pwd, get_user_info, get_user_routers, get_user_menus, get_user_permission, get_user_dept, change_user_pwd, \
-    user_data_service
+    user_data_service, edit_user_dept
 
 user_router = APIRouter()
 
@@ -142,4 +142,16 @@
     user_info = await user_data_service(db, userId)
     if not user_info:
         return Response(code=500, msg="user get failure", data={})
-    return Response(code=200, msg="successfully", data=user_info)
\ No newline at end of file
+    return Response(code=200, msg="successfully", data=user_info)
+
+
+
+@user_router.put("/dept", response_model=Response)
+async def edit_user(user: UserDept, current_user: UserModel = Depends(get_current_user), db=Depends(get_db)):
+    user_info = db.query(UserModel).filter(UserModel.id == user.userId).first()
+    if not user_info:
+        return Response(code=400, msg="user does not exist")
+    is_edit = await edit_user_dept(db, user.userId, user.depts)
+    if not is_edit:
+        return Response(code=500, msg="user edit failure", data={})
+    return Response(code=200, msg="user edit successfully", data={})
\ No newline at end of file
diff --git a/app/config/const.py b/app/config/const.py
index f4fb7a9..824f0ae 100644
--- a/app/config/const.py
+++ b/app/config/const.py
@@ -3,6 +3,7 @@
 DOCUMENT_TO_CLEANING = "document_to_cleaning"
 DOCUMENT_TO_REPORT = "document_to_report"
 IMAGE_TO_TEXT = "image_and_text_conversion"
+DOCUMENT_IA_QUESTIONS = "document_ia_questions"
 
 
 ### -----------app register --------------
diff --git a/app/models/dialog_model.py b/app/models/dialog_model.py
index 6751937..058581c 100644
--- a/app/models/dialog_model.py
+++ b/app/models/dialog_model.py
@@ -19,7 +19,7 @@
     name = Column(String(255))                 # 鍚嶇О
     description = Column(Text)                 # 璇存槑
     icon = Column(Text, default="intelligentFrame1")                         # 鍥炬爣
-    status = Column(String(1), default="1")                 # 鐘舵��
+    status = Column(String(1), default="0")                 # 鐘舵��
     dialog_type = Column(String(1))            #  骞冲彴
     # agent_id = Column(String(36))
     mode = Column(String(36))
diff --git a/app/models/organization_model.py b/app/models/organization_model.py
index 08bb6e4..43a9354 100644
--- a/app/models/organization_model.py
+++ b/app/models/organization_model.py
@@ -92,6 +92,22 @@
 
         return json
 
+    def to_base_json(self):
+        json = {
+            'deptId': self.id,
+            'deptName': self.name,
+            'address': self.address,
+            'code': self.code,
+            'iconCls': self.iconcls,
+            'orderNum': self.seq,
+            'leader': self.leader,
+            'phone': self.phone,
+            'email': self.email,
+            'status': self.status
+        }
+
+        return json
+
 
     def role_json(self, role):
         return {
diff --git a/app/models/role_model.py b/app/models/role_model.py
index 22f73c5..42895df 100644
--- a/app/models/role_model.py
+++ b/app/models/role_model.py
@@ -25,7 +25,7 @@
     seq = Column(Integer)
     roleKey = Column(String(100))
     dataScope = Column(Integer)
-    status = Column(String(10), default="0")
+    status = Column(String(10), default="1")
     creator = Column(Integer)
     role_type = Column(Integer, default=1)
 
@@ -58,11 +58,10 @@
             'dataScope': self.dataScope
         }
 
-        if len(self.resources) > 0:
-            json['resources'] = [resource.to_json() for resource in self.resources]
+        # if len(self.resources) > 0:
+        json['resources'] = [resource.to_json() for resource in self.resources]
 
-        if hasattr(self, 'flag'):
-            json['flag'] = self.flag
+        json['dept'] = [dept.to_base_json() for dept in self.organizations]
 
         return json
 
@@ -102,3 +101,4 @@
     roleKey: Optional[str] = ""
     dataScope: Optional[int] = 0
     editType: int
+    depts: Optional[list] = []
diff --git a/app/models/user.py b/app/models/user.py
index 1d96a23..731bd2e 100644
--- a/app/models/user.py
+++ b/app/models/user.py
@@ -53,3 +53,8 @@
     oldPassword: str
 
 
+class UserDept(BaseModel):
+    userId: int
+    depts: list
+
+
diff --git a/app/service/dialog.py b/app/service/dialog.py
index 7073aa5..d00ad53 100644
--- a/app/service/dialog.py
+++ b/app/service/dialog.py
@@ -92,7 +92,7 @@
 
 async def create_dialog_service(db, dialog_id, dialog_name, description, icon, dialog_type, mode, user_id):
     try:
-        dialog_model = DialogModel(id=dialog_id,name=dialog_name, description=description,icon=icon, dialog_type=dialog_type, tenant_id=user_id, agent_id=dialog_id, mode=mode)
+        dialog_model = DialogModel(id=dialog_id,name=dialog_name, description=description,icon=icon, dialog_type=dialog_type, tenant_id=user_id, mode=mode,update_date=datetime.now(),create_date=datetime.now())
         db.add(dialog_model)
         db.commit()
         db.refresh(dialog_model)
@@ -105,7 +105,7 @@
 
 async def update_dialog_status_service(db, dialog_id, status):
     try:
-        db.query(DialogModel).filter_by(id=dialog_id).update({"status":status})
+        db.query(DialogModel).filter_by(id=dialog_id).update({"status":status, "update_date": datetime.now()})
         db.commit()
     except Exception as e:
         logger.error(e)
diff --git a/app/service/difyService.py b/app/service/difyService.py
index c51719e..97de46b 100644
--- a/app/service/difyService.py
+++ b/app/service/difyService.py
@@ -127,19 +127,9 @@
 
 
 
-    async def chat(self, token: str, user_id: int,  message: str, upload_file_id: str, conversation_id: str):
+    async def chat(self, token: str, user_id: int,  message: str, files: [], conversation_id: str):
 
         target_url = f"{self.base_url}/v1/chat-messages"
-        files = []
-        if upload_file_id:
-            files = [
-                {
-                    "type": "image",
-                    "transfer_method": "local_file",
-                    "url": "",
-                    "upload_file_id": upload_file_id
-                }
-            ]
         data = {
             "inputs": {},
             "query": message,
diff --git a/app/service/role.py b/app/service/role.py
index bc3e1af..c7da9b6 100644
--- a/app/service/role.py
+++ b/app/service/role.py
@@ -1,6 +1,7 @@
 import uuid
 
 from Log import logger
+from app.models import OrganizationModel
 from app.models.resource_model import ResourceModel
 from app.models.role_model import RoleModel
 
@@ -13,7 +14,7 @@
     if keyword:
         query = query.filter(RoleModel.name.like('%{}%'.format(keyword)))
     total = query.count()
-    roles = query.order_by(RoleModel.id.desc()).limit(page_size).offset(
+    roles = query.order_by(RoleModel.created_at.desc()).limit(page_size).offset(
         (page_index - 1) * page_size).all()
     return {"total": total, "rows":  [role.to_json() for role in roles]}
 
@@ -54,7 +55,7 @@
     return True
 
 
-async def edit_role_resource(db, role_id:str, role_name:str, description:str,role_key:str, data_scope:int, resources:list, edit_type:int):
+async def edit_role_resource(db, role_id:str, role_name:str, description:str,role_key:str, data_scope:int, resources:list, edit_type:int, depts:list):
     try:
         role = db.query(RoleModel).filter(RoleModel.id == role_id).first()
         if edit_type == 1:
@@ -65,8 +66,10 @@
                 role.roleKey = role_key
             if data_scope:
                 role.dataScope = data_scope
-        else:
+        elif edit_type == 2:
             role.resources = [db.get(ResourceModel, resourcesId) for resourcesId in resources]
+        elif edit_type == 3:
+            role.organizations = [db.get(OrganizationModel, deptId) for deptId in depts]
         db.add(role)
         db.commit()
     except Exception as e:
diff --git a/app/service/user.py b/app/service/user.py
index 1ce7417..895f477 100644
--- a/app/service/user.py
+++ b/app/service/user.py
@@ -5,7 +5,7 @@
 from app.api.dialog import dialog_list
 from app.config.config import settings
 from app.config.const import RAGFLOW, BISHENG, DIFY
-from app.models import RoleModel, GroupModel, AgentType, role_resource_table, DialogModel
+from app.models import RoleModel, GroupModel, AgentType, role_resource_table, DialogModel, OrganizationModel
 from app.models.menu_model import WebMenuModel, MenuCapacityModel
 from app.models.user_model import UserModel, UserAppModel
 from Log import logger
@@ -245,6 +245,7 @@
     for group in user.groups:
         for dialog in group.dialogs:
             dialog_list.append(dialog.id)
+    print(dialog_list)
     menu_list = db.query(WebMenuModel.id, WebMenuModel.title, WebMenuModel.describe, WebMenuModel.icon, WebMenuModel.desc,WebMenuModel.rank,
                          WebMenuModel.img, MenuCapacityModel.capacity_id, MenuCapacityModel.capacity_type, MenuCapacityModel.chat_id.label("agentId")).outerjoin(
         MenuCapacityModel, WebMenuModel.id == MenuCapacityModel.menu_id).outerjoin(
@@ -258,7 +259,7 @@
         for m in menus:
             if user.permission == "admin":
                 continue
-            elif not m.capacity_type or m.capacity_type == 1 and m.capacity_id not in dialog_list:
+            elif m.capacity_id not in dialog_list:
                 break
         else:
             res.append({
@@ -343,4 +344,16 @@
     user = db.query(UserModel).filter_by(id=user_id).first()
 
 
-    return {"roles": [i.to_dict() for i in user.roles], "user": user.to_dict()}
\ No newline at end of file
+    return {"roles": [i.to_dict() for i in user.roles], "user": user.to_dict()}
+
+
+async def edit_user_dept(db, user_id, dept_list):
+    try:
+        user = db.query(UserModel).filter(UserModel.id == user_id).first()
+        user.organizations = [db.get(OrganizationModel, deptId) for deptId in dept_list]
+        db.commit()
+    except Exception as e:
+        logger.error(e)
+        db.rollback()
+        return False
+    return True
\ No newline at end of file
diff --git a/app/task/fetch_agent.py b/app/task/fetch_agent.py
index 5d08434..eec88ad 100644
--- a/app/task/fetch_agent.py
+++ b/app/task/fetch_agent.py
@@ -7,7 +7,8 @@
 
 from app.config.config import settings
 from app.config.const import RAGFLOW, BISHENG, DIFY
-from app.models import DialogModel
+from app.models.dialog_model import DialogModel
+from app.models.user_model import UserAppModel
 from app.models.agent_model import AgentModel
 from app.models.base_model import SessionLocal, Base
 from app.service.v2.app_register import AppRegisterDao
@@ -130,9 +131,9 @@
             result = db.query(AgentModel).delete()
             db.commit()  # 鎻愪氦浜嬪姟
         initial_agents = [
-            ('80ee430a-e396-48c4-a12c-7c7cdf5eda51', 1, '鎶ュ憡鐢熸垚', 'BISHENG', 'report'),
+            # ('80ee430a-e396-48c4-a12c-7c7cdf5eda51', 1, '鎶ュ憡鐢熸垚', 'DIFY', 'report'),
             ('basic_excel_merge', 2, '鎶ヨ〃鍚堝苟', 'BASIC', 'excelMerge'),
-            ('bfd090d589d811efb3630242ac190006', 4, '鏂囨。鏅鸿兘', 'BISHENG', 'report'),
+            ('bfd090d589d811efb3630242ac190006', 4, '鏂囨。鏅鸿兘', 'DIFY', 'documentIa'),
             ('da3451da89d911efb9490242ac190006', 3, '鐭ヨ瘑闂瓟', 'RAGFLOW', 'knowledgeQA'),
             ('e96eb7a589db11ef87d20242ac190006', 5, '鏅鸿兘闂瓟', 'RAGFLOW', 'chat'),
             ('basic_excel_talk', 6, '鏅鸿兘鏁版嵁', 'BASIC', 'excelTalk'),
@@ -157,10 +158,10 @@
 
 def sync_agents():
     try:
-        bisheng_data = get_data_from_bisheng(BISHENG_NAMES_TO_SYNC)
+        # bisheng_data = get_data_from_bisheng(BISHENG_NAMES_TO_SYNC)
         ragflow_data = get_data_from_ragflow(RAGFLOW_NAMES_TO_SYNC)
 
-        update_ids_in_local(bisheng_data)
+        # update_ids_in_local(bisheng_data)
         update_ids_in_local(ragflow_data)
 
         print("Agents synchronized successfully")
@@ -184,6 +185,14 @@
         raise
     finally:
         db.close()
+
+def get_rag_user_id(db, tenant_id, app_type):
+
+    user = db.query(UserAppModel).filter(UserAppModel.app_type==app_type, UserAppModel.app_id==tenant_id).first()
+    if user:
+        return user.user_id
+    return tenant_id
+
 
 def get_data_from_bisheng_v2(names: List[str]) -> List[Dict]:
     db = SessionBisheng()
@@ -242,9 +251,7 @@
 def update_ids_in_local_v2(data: List[Dict], dialog_type:str):
     db = SessionLocal()
     agent_id_list = []
-    print("----------------------------------------")
-    print(data)
-    print("*********************************************")
+    type_dict = {"1": RAGFLOW,"2": BISHENG,"4": DIFY}
     try:
         for row in data:
             agent_id_list.append(row["id"])
@@ -252,8 +259,9 @@
             if existing_agent:
                 existing_agent.name = row["name"]
                 existing_agent.description = row["description"]
+                existing_agent.tenant_id = get_rag_user_id(db, row["user_id"], type_dict[dialog_type])
             else:
-                existing = DialogModel(id=row["id"], name=row["name"], description=row["description"], tenant_id=row["user_id"], dialog_type=dialog_type)
+                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)
                 db.add(existing)
         db.commit()
         for dialog in db.query(DialogModel).filter_by(dialog_type=dialog_type).all():
@@ -269,7 +277,16 @@
 
 
 def get_data_from_ragflow_knowledge():
-    ...
+    db = SessionRagflow()
+    try:
+
+        results = db.query(Dialog.id, Dialog.name, Dialog.description, Dialog.status, Dialog.tenant_id).all()
+        formatted_results = [
+            {"id": format_uuid(row[0]), "name": row[1], "description": row[2], "status": str(row[3]),
+             "user_id": str(row[4])} for row in results]
+        return formatted_results
+    finally:
+        db.close()
 
 def sync_agents_v2():
     db = SessionLocal()
diff --git a/env_conf/app_register_conf.json b/env_conf/app_register_conf.json
index 75cbbbb..1b0c73e 100644
--- a/env_conf/app_register_conf.json
+++ b/env_conf/app_register_conf.json
@@ -1,5 +1,5 @@
 {
-  "bisheng_app": 1,
+  "bisheng_app": 0,
   "dify_app": 1,
   "ragflow_app": 1
 }
\ No newline at end of file
diff --git a/env_conf/menu_conf.json b/env_conf/menu_conf.json
index 6139123..224189b 100644
--- a/env_conf/menu_conf.json
+++ b/env_conf/menu_conf.json
@@ -10,8 +10,8 @@
       "rank": 100,
       "dialog": [
         {
-          "id": "1",
-          "chat_id": "",
+          "id": "80ee430a-e396-48c4-a12c-7c7cdf5eda51",
+          "chat_id": "80ee430a-e396-48c4-a12c-7c7cdf5eda51",
           "chat_type": "report",
           "agentType": 2
         }
@@ -26,10 +26,10 @@
       "describe": "鍩轰簬鎮ㄤ笂浼犵殑鎶ヨ〃杩涜鍚堝苟锛屽姪鎮ㄥ揩閫熷畬鎴愭姤琛ㄦ暣鍚堜笌鍒嗘瀽",
       "dialog": [
         {
-          "id": "2",
-          "chat_id": "",
+          "id": "basic_excel_merge",
+          "chat_id": "basic_excel_merge",
           "chat_type": "excelMerge",
-          "agentType": 1
+          "agentType": 3
         }
       ],
       "rank": 99
@@ -42,7 +42,14 @@
       "desc": "閬嶅巻宸插垱寤虹殑鏂囨。鐭ヨ瘑搴擄紝鐢熸垚瀹屾暣鍜屽噯纭殑绛旀锛屽悓鏃舵樉绀烘潵婧愭枃妗d緵鎮ㄥ弬鑰�",
       "describe": "鍨傚煙鐭ヨ瘑鐨勯棶绛斿姪鎵嬶紝閽堝浣犵殑鎻愰棶锛屾垜浠皢閬嶅巻宸插垱寤虹殑鏂囨。鐭ヨ瘑搴擄紝鐢熸垚瀹屾暣鍜屽噯纭殑绛旀锛屽悓鏃舵樉绀烘潵婧愭枃妗d緵鎮ㄥ弬鑰冦��",
       "rank": 98,
-      "dialog": []
+      "dialog": [
+        {
+          "id": "42e4fcdc-9bea-11ef-ac30-0242ac160006",
+          "chat_id": "42e4fcdc-9bea-11ef-ac30-0242ac160006",
+          "chat_type": "knowledgeQA",
+          "agentType": 1
+        }
+      ]
     },
     {
       "id": 3,
@@ -54,10 +61,10 @@
       "rank": 97,
       "dialog": [
         {
-          "id": "3",
-          "chat_id": "",
+          "id": "c684bab4-f05b-423e-8727-f50497e73ebf",
+          "chat_id": "c684bab4-f05b-423e-8727-f50497e73ebf",
           "chat_type": "report",
-          "agentType": 1
+          "agentType": 2
         }
       ]
     },
@@ -69,7 +76,14 @@
       "desc": "鑳藉鐞嗚В鍜屽涔犱汉绫荤殑璇█锛屽叿澶囧杞璇濈殑鑳藉姏",
       "describe": "鎴戝彲浠ョ悊瑙e拰瀛︿範浜虹被鐨勮瑷�锛屽叿澶囧杞璇濈殑鑳藉姏锛岀幇鍦ㄥ拰鎴戝紑濮嬩氦娴佸惂锝�",
       "rank": 96,
-      "dialog": []
+      "dialog": [
+        {
+          "id": "90d53372-9c02-11ef-bf6b-0242ac160006",
+          "chat_id": "90d53372-9c02-11ef-bf6b-0242ac160006",
+          "chat_type": "chat",
+          "agentType": 1
+        }
+      ]
     },
     {
       "id": 5,
@@ -79,7 +93,14 @@
       "desc": "鎮ㄥ彲浠ヤ笂浼犳枃妗f垨娣诲姞鏁版嵁搴撳湴鍧�锛屽皬鏁板彲閽堝浣犳枃妗g殑鏁版嵁杩涜鍒嗘瀽锛屽苟鐢熸垚鎸囧畾鐨勫浘琛�",
       "describe": "鎮ㄥ彲浠ヤ笂浼犳枃妗f垨娣诲姞鏁版嵁搴撳湴鍧�锛屽皬鏁板彲閽堝浣犳枃妗g殑鏁版嵁杩涜鍒嗘瀽锛屽苟鐢熸垚鎸囧畾鐨勫浘琛�",
       "rank": 95,
-      "dialog": []
+      "dialog": [
+        {
+          "id": "basic_excel_talk",
+          "chat_id": "basic_excel_talk",
+          "chat_type": "excelTalk",
+          "agentType": 1
+        }
+      ]
     },
     {
       "id": 6,
@@ -89,7 +110,14 @@
       "desc": "鍩轰簬鎮ㄤ笂浼犵殑鍥剧墖锛岀敓鎴愬搴旂殑鏂囧瓧鎻忚堪骞跺熀浜庡浘鐗囧唴瀹瑰疄鐜伴棶绛斻��",
       "describe": "鍩轰簬鎮ㄤ笂浼犵殑鍥剧墖锛岀敓鎴愬搴旂殑鏂囧瓧鎻忚堪骞跺熀浜庡浘鐗囧唴瀹瑰疄鐜伴棶绛斻��",
       "rank": 94,
-      "dialog": []
+      "dialog": [
+        {
+          "id": "9d75142a-66eb-4e23-b7d4-03efe4584915",
+          "chat_id": "9d75142a-66eb-4e23-b7d4-03efe4584915",
+          "chat_type": "imageTalk",
+          "agentType": 4
+        }
+      ]
     },
     {
       "id": 7,
@@ -99,7 +127,14 @@
       "desc": "鎮ㄥ彲浠ヤ笂浼犳枃妗o紝灏忔暟鑳介拡瀵瑰崟鏂囨。鎴栧涓枃妗e唴瀹硅嚜鍔ㄥ嚭棰橈紝楂樻晥渚挎嵎鐨勫府鍔╀綘寤虹珛绉佷汉棰樺簱銆�",
       "describe": "鎮ㄥ彲浠ヤ笂浼犳枃妗o紝灏忔暟鑳介拡瀵瑰崟鏂囨。鎴栧涓枃妗e唴瀹硅嚜鍔ㄥ嚭棰橈紝楂樻晥渚挎嵎鐨勫府鍔╀綘寤虹珛绉佷汉棰樺簱銆�",
       "rank": 93,
-      "dialog": []
+      "dialog": [
+        {
+          "id": "basic_paper_talk",
+          "chat_id": "basic_paper_talk",
+          "chat_type": "paperTalk",
+          "agentType": 3
+        }
+      ]
     },
     {
       "id": 8,
@@ -109,7 +144,14 @@
       "desc": "鎮ㄥ彲浠ヤ笂浼犳枃妗o紝灏忔暟鑳介拡瀵瑰崟鏂囨。鎴栧涓枃妗e唴瀹硅嚜鍔ㄥ嚭棰橈紝楂樻晥渚挎嵎鐨勫府鍔╀綘寤虹珛绉佷汉棰樺簱銆�",
       "describe": "鎮ㄥ彲浠ヤ笂浼犳枃妗o紝灏忔暟鑳介拡瀵瑰崟鏂囨。鎴栧涓枃妗e唴瀹硅嚜鍔ㄥ嚭棰橈紝楂樻晥渚挎嵎鐨勫府鍔╀綘寤虹珛绉佷汉棰樺簱銆�",
       "rank": 92,
-      "dialog": []
+      "dialog": [
+         {
+          "id": "basic_question_talk",
+          "chat_id": "basic_question_talk",
+          "chat_type": "questionTalk",
+          "agentType": 3
+        }
+      ]
     },
     {
       "id": 9,
@@ -121,13 +163,13 @@
       "rank": 91,
       "dialog": [
         {
-          "id": "basic_excel_merge",
+          "id": "72a69e47-458d-47f9-b534-1859e5da244f",
           "chat_id": "basic_report_clean",
           "chat_type": "reportWorkflow",
           "agentType": 4
         },
         {
-          "id": "basic_paper_talk",
+          "id": "6eda0700-6273-488d-a97c-88d315bd9d8f",
           "chat_id": "basic_report_clean",
           "chat_type": "reportWorkflow",
           "agentType": 4

--
Gitblit v1.8.0