赞
踩
本文将详细介绍如何基于你自己的开源项目搭建一个准实时聊天问答程序,包括微信小程序和H5网页版。
该项目服务端主要使用了Java + Spring Boot + Netty + WebSocket等技术栈,聊天客户端使用的是UniApp来轻松搭建微信小程序和H5网页端。
在开始之前,请确保已经准备好以下环境和工具:
准实时聊天问答程序的架构设计如下:
https://gitee.com/yeeevip/yeee-chatgpt
https://github.com/yeeevip/yeee-chatgpt
使用IDE创建一个新的Spring Boot项目,并添加相关依赖:
<dependencies> ... <!-- 该依赖封装了Netty + websocket,并集成到springboot-starter中 --> <dependency> <groupId>vip.yeee.memo</groupId> <artifactId>common-netty-websocket</artifactId> </dependency> <!-- 引入此依赖为了使用openai的stream模式来快速获取内容 --> <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp-sse</artifactId> </dependency> <!-- 以下两个依赖为服务鉴权依赖 --> <dependency> <groupId>vip.yeee.memo</groupId> <artifactId>common-app-auth-server</artifactId> </dependency> <dependency> <groupId>vip.yeee.memo</groupId> <artifactId>common-app-auth-client</artifactId> </dependency> ... </dependencies>
添加WebSocket的支持后,我们需要编写具体的端点事件方法,如OnOpen、OnMessage等事件,用于实现消息的接收和发送逻辑。
@Component @ServerEndpoint(path = "/ws/airobot/{chatId}", port = "8802", readerIdleTimeSeconds = "15") public class ChatAppWebSocket { @Autowired private ApiChatGptBiz apiChatGptBiz; // ws打开时触发 @OnOpen public void onOpen(Session session, HttpHeaders headers, @PathParam("chatId") String chatId) { apiChatGptBiz.handleWsOnOpen(session, headers, chatId); } // 收到客户端ws消息时触发 @OnMessage public void onMessage(Session session, String msg) { apiChatGptBiz.handleWsOnMessage(session, msg); } // 客户端ws连接关闭时触发 @OnClose public void onClose(Session session) throws IOException { apiChatGptBiz.handleWsOnClose(session); } // 这里主要处理netty的一些事件,如读超时、写超时,可以方便实现心跳检测 @OnEvent public void onEvent(Session session, Object evt) { apiChatGptBiz.handleWsOnEvent(session, evt); } }
根据你的聊天模型实现,添加相关代码将模型集成到服务端中。你可以使用开源的ChatGPT模型,或自行训练一个模型。
具体实现将模型集成到服务端的步骤和代码,根据你使用的具体ChatGPT模型会有所不同,请参考相应的文档和示例。
这里主要调用的是openai的api接口,代码如下:
@Component public class OpenaiApiService { @Autowired private OkHttpClient okHttpClient; @Autowired private OkHttp3Kit okHttp3Kit; // 使用okhttp的sse请求模式来调用会话接口,流式调用的话阻塞影响小性能比较好 public EventSource chatCompletions(Map<String, String> headers, ChatParams params, EventSourceListener eventSourceListener) { try { EventSource.Factory factory = EventSources.createFactory(okHttpClient); ObjectMapper mapper = new ObjectMapper(); String requestBody = mapper.writeValueAsString(params); Request request = new Request.Builder() .url(getApiHost() + "/v1/chat/completions") .post(RequestBody.create(MediaType.parse(ContentType.JSON.getValue()), requestBody)) .headers(Headers.of(headers)) .build(); return factory.newEventSource(request, eventSourceListener); } catch (Exception e) { throw new BizException("chatCompletions error"); } } }
根据你的需求,实现业务逻辑。此处的业务逻辑是处理用户输入的消息,在服务端调用ChatGPT模型生成回复,并将回复发送给客户端。
@Service public class ChatService { ... public void doWsChat(String msg, String chatId, String uid) { WsEventSourceListener listener = new WsEventSourceListener(chatId, uid, msg); String limitUserKey = StrUtil.isNotBlank(chatRedisRepository.getUserOpenIdCache(uid)) ? chatRedisRepository.getUserOpenIdCache(uid) : uid; if (!this.checkLimit(uid, msg, limitUserKey, listener)) { return; } ... ChatParams params = new ChatParams(); List<ChatMessage2> messages = ChatLocalRepository.getChatContext(chatId, chatRedisRepository.getPreRecordCount()); ChatMessage2 chatMessage2 = this.buildUserMessage(msg); messages.add(chatMessage2); params.setMessages(messages); params.setUser(authService.getUserId()); params.setStream(true); listener.setStartTime(new Date()); EventSource eventSource = openaiApiService.chatCompletions(headers(), params, listener); listener.setEventSource(eventSource); ChatAppWsContext.setUserRecentESL(chatId, uid, listener); } ... }
... // 与服务器建立连接 vm.ws = uni.connectSocket({ url: vm.baseWsAddr + '/ws/airobot/' + vm.chatId, header: { 'Utoken': 'Bearer ' + t }, complete: () => { } }) // 处理服务器返回的消息 vm.ws.onMessage(function (e) { ... }) vm.ws.onOpen(function (e) { console.log('ws open') setInterval(function() { if (vm.ws) { vm.ws.send({ data: 'ping' }) } }, 5000); }) ...
微信小程序
H5网页版
本文详细介绍了如何基于Java + Spring Boot + Netty + WebSocket技术栈搭建一个ChatGPT程序,并使用Uniapp开发微信小程序和H5作为客户端。通过完成这个项目,你可以搭建一个功能强大的聊天机器人系统,满足用户的各种需求。希望这篇文章能够帮助你顺利完成ChatGPT程序的搭建与开发!
https://gitee.com/yeeevip/yeee-chatgpt
https://github.com/yeeevip/yeee-chatgpt
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。