Bläddra i källkod

上传dify文件

zhaoqingang 1 år sedan
förälder
incheckning
1ab90de913
4 ändrade filer med 32 tillägg och 24 borttagningar
  1. 6 0
      app/api/agent.py
  2. 2 2
      app/api/chat.py
  3. 15 15
      app/api/files.py
  4. 9 7
      app/service/difyService.py

+ 6 - 0
app/api/agent.py

@@ -64,6 +64,12 @@ async def chat_list(
         result = [item.to_dict() for item in records]
         return ResponseList(code=200, msg="", data=result)
 
+    elif agent.agent_type == AgentType.DIFY:
+        offset = (page - 1) * limit
+        records = db.query(SessionModel).filter(SessionModel.agent_id == agent_id, SessionModel.tenant_id==current_user.id).order_by(SessionModel.create_date.desc()).offset(offset).limit(limit).all()
+        result = [item.to_dict() for item in records]
+        return ResponseList(code=200, msg="", data=result)
+
     else:
         return ResponseList(code=200, msg="Unsupported agent type")
 

+ 2 - 2
app/api/chat.py

@@ -314,7 +314,7 @@ async def handle_client(websocket: WebSocket,
                     except Exception as e:
                         logger.error(e)
                     complete_response = ""
-                    async for rag_response in dify_service.chat(token, chat_id, question, upload_file_id, conversation_id):
+                    async for rag_response in dify_service.chat(token, current_user.id, question, upload_file_id, conversation_id):
                         try:
                             if rag_response[:5] == "data:":
                                 # 如果是,则截取掉前5个字符,并去除首尾空白符
@@ -326,7 +326,7 @@ async def handle_client(websocket: WebSocket,
                             try:
                                 data = json.loads(complete_response)
                                 # data = json_data.get("data")
-                                if "answer" not in  data or isinstance(data["answer"], dict):  # 信息过滤
+                                if "answer" not in  data or not isinstance(data["answer"], dict):  # 信息过滤
                                     continue
                                 else:  # 正常输出
                                     answer = data.get("answer", "")

+ 15 - 15
app/api/files.py

@@ -94,21 +94,21 @@ async def upload_files(
             service = BasicService(base_url=settings.basic_paper_url)
             result = await service.paper_file_upload(chat_id, file.filename, file_content)
 
-        elif agent.agent_type == AgentType.DIFY:
-            file = file[0]
-            # 读取上传的文件内容
-            try:
-                file_content = await file.read()
-            except Exception as e:
-                return Response(code=400, msg=str(e))
-            dify_service = DifyService(base_url=settings.dify_base_url)
-            try:
-                token = get_bisheng_token(db, current_user.id)
-                result = await dify_service.upload(token, file.filename, file_content)
-            except Exception as e:
-                raise HTTPException(status_code=500, detail=str(e))
-            result["file_name"] = file.filename
-            return Response(code=200, msg="", data=result)
+    elif agent.agent_type == AgentType.DIFY:
+        file = file[0]
+        # 读取上传的文件内容
+        try:
+            file_content = await file.read()
+        except Exception as e:
+            return Response(code=400, msg=str(e))
+        dify_service = DifyService(base_url=settings.dify_base_url)
+        try:
+            token = get_bisheng_token(db, current_user.id)
+            result = await dify_service.upload(token, file.filename, file_content, current_user.id)
+        except Exception as e:
+            raise HTTPException(status_code=500, detail=str(e))
+        result["file_name"] = file.filename
+        return Response(code=200, msg="", data=result)
 
         return Response(code=200, msg="", data=result)
 

+ 9 - 7
app/service/difyService.py

@@ -62,7 +62,7 @@ class DifyService:
                 raise Exception("Authorization header not found in response")
             return authorization
 
-    async def chat(self, token: str, chat_id: str,  message: str, upload_file_id: str, conversation_id: str):
+    async def chat(self, token: str, user_id: int,  message: str, upload_file_id: str, conversation_id: str):
 
         target_url = f"{self.base_url}/v1/chat-messages"
         files = []
@@ -80,7 +80,7 @@ class DifyService:
             "query": message,
             "response_mode": "streaming",
             "conversation_id": conversation_id,
-            "user": chat_id,
+            "user": str(user_id),
             "files": files
         }
 
@@ -114,17 +114,19 @@ class DifyService:
                 return data
             return data.get("message", [])
 
-    async def upload(self, token: str, filename: str, file: bytes) -> dict:
-        url = f"{self.base_url}/console/api/files/upload"
+    async def upload(self, token: str, filename: str, file: bytes, user_id) -> dict:
+        url = f"{self.base_url}/v1/files/upload"
         headers = {
-            'Content-Type': 'application/json',
+            # 'Content-Type': 'application/json',
             'Authorization': f'Bearer {token}'
         }
-
+        data = {
+            'user': str(user_id)
+        }
         # 创建表单数据,包含文件
         files = {"file": (filename, file)}
         async with httpx.AsyncClient() as client:
-            response = await client.post(url, headers=headers, files=files)
+            response = await client.post(url, headers=headers, files=files, data=data)
             data = self._handle_response(response)
             # file_path = data.get("file_path", "")
             result = {