【chatgpt】学习开源项目chatgpt-web,搭建自己的chatgpt服务,功能非常丰富有打字效果

前言


本文的原文连接是:
https://blog.csdn.net/freewebsys/article/details/130438873

1,开源的chatgpt项目


项目地址:
https://github.com/Chanzhaoyu/chatgpt-web

也有gitee搬运的项目,不知道是不是作者,最近也在更新:
https://gitee.com/boomer001/chanzhaoyu-chatgpt-web

项目从23年2月份开始,到目前项目已经有了很高的星星 20K 了。
项目的前端使用的是vue进行开发的。
项目的后端使用的nodejs 进行开发的,全栈项目了。

而且也官方的docker 镜像,直接配置起来就可以了。

2,项目可以直接使用docker-compose跑起来


从第二步骤讲起,apikey 如何申请,不在这里讨论,大家可以自行解决。

官方也有简单的使用docker-compose 配置,这个整理了下就配置下apikey 就行了:

docker-compose.yaml 配置文件:

services:
  app:
    restart: always
    image: chenzhaoyu94/chatgpt-web # 总是使用 latest ,更新时重新 pull 该 tag 镜像即可
    ports:
      - 3002:3002
    #volumes: #要是想自己修改页面,可以吧dist映射到/app/pulbic目录即可。
    #  - ./chatgpt-web/dist:/app/public
    environment:
      # 二选一
      OPENAI_API_KEY: sk-xxxxxxx
      # 二选一
      # API接口地址,可选,设置 OPENAI_API_KEY 时可用
      OPENAI_API_BASE_URL: http://localhost:3002
      # API模型,可选,设置 OPENAI_API_KEY 时可用
      OPENAI_API_MODEL: gpt-3.5-turbo
      # 访问权限密钥,可选
      AUTH_SECRET_KEY: chat666
      # 超时,单位毫秒,可选
      TIMEOUT_MS: 60000

要是想自己修改页面,可以吧dist映射到/app/pulbic目录即
./chatgpt-web/dist:/app/public
chatgpt-web 就是这个github 项目下载后的地址。

当然也可以直接使用nodejs跑起来,分前后端的,前端项目也需要进行编译。

启动成功:
在这里插入图片描述
有登陆授权提示,需要输入配置的 auth 密码 比如chat666 。
要是错登陆不进去,当然这个是一个简单的授权。
在这里插入图片描述

登陆成功之后就可以使用了
在这里插入图片描述
带打字模式回答问题,这个地方就需要注意了。

3,关于打字模式SSE, octet-stream (打字特效)


SSE 是指“Server-Sent Events”,它是一种基于 HTTP 的服务器推送技术。使用 SSE 可以让服务器向客户端发送事件流,从而实现实时的数据更新和通知功能。SSE 协议基于 HTML5 标准,支持跨域通信,并且与 Web Sockets 不同,它是一种单向通信方式,即只能由服务器向客户端发送消息。在浏览器中,可以通过 JavaScript 的 EventSource API 来实现对 SSE 事件流的监听和处理。

H5的一个新协议,这里需要注意下,如果是直接暴露端口不用管。
但是要是需要使用nginx进行转发的就需要修改nginx配置了。

这里折腾了几天才弄明白,官方也给了解决办法,配置nginx的 octet-stream (打字特效)配置:

参考这个:
https://github.com/Chanzhaoyu/chatgpt-web/issues/402

也就是需要在nginx 配置后端接口:

	location ~ ^/api/chat-process {
    
    

        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";

		# 流式输出
		chunked_transfer_encoding on;  # 开启分块传输编码
		tcp_nopush on;  # 开启TCP NOPUSH选项,禁止Nagle算法
		tcp_nodelay on;  # 开启TCP NODELAY选项,禁止延迟ACK算法
		keepalive_timeout 300;  # 设定keep-alive超时时间为65秒
	
		proxy_pass http://app:3002;

	}

