对话兼容报错没data前缀,ragflow会话历史传空时创建会话
| | |
| | | while True: |
| | | message = await websocket.receive_json() |
| | | print(f"Received from client {chat_id}: {message}") |
| | | async for rag_response in ragflow_service.chat(token, chat_id, message["chatHistory"]): |
| | | chat_history = message.get('chatHistory', []) |
| | | if len(chat_history) == 0: |
| | | |
| | | chat_history = await ragflow_service.set_session(token, agent_id, message["message"], chat_id, True) |
| | | if len(chat_history) == 0: |
| | | result = {"message": "内部错误:创建会话失败", "type": "close"} |
| | | await websocket.send_json(result) |
| | | continue |
| | | async for rag_response in ragflow_service.chat(token, chat_id, chat_history): |
| | | try: |
| | | print(f"Received from ragflow: {rag_response}") |
| | | json_str = rag_response[5:].strip() |
| | | if rag_response[:5] == "data:": |
| | | # 如果是,则截取掉前5个字符,并去除首尾空白符 |
| | | json_str = rag_response[5:].strip() |
| | | else: |
| | | # 否则,保持原样 |
| | | json_str = rag_response |
| | | json_data = json.loads(json_str) |
| | | data = json_data.get("data") |
| | | if data is True: # 完成输出 |
| | |
| | | answer = json_data.get("retmsg", json_data.get("retcode")) |
| | | result = {"message": "内部错误:" + answer, "type": "stream"} |
| | | else: # 正常输出 |
| | | answer = json_data.get("data", {}).get("answer", "") |
| | | answer = data.get("answer", "") |
| | | result = {"message": answer, "type": "stream"} |
| | | await websocket.send_json(result) |
| | | print(f"Forwarded to client {chat_id}: {result}") |
| | |
| | | ] |
| | | return result |
| | | |
| | | async def set_session(self, token: str, dialog_id: str, name: str, chat_id: str, is_new: bool) -> bool: |
| | | async def set_session(self, token: str, dialog_id: str, name: str, chat_id: str, is_new: bool) -> list: |
| | | url = f"{self.base_url}/v1/conversation/set?dialog_id={dialog_id}" |
| | | headers = { |
| | | "Authorization": token |
| | |
| | | async with httpx.AsyncClient() as client: |
| | | response = await client.post(url, headers=headers, json=data) |
| | | if response.status_code != 200: |
| | | return False |
| | | return True |
| | | |
| | | return [] |
| | | return [{ |
| | | "content": "你好! 我是你的助理,有什么可以帮到你的吗?", |
| | | "role": "assistant" |
| | | }, |
| | | { |
| | | "content": name, |
| | | "doc_ids": [], |
| | | "role": "user" |
| | | }] |