0

0

怎么使用springboot+chatgpt+chatUI Pro开发智能聊天工具

WBOY

WBOY

发布时间:2023-05-16 21:04:29

|

1955人浏览过

|

来源于亿速云

转载

一、技术介绍

chatgpt-java是一款支持开箱即用的openai java sdk。目前以支持官网全部api。我们赞成使用最新版本的gpt-3.5-turbo和whisper-1模型。

2.Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。这个框架采用特定的配置方式,无需开发人员再定义通用配置。通过这种方式,Spring Boot致力于在蓬勃发展的快速应用开发领域(rapid application development)成为领导者。

3.ChatUI Pro 是在ChatUI 基础组件的基础上,结合阿里小蜜的最佳实践,沉淀和总结出来的一个开箱即用的,可快速搭建智能对话机器人的框架。它简单易上手,通过简单的配置就能搭建出对话机器人;同时它强大易扩展,通过丰富的接口和自定义卡片满足各种定制化需求。

二、项目介绍

本项目采用了GPT-3.5-Turb模型作为基础,通过springboot结合redis、chat-java以及chatUI Pro实现简单的人工智能机器人。因为访问openAI的API返回结果比较慢,项目中当前端将问题请求发送到后端后,后端会将生成一个UUID,返回前端,同时后端也会重新开启一个线程去访问openAI,当openAI返回结果后,后端将UUID做为key,openAI返回的结果做为value存储到redis中。前端会根据后端第一次请求的结果中UUID做为参数每个5s请求一次后端的answer接口,answer接口会根据UUID查询redis是否有值,直到后端answer接口返回结果后前端将结果输出给用户

三、项目搭建

1.创建springboot项目,项目命名mychatgpt。

怎么使用springboot+chatgpt+chatUI Pro开发智能聊天工具

2.导入项目pom的依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.12</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.xyh</groupId>
    <artifactId>mychatgpt</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>mychatgpt</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.apache.logging.log4j</groupId>
                    <artifactId>log4j-api</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.apache.logging.log4j</groupId>
                    <artifactId>log4j-to-slf4j</artifactId>
                </exclusion>
            </exclusions>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
        </dependency>
        <dependency>
            <groupId>com.theokanning.openai-gpt3-java</groupId>
            <artifactId>api</artifactId>
            <version>0.10.0</version>
        </dependency>
        <dependency>
            <groupId>com.theokanning.openai-gpt3-java</groupId>
            <artifactId>service</artifactId>
            <version>0.10.0</version>
        </dependency>
        <dependency>
            <groupId>com.theokanning.openai-gpt3-java</groupId>
            <artifactId>client</artifactId>
            <version>0.10.0</version>
        </dependency>
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.8.12</version>
        </dependency>
        <dependency>
            <groupId>com.unfbx</groupId>
            <artifactId>chatgpt-java</artifactId>
            <version>1.0.5</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.17</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.8</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.2</version>
            <exclusions>
                <exclusion>
                    <groupId>com.baomidou</groupId>
                    <artifactId>mybatis-plus-generator</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.github.yulichang</groupId>
            <artifactId>mybatis-plus-join</artifactId>
            <version>1.4.2</version>
        </dependency>
        <!--集成随机生成数据包 -->
        <dependency>
            <groupId>com.apifan.common</groupId>
            <artifactId>common-random</artifactId>
            <version>1.0.19</version>
        </dependency>
        <!--集成随机生成数据包 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

3.编写chatGPT实现工具类

MusicAI
MusicAI

AI音乐生成工具

下载
package com.xyh.mychatgpt.utils;
import com.unfbx.chatgpt.OpenAiClient;
import com.unfbx.chatgpt.entity.chat.ChatChoice;
import com.unfbx.chatgpt.entity.chat.ChatCompletion;
import com.unfbx.chatgpt.entity.chat.Message;
import com.unfbx.chatgpt.entity.common.Choice;
import com.unfbx.chatgpt.entity.completions.Completion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.List;
/**
 * @author xiangyuanhong
 * @description: TODO
 * @date 2023/3/21上午9:28
 */
@Component
public class ChatGPTUtils {
    @Value("${xyh.openai.key}")
    private  String token;
    @Autowired
    private RedisUtils redisUtils;
    public void ask(String model,String question,String uuid){
        StringBuffer result=new StringBuffer();
        try {
            OpenAiClient openAiClient = new OpenAiClient(token, 3000, 300, 300, null);
            if("GPT-3.5-Turb".equals(model)){
            // GPT-3.5-Turb模型
            Message message=Message.builder().role(Message.Role.USER).content(question).build();
            ChatCompletion chatCompletion = ChatCompletion.builder().messages(Arrays.asList(message)).build();
            List<ChatChoice> resultList = openAiClient.chatCompletion(chatCompletion).getChoices();
            for (int i = 0; i < resultList.size(); i++) {
                result.append(resultList.get(i).getMessage().getContent());
            }
            }else{
                //text-davinci-003/text-ada-003
                Completion completion = Completion.builder()
                        .prompt(question)
                        .model(model)
                        .maxTokens(2000)
                        .temperature(0)
                        .echo(false)
                        .build();
                Choice[] resultList = openAiClient.completions(completion).getChoices();
                for (Choice choice : resultList) {
                    result.append(choice.getText());
                }
            }
        }catch (Exception e) {
            System.out.println(e.getMessage());
            result.append("小爱还不太懂,回去一定努力学习补充知识");
        }
        redisUtils.set(uuid,result.toString());
    }
}