返回的数据格式是数组,照回车 \n 进行区分,然后才是数据。
返回一个或者几个字词然后,界面上就有打字效果了:

在这里插入图片描述

项目中的处理函数:

const fetchChatAPIOnce = async () => {
    
    
      await fetchChatAPIProcess<Chat.ConversationResponse>({
    
    
        prompt: message,
        options,
        signal: controller.signal,
        onDownloadProgress: ({
     
      event }) => {
    
    
          const xhr = event.target
          const {
    
     responseText } = xhr
          // Always process the final line
          const lastIndex = responseText.lastIndexOf('\n', responseText.length - 2)
          let chunk = responseText
          if (lastIndex !== -1)
            chunk = responseText.substring(lastIndex)
          try {
    
    
            const data = JSON.parse(chunk)
            updateChat(
              +uuid,
              index,
              {
    
    
                dateTime: new Date().toLocaleString(),
                text: lastText + (data.text ?? ''),
                inversion: false,
                error: false,
                loading: true,
                conversationOptions: {
    
     conversationId: data.conversationId, parentMessageId: data.id },
                requestOptions: {
    
     prompt: message, options: {
    
     ...options } },
              },
            )

            if (openLongReply && data.detail.choices[0].finish_reason === 'length') {
    
    
              options.parentMessageId = data.id
              lastText = data.text
              message = ''
              return fetchChatAPIOnce()
            }
          }
          catch (error) {
    
    
            //
          }
        },
      })

项目中一共有4个接口:

/api/config 配置的接口,返回使用情况,配置信息。
/api/session 返回模型信息。这个成 功之后才可以进行聊天。
/api/verify 校验用户登陆状态。
/api/chat-process 最重要的用户聊天对话消息处理,使用了 SSE 模拟打字。

同时这个项目中还可以开启多个对话,记录上次对话内容。
比如先问上海的景点:
在这里插入图片描述
然后在问三个最好的,这时候chatgpt 就知道是上海的景点:
在这里插入图片描述

这个前端样式使用 naiveui

https://www.naiveui.com/zh-CN/os-theme
github 地址:
https://github.com/tusen-ai/naive-ui

只是手机端和pc端样式自适应。

4,关于内容存储


这个项目采取的是将相关的聊天信息存储到本地文件中。
在localstorage 中,优点是效率高,速度快。

在 uitls/storage/local.ts 使用的是

window.localStorage.setItem(key, json)
window.localStorage.getItem(key)
window.localStorage.removeItem(key)
window.localStorage.clear()

存储相关的信息,都存储到了一个字段中了。
分chat和 history 两个属性。
在这里插入图片描述
active 是激活的当前会话id

就是当前的时间戳:

  chatStore.addHistory({
    
     title: 'New Chat', uuid: Date.now(), isEdit: false })

这里鉴权是做的写死的设置:

service.interceptors.request.use(
  (config) => {
    
    
    const token = useAuthStore().token
    if (token)
      config.headers.Authorization = `Bearer ${
     
     token}`
    return config
  },
  (error) => {
    
    
    return Promise.reject(error.response)
  },
)

直接在head里面写死的,但是这样并不安全。
服务器授权如果使用 jwt 可以修改 verify 接口。
服务端返回 jwt 的授权,然后本地存储。

在拦截器里面都使用 jwt的鉴权,或者是直接存储到 cookie当中也行,但是会有跨域的问题需要解决。

5,总结


最近在使用chatgpt发现确实可以非常方便的提高效率的。
对于开发上面的各种问题的解决也是帮助非常大的。
同时在使用大模型的服务上也会有很多的工程问题需要解决。
一些登陆授权的还是常用的软件知识,都需要掌握进行学习。

这个开源项目非常的好!非常值得推荐!

本文的原文连接是:
https://blog.csdn.net/freewebsys/article/details/130438873

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/freewebsys/article/details/130438873