使用java对接chatgpt(含全部代码)

使用java对接chatgpt(含全部代码)

  1. 因为对vscode不熟悉,前段界面我也是在idea里写的,先看一下效果图是这样,比较简陋使用java对接chatgpt(含全部代码)_第1张图片

我直接上代码,关于chatgpt前端的html,对了因为这个是我用之前写的匿名群聊改的,可能有多余的就是样式没去掉,如果有人用的话自己看着可以优化下
前端这方面还有两个问题还没有优化我说一下,就是chatgpt返回的有markdown样式的话不能正常解析,二一个是换行有问题
不过不影响大方面使用,后期我会优化的

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0, maximum-scale=1.0,user-scalable=no,minimal-ui">
    <title>chatgpt问答</title>
    <link rel="icon" href="./../images/favico.ico">
    <!--不同屏幕尺寸根字体设置-->
    <script src="./../js/base.js"></script>
    <!--element-ui的样式-->
    <link rel="stylesheet" href="../../backend/plugins/element-ui/index.css"/>
    <!--引入vant样式-->
    <link rel="stylesheet" href="../styles/vant.min.css"/>
    <!-- 引入样式  -->
    <!--<link rel="stylesheet" href="../styles/index.css"/>-->
    <!--本页面内容的样式-->
    <link rel="stylesheet" href="./../styles/login.css"/>

    <style scoped>
        .chat {
            font-size: 20px;
            padding-left: 5%;
            padding-right: 5%;
            padding-top: 20px;
            position: absolute;
            height: 75%;
            width: 90%;
            /*height: 500px; !* 设置内容高度 *!*/
            overflow-y: scroll; /* 启用垂直滚动 */
            overflow-x: hidden; /* 禁用水平滚动 */
        }

        .chat-header .back-btn {
            margin-right: 16px;
            cursor: pointer;
        }

        .chat-header .user-avatar {
            margin-right: 12px;
            width: 40px;
            height: 40px;
            border-radius: 50%;
            overflow: hidden;
        }

        .message-user img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            object-position: center;
        }

        .chat-input {
            flex: 1;
            /*height: 40px;*/
            /*margin-right: 10px;*/
            padding-bottom: 10px;
        }

        form {
            position: fixed;
            /*padding-top: 20px;*/
            /*padding-left: 5%;*/
            bottom: 0;
            width: 90%
            /*padding-right: 5%;*/
        }

        p {
            color: black;
            font-size: 15px;
            margin-bottom: 10px;
        }

        .el-textarea {
            padding-right: 20px;
            display: inline-block;
            width: 70%;
        }

        .chat-input .el-button el-button--primary {
            margin-left: 10px;
        }

        .message-body img {
            width: 50%;
            height: 50%;
            object-fit: cover;
        }

        .avatar {
            margin-right: 12px;
            /*width: 40px;*/
            /*height: 40px;*/
            /*border-radius: 50%;*/
            overflow: hidden;
            float: left; /* 将用户头像框浮动到左侧 */
            margin-top: 5px; /* 稍微调整一下上边距,使其垂直居中 */
        }
        .message-content {
            overflow: hidden;
        }
        .message-content span{
            vertical-align: super;
        }
        .avatar img {
            width: 46px;
            height: auto;
        }

        .el-message-box {
            width: 300px;
        }

        [v-cloak] {
            display: none;
        }
    </style>


</head>
<body>

    <div class="chat" id="login" >
        <div class="chat-history" v-cloak>
            <div class="chat-bubble" v-for="message in messages" :key="message.id">
                <div class="message-content" v-if='message.role=="assistant"'>
                    <img :src="'./../images/1.ico'" alt="请等待">
                    <span>{{message.name}}</span>
                    <div class="content">{{message.content}}</div>
                </div>
                <div class="message-content" v-else>
                    <img :src="'./../images/2.ico'">
                    <span style="color: blue">{{message.name}}</span>
                    <div class="content">{{message.content}}</div>

                </div>
                <hr/>
            </div>
            <a id="myElement"></a>
        </div>

        <form>
            <div class="chat-input">
                <el-input :disabled="isButtonDisabled"
                          type="textarea"
                          placeholder="发送消息对chatgpt提问..."
                          v-model="input"
                ></el-input>
                <el-button type="primary"  @click="sendMessage">发送</el-button>
            </div>
        </form>
    </div>

