From 28f41fceef54144cf87eaedd18d09a5a8b9cd5e1 Mon Sep 17 00:00:00 2001
From: zhaoqingang <zhaoqg0118@163.com>
Date: 星期三, 27 十一月 2024 09:40:58 +0800
Subject: [PATCH] dify 多次对话问题

---
 app/api/chat.py |   44 ++++++++++++++++++++++++++++++++------------
 1 files changed, 32 insertions(+), 12 deletions(-)

diff --git a/app/api/chat.py b/app/api/chat.py
index cd5c060..7e85a8e 100644
--- a/app/api/chat.py
+++ b/app/api/chat.py
@@ -1,4 +1,5 @@
 import json
+import re
 import uuid
 
 from fastapi import WebSocket, WebSocketDisconnect, APIRouter, Depends
@@ -250,7 +251,9 @@
                         await websocket.send_json(result)
 
                 else:
+                    logger.error("---------------------excel_talk-----------------------------")
                     async for data in service.excel_talk(question, chat_id):
+                        logger.error(data)
                         output = data.get("output", "")
                         excel_name = data.get("excel_name", "")
                         image_name = data.get("image_name", "")
@@ -293,7 +296,11 @@
         token = settings.dify_api_token
         try:
             async def forward_to_dify():
+
+
                 while True:
+                    image_list = []
+                    is_image = False
                     conversation_id = ""
                     receive_message = await websocket.receive_json()
                     print(f"Received from client {chat_id}: {receive_message}")
@@ -339,8 +346,14 @@
                                     else:  # 姝e父杈撳嚭
                                         answer = data.get("answer", "")
                                         if isinstance(answer, str):
-
-                                            answer_str += answer
+                                            if "![](https://res.stepfun.com/" in answer and image_list:
+                                                is_image = True
+                                                pattern = r'!\[\] *\(https://res\.stepfun\.com/image_gen/[^)]+\)'
+                                                url_image = image_list.pop()
+                                                new_answer = re.sub(pattern, url_image, answer)
+                                                answer_str += new_answer
+                                            else:
+                                                answer_str += answer
 
                                         elif isinstance(answer, dict):
                                             logger.error("鏈煡鏁版嵁浣擄細0---------------------------------")
@@ -349,22 +362,29 @@
 
                                         result = {"message": answer_str, "type": "message"}
                                 elif data.get("event") == "message_end":
-                                    message_files = []
-                                    res_msg = await dify_service.get_session_history(token, data.get("conversation_id"), str(current_user.id))
-                                    if len(res_msg) > 0:
-                                        message_files = res_msg[0].get("message_files")
-
-                                    result = {"message": answer_str, "type": "close", "message_files": message_files}
+                                    images_url = []
+                                    # res_msg = await dify_service.get_session_history(token, data.get("conversation_id"), str(current_user.id))
+                                    # if len(res_msg) > 0:
+                                    #     message_files = res_msg[-1].get("message_files")
+                                    #     for msg_file in message_files:
+                                    #         await  dify_service.save_images(msg_file.get("url"), msg_file.get("id")+".png")
+                                    #         images_url.append(msg_file.get("id"))
+                                    # result = {"message": answer_str, "type": "close"} # , "message_files": images_url
+                                    if image_list and not is_image:
+                                        answer_str += image_list[-1]
+                                    result = {"message": answer_str,
+                                              "type": "close"}  # , "message_files": images_url
                                     try:
                                         SessionService(db).update_session(chat_id,
-                                                                          message={"role": "assistant", "content": {"answer":answer_str, "images":[i.get("url") for i in message_files]}},conversation_id=data.get("conversation_id"))
+                                                                          message={"role": "assistant", "content": {"answer":answer_str, "images":images_url}},conversation_id=data.get("conversation_id"))
                                     except Exception as e:
                                         logger.error("淇濆瓨dify鐨勪細璇濆紓甯革紒")
                                         logger.error(e)
                                 elif data.get("event") == "message_file":
-
-                                    url = data.get("url", "")
-                                    result = {"message": url, "type": "image"}
+                                    await  dify_service.save_images(data.get("url"), data.get("id") + ".png")
+                                    image_list.append(f"![](/api/files/image/{data.get('id')})")
+                                    # result = {"message": answer_str, "type": "message"}
+                                    continue
                                 else:
                                     continue
                                 await websocket.send_json(result)

--
Gitblit v1.8.0