[Chanzhaoyu/chatgpt-web]希望能增加聊天对话的日志功能

2024-06-26 702 views
6

@Chanzhaoyu 请完善一下chatgpt-web的聊天历史记录日志这一项功能,这很有用!

回答

7

/src/chatgpt/index.ts debug改为ture,可以查看log

5

已经改了,请问这个日志保存在什么地方呢?

4

命令行,你如果在本地就可以直接在启动服务端的cmd里看到,如果在docker里部署,就用docker logs命令去看

8

这个日志里显示的内容并没有包含聊天历史内容:

......

POST https://gpt.pawan.krd/backend-api/conversation { body: { action: 'next', messages: [ [Object] ], model: 'text-davinci-002-render-sha', parent_message_id: '081df437-7a45-45dd-a0de-6707c594b7bb', conversation_id: '70abb172-884a-4824-92a6-990d513b5e28' }, headers: { Authorization: 'Bearer xxxxxxxxxx......', Accept: 'text/event-stream', 'Content-Type': 'application/json' } }

......

2

哈哈,自己把这个功能实现了,加了3行代码,不过还是要感谢@mm519897405 给我提供了思路

0

哈哈,自己把这个功能实现了,加了3行代码,不过还是要感谢@mm519897405 给我提供了思路

请问能够提供增加的三行代码吗?

7

@xieyusi9 请问能够提供增加的三行代码吗?

1

我也想要这个功能。我没有仔细阅读其他代码,我按照上面的路径找debug也没看见,就写了个记录函数粗暴的写入本地文件,共享出来: service/src/chatgpt/index.ts:

import fs from 'fs';
import path from 'path';

/*
* 没错是GPT代写的
* 将请求内容记录到本地文件中
* @param {string} content 要记录的内容
* @param {string} [filename='request_log.txt'] 日志文件名,默认为'request_log.txt'
*/
function logRequestToFile(content, filename = 'request_log.txt') {
 // 构建日志文件的完整路径
 const logFilePath = path.join(__dirname, filename);

 // 获取当前时间戳
 const timestamp = new Date().toISOString();

 // 构建要写入文件的字符串
 const logEntry = `${timestamp} - ${content}\n`;

 // 异步地将日志条目追加到文件中。如果文件不存在,则创建该文件
 fs.appendFile(logFilePath, logEntry, (err) => {
   if (err) {
     console.error('写入日志文件时发生错误:', err);
   } else {
     console.log('请求内容已记录到文件');
   }
 });
}

然后修改chatReplyProcess函数:

async function chatReplyProcess(options: RequestOptions) {
  const { message, lastContext, process, systemMessage, temperature, top_p } = options
  try {
    let options: SendMessageOptions = { timeoutMs }
    logRequestToFile(`Sending message: ${message}`);
    if (apiModel === 'ChatGPTAPI') {
      if (isNotEmptyString(systemMessage))
        options.systemMessage = systemMessage
      options.completionParams = { model, temperature, top_p }
    }

    if (lastContext != null) {
      if (apiModel === 'ChatGPTAPI')
        options.parentMessageId = lastContext.parentMessageId
      else
        options = { ...lastContext }
    }

    const response = await api.sendMessage(message, {
      ...options,
      onProgress: (partialResponse) => {
        process?.(partialResponse)
      },
    })
    logRequestToFile(`Received response: ${JSON.stringify(response.text)}`);
    logRequestToFile(`Received metadata: ${JSON.stringify(response)}`);
    return sendResponse({ type: 'Success', data: response })
  }
  catch (error: any) {
    const code = error.statusCode
    global.console.log(error)
    logRequestToFile(`Error sending message: ${error.message}`);
    if (Reflect.has(ErrorCodeMessage, code))
      return sendResponse({ type: 'Fail', message: ErrorCodeMessage[code] })
    return sendResponse({ type: 'Fail', message: error.message ?? 'Please check the back-end console' })
  }
}

我把回复内容和回复包分别写入了,这个按照需求自己改吧。 注意log文件路径,如果你们保存在项目文件夹下的话是可以被公网访问的,如果被爬出来的话就会暴露你的log信息,我的话无所谓所以我就这么放了。还方便我自己在线查看。顺便把在线查看的html也贴出来:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Display Text File Content</title>
</head>
<body>
    <h1>Log File Content:</h1>
    <div id="text-content">Loading...</div>

    <script>
        if (window.FileReader) {
            const reader = new FileReader();

            fetch('request_log.txt')
                .then(response => response.blob())
                .then(blob => {
                    reader.readAsText(blob);
                })
                .catch(error => {
                    console.error('Error fetching the text file:', error);
                    document.getElementById('text-content').innerText = 'Failed to load content.';
                });

            reader.onload = function(event) {
                document.getElementById('text-content').innerText = event.target.result;
            };
        } else {
            document.getElementById('text-content').innerText = 'Your browser does not support FileReader.';
        }
    </script>
</body>
</html>