4.开发项目Controller类,用来与前端进行交互

package com.xyh.mychatgpt.controller;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.xyh.mychatgpt.utils.ChatGPTUtils;
import com.xyh.mychatgpt.utils.R;
import com.xyh.mychatgpt.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
/**
 * @author xiangyuanhong
 * @description: TODO
 * @date 2023/2/28下午4:57
 */
@RestController
public class IndexController {
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private ChatGPTUtils chatGPTUtils;
    @GetMapping("/ask")
    public R ask(String question,HttpServletRequest request) {
        String uuid=IdUtil.simpleUUID();
        if (StrUtil.isBlank(question)) {
            question = "今天天气怎么样?";
        }
        String finalQuestion = question;
        ThreadUtil.execAsync(()->{
            chatGPTUtils.ask("GPT-3.5-Turb", finalQuestion,uuid);
        });
        return R.ok().put("data",uuid);
    }
    @GetMapping("/answer")
    public R answer(String uuid){
        String result=redisUtils.get(uuid);
          return R.ok().put("data",result);
    }
}

5.前端页面开发,在项目templates目录创建index.html页面,并引入chatUI pro相关文件

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta name="renderer" content="webkit" />
    <meta name="force-rendering" content="webkit" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0, viewport-fit=cover" />
    <title>滴答小爱</title>
    <link rel="stylesheet" href="//g.alicdn.com/chatui/sdk-v2/0.2.4/sdk.css" rel="external nofollow" >
</head>
<body>
<div id="root"></div>
<script src="//g.alicdn.com/chatui/sdk-v2/0.2.4/sdk.js"></script>
<script src="//g.alicdn.com/chatui/extensions/0.0.7/isv-parser.js"></script>
<script src="js/setup.js"></script>
<script src="js/jquery-3.6.3.min.js"></script>
<script src="//g.alicdn.com/chatui/icons/0.3.0/index.js" async></script>
</body>
</html>

6.创建setup.js实现chatUI Pro与后端通信交换。

var bot = new ChatSDK({
    config: {
        // navbar: {
        //     title: '滴答小爱'
        // },
        robot: {
            avatar: 'images/chat.png'
        },
        // 用户头像
        user: {
            avatar: 'images/user.png',
        },
        // 首屏消息
        messages: [
            {
                type: 'text',
                content: {
                    text: '您好,小爱为您服务,请问有什么可以帮您的?'
                }
            }
        ],
        // 快捷短语
        // quickReplies: [
        //     { name: '健康码颜色',isHighlight:true },
        //     { name: '入浙通行申报' },
        //     { name: '健康码是否可截图使用' },
        //     { name: '健康通行码适用范围' },
        // ],
        // 输入框占位符
        placeholder: '输入任何您想询问的问题',
    },
    requests: {
        send: function (msg) {
            if (msg.type === 'text') {
                return {
                    url: '/ask',
                    data: {
                        question: msg.content.text
                    }
                };
            }
        }
    },
    handlers: {
        /**
         *
         * 解析请求返回的数据
         * @param {object} res - 请求返回的数据
         * @param {object} requestType - 请求类型
         * @return {array}
         */
        parseResponse: function (res, requestType) {
            // 根据 requestType 处理数据
            if (requestType === 'send' && res.code==0) {
                // 用 isv 消息解析器处理数据
                $.ajaxSettings.async=false;
                var answer="";
                var isOK=false;
                while(!isOK){
                    $.get("/answer",{uuid:res.data},function(result){
                        console.log(result.data)
                        if(null != result.data){
                            isOK=true;
                            answer=result.data;
                        }
                    },"json");
                    if(!isOK){
                        sleep(5000);
                    }
                }
                $.ajaxSettings.async=true;
                return [{"_id":res.data,type:"text",content:{text:answer},position:"left"}];
            }
        },
    },
});
function sleep(n) { //n表示的毫秒数
    var start = new Date().getTime();
    while (true) {
        if (new Date().getTime() - start > n) {
            break;
        }
    }
}
bot.run();

一旦完成项目搭建,启动 Spring Boot 项目并访问 http://ip:端口 即可。项目最终效果:http://hyrun.vip/

四、项目展示

怎么使用springboot+chatgpt+chatUI Pro开发智能聊天工具

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