<!-- 开发环境版本,包含了有帮助的命令行警告 -->
<script src="../../backend/plugins/vue/vue.js"></script>
<!-- 引入组件库 -->
<script src="../../backend/plugins/element-ui/index.js"></script>
<!-- 引入vant样式 -->
<script src="./../js/vant.min.js"></script>
<!-- 引入axios -->
<script src="../../backend/plugins/axios/axios.min.js"></script>
<script src="./../js/request.js"></script>
<script src="./../api/login.js"></script>

</body>

<script>
    new Vue({
        el: "#login",
        data() {
            return {
                lock:true,
                input:'',
                messages:[
                ],
                isButtonDisabled: false,
                isInteger: 0
            };
        },
        created() {
            let uuid = localStorage.getItem('uuid');
            if (uuid == null) {
                uuid = Math.random().toString(36).substring(2, 10);
                localStorage.setItem('uuid', uuid);
            }
        },
        watch: {
            messages(value) {
                if (this.isInteger != value.length) {
                    this.isInteger = value.length;
                    this.scrollToEnd();
                }
            },
        },
        methods:{
            async sendMessage(){
                if (this.isButtonDisabled) {
                    return;
                }
                this.isButtonDisabled = true;

                let uuid = localStorage.getItem('uuid');
                if(this.input!=null&&this.input!=''&&this.lock==true){
                    this.lock=false;
                    this.messages.push({role:"user",content:this.input,name:"笨笨的杰瑞"});

                    $axios.post("/chatgpt", { userId: uuid, message: this.input })
                        .then((res) => {
                            this.messages.push({role:'assistant',content:res,name:"聪明的汤姆"});
                            this.lock=true;
                            this.isButtonDisabled = false;
                        });
                    this.input='';
                }
            },
            scrollToEnd() {
                const element = document.getElementById('myElement');
                element.scrollIntoView(false);
            }
        }
    });
</script>
</html>

后端代码如下

@RestController
@RequestMapping("/chatgpt")
public class chatgptController {
    private final String OPENAI_API_KEY = "你的sk";
    private final String OPENAI_API_URL = "https://api.openai.com/v1/chat/completions";
    private Map<String, List<String>> userSessions = new HashMap<>();

    @PostMapping
    public String chatWithGPT(@RequestBody ChatRequest chatRequest) {

        //获取用户的标识和消息
        String userId = chatRequest.getUserId();
        String message = chatRequest.getMessage();
        // 检查用户会话是否存在
        if (!userSessions.containsKey(userId)) {
            //第一次进来肯定不存在会话中,这时候我们放进去
            userSessions.put(userId, new ArrayList<>());
        }
        //把发送的消息扔进这个人的list中
        List<String> sessionMessages = userSessions.get(userId);
        sessionMessages.add(message);

        // 构建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBearerAuth(OPENAI_API_KEY);

        // 构建请求体
        String requestBody = buildRequestBody(userId, sessionMessages);

        // 发送请求
        RestTemplate restTemplate = new RestTemplate();
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        //我用的呆里端口33210,这个要改
        factory.setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 33210)));
        restTemplate.setRequestFactory(factory);

        HttpEntity<String> request = new HttpEntity<>(requestBody, headers);
        ResponseEntity<String> response = restTemplate.postForEntity(OPENAI_API_URL,request, String.class);
        // 提取回复消息
        String responseBody = response.getBody();
        String reply = extractReplyFromResponse(responseBody);
        System.out.println("-------------------"+reply+"--------------------");

        //把回复消息也存进当前用户的的list中,方便上下文记忆
        sessionMessages.add(reply);

        return reply;
    }

    private String buildRequestBody(String userId, List<String> sessionMessages) {
        JSONArray messagesArray = new JSONArray();
        for (String message : sessionMessages) {
            JSONObject messageObj = new JSONObject();
            messageObj.put("role", "user");
            messageObj.put("content", message);
            messagesArray.add(messageObj);
        }

        JSONObject requestBodyObj = new JSONObject();
        requestBodyObj.put("model", "gpt-3.5-turbo");
        requestBodyObj.put("messages", messagesArray);

        return requestBodyObj.toString();
    }

    private String extractReplyFromResponse(String response) {
        JSONObject jsonObject = JSONUtil.parseObj(response);
        JSONArray choices = jsonObject.getJSONArray("choices");
        JSONObject firstChoice = choices.getJSONObject(0);
        JSONObject message = firstChoice.getJSONObject("message");
        String reply = message.getStr("content");

        return reply;
    }
}

好了,这就是关于通过java调用chatgpt的全部代码了

你可能感兴趣的:(java,java,chatgpt,开发语言)