zhangqian
2024-11-22 0ad20a631808fcc255a8739d0ea27bfe044f4ea0
请求basic_agent换成requests库,保存消息是不再保存中间结果
2个文件已修改
1个文件已删除
137 ■■■■ 已修改文件
app/api/chat.py 17 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
app/api/excel_talk.py 69 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
app/service/basic.py 51 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
app/api/chat.py
@@ -261,10 +261,19 @@
                                    f"&file_type={file_type}")
                        excel_url = build_file_url(excel_name, 'excel')
                        image_url = build_file_url(image_name, 'image')
                        try:
                            SessionService(db).update_session(chat_id, message={"content": output, "role": "assistant"})
                        except Exception as e:
                            logger.error(f"Unexpected error when update_session: {e}")
                        if excel_url or data.get("e", ""):
                            try:
                                SessionService(db).update_session(chat_id,
                                                                  message={
                                                                      "content": output,
                                                                      "excel_url": excel_url,
                                                                      "image_url": image_url,
                                                                      "sql": data.get("sql", ""),
                                                                      "code": data.get("code", ""),
                                                                      "e": data.get("e", ""),
                                                                      "role": "assistant"})
                            except Exception as e:
                                logger.error(f"Unexpected error when update_session: {e}")
                        # 发送结果给客户端
                        data["type"] = "message"
                        data["message"] = output
app/api/excel_talk.py
File was deleted
app/service/basic.py
@@ -1,6 +1,7 @@
import json
import httpx
import requests
from Log import logger
@@ -48,8 +49,6 @@
        url = f"{self.base_url}/exceltalk/upload/files"
        params = {'chat_id': chat_id, 'is_col': '0'}
        async with httpx.AsyncClient() as client:
            response = await client.post(
                url,
@@ -63,28 +62,25 @@
        params = {'chat_id': chat_id}
        data = {"query": question}
        headers = {'Content-Type': 'application/json'}
        buffer = bytearray()
        async with httpx.AsyncClient(timeout=300.0) as client:
            async with client.stream("POST", url, params=params, json=data, headers=headers) as response:
                if response.status_code == 200:
        with requests.post(url, headers=headers, json=data, params=params, timeout=60,
                           stream=True) as response:
            for line in response.iter_lines():
                if line:
                    decoded_line = line.decode("utf-8")
                    try:
                        async for chunk in response.aiter_bytes():
                            json_data = process_buffer(chunk, buffer)
                            if json_data:
                                yield json_data
                                buffer.clear()
                        if decoded_line.startswith("data:"):
                            decoded_line = decoded_line[5:]
                        answer = json.loads(decoded_line)
                        yield answer
                    except GeneratorExit as e:
                        print(e)
                        yield {"message": "内部错误", "type": "close"}
                    finally:
                        # 在所有数据接收完毕后记录日志
                        logger.info("All messages received and processed - over")
                        # 在所有数据接收完毕后返回close
                        yield {"message": "", "type": "close"}
                else:
                    yield f"Error: {response.status_code}"
    async def questions_talk(self, question, chat_id: str):
        logger.error("---------------questions_talk--------------------------")
@@ -102,27 +98,4 @@
    async def questions_talk_word_download(self, file_id: str):
        url = f"{self.base_url}/questions/download/word"
        return await self.download_from_url(url, params={'word_name': file_id})
def process_buffer(data, buffer):
    def try_parse_json(data1):
        try:
            return True, json.loads(data1)
        except json.JSONDecodeError:
            return False, None
    if data.startswith(b'data:'):
        # 删除 'data:' 头
        data = data[5:].strip()
    else:
        pass
    # 直接拼接到缓冲区尝试解析JSON
    buffer.extend(data.strip())
    success, parsed_data = try_parse_json(buffer)
    if success:
        return parsed_data
    else:
        # 解析失败,继续拼接
        return None
        return await self.download_from_url(url, params={'word_name': file_id})