WorkBuddy
WorkBuddy

腾讯云推出的AI原生桌面智能体工作台

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
TypeScript类型系统进阶与大型前端项目实践
TypeScript类型系统进阶与大型前端项目实践

本专题围绕 TypeScript 在大型前端项目中的应用展开,深入讲解类型系统设计与工程化开发方法。内容包括泛型与高级类型、类型推断机制、声明文件编写、模块化结构设计以及代码规范管理。通过真实项目案例分析,帮助开发者构建类型安全、结构清晰、易维护的前端工程体系,提高团队协作效率与代码质量。

49

2026.03.13

Python异步编程与Asyncio高并发应用实践
Python异步编程与Asyncio高并发应用实践

本专题围绕 Python 异步编程模型展开,深入讲解 Asyncio 框架的核心原理与应用实践。内容包括事件循环机制、协程任务调度、异步 IO 处理以及并发任务管理策略。通过构建高并发网络请求与异步数据处理案例,帮助开发者掌握 Python 在高并发场景中的高效开发方法,并提升系统资源利用率与整体运行性能。

89

2026.03.12

C# ASP.NET Core微服务架构与API网关实践
C# ASP.NET Core微服务架构与API网关实践

本专题围绕 C# 在现代后端架构中的微服务实践展开,系统讲解基于 ASP.NET Core 构建可扩展服务体系的核心方法。内容涵盖服务拆分策略、RESTful API 设计、服务间通信、API 网关统一入口管理以及服务治理机制。通过真实项目案例,帮助开发者掌握构建高可用微服务系统的关键技术,提高系统的可扩展性与维护效率。

276

2026.03.11

Go高并发任务调度与Goroutine池化实践
Go高并发任务调度与Goroutine池化实践

本专题围绕 Go 语言在高并发任务处理场景中的实践展开,系统讲解 Goroutine 调度模型、Channel 通信机制以及并发控制策略。内容包括任务队列设计、Goroutine 池化管理、资源限制控制以及并发任务的性能优化方法。通过实际案例演示,帮助开发者构建稳定高效的 Go 并发任务处理系统,提高系统在高负载环境下的处理能力与稳定性。

59

2026.03.10

Kotlin Android模块化架构与组件化开发实践
Kotlin Android模块化架构与组件化开发实践

本专题围绕 Kotlin 在 Android 应用开发中的架构实践展开,重点讲解模块化设计与组件化开发的实现思路。内容包括项目模块拆分策略、公共组件封装、依赖管理优化、路由通信机制以及大型项目的工程化管理方法。通过真实项目案例分析,帮助开发者构建结构清晰、易扩展且维护成本低的 Android 应用架构体系,提升团队协作效率与项目迭代速度。

99

2026.03.09

JavaScript浏览器渲染机制与前端性能优化实践
JavaScript浏览器渲染机制与前端性能优化实践

本专题围绕 JavaScript 在浏览器中的执行与渲染机制展开,系统讲解 DOM 构建、CSSOM 解析、重排与重绘原理,以及关键渲染路径优化方法。内容涵盖事件循环机制、异步任务调度、资源加载优化、代码拆分与懒加载等性能优化策略。通过真实前端项目案例,帮助开发者理解浏览器底层工作原理,并掌握提升网页加载速度与交互体验的实用技巧。

105

2026.03.06

Rust内存安全机制与所有权模型深度实践
Rust内存安全机制与所有权模型深度实践

本专题围绕 Rust 语言核心特性展开,深入讲解所有权机制、借用规则、生命周期管理以及智能指针等关键概念。通过系统级开发案例,分析内存安全保障原理与零成本抽象优势,并结合并发场景讲解 Send 与 Sync 特性实现机制。帮助开发者真正理解 Rust 的设计哲学,掌握在高性能与安全性并重场景中的工程实践能力。

230

2026.03.05

PHP高性能API设计与Laravel服务架构实践
PHP高性能API设计与Laravel服务架构实践

本专题围绕 PHP 在现代 Web 后端开发中的高性能实践展开,重点讲解基于 Laravel 框架构建可扩展 API 服务的核心方法。内容涵盖路由与中间件机制、服务容器与依赖注入、接口版本管理、缓存策略设计以及队列异步处理方案。同时结合高并发场景,深入分析性能瓶颈定位与优化思路,帮助开发者构建稳定、高效、易维护的 PHP 后端服务体系。

619

2026.03.04

AI安装教程大全
AI安装教程大全

2026最全AI工具安装教程专题:包含各版本AI绘图、AI视频、智能办公软件的本地化部署手册。全篇零基础友好,附带最新模型下载地址、一键安装脚本及常见报错修复方案。每日更新,收藏这一篇就够了,让AI安装不再报错!

173

2026.03.04

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Redis6入门到精通超详细教程
Redis6入门到精通超详细教程

共47课时 | 5.6万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号