当前位置:   article > 正文

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

java调用chatgpt接口

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

  1. 因为对vscode不熟悉,前段界面我也是在idea里写的,先看一下效果图是这样,比较简陋请添加图片描述

我直接上代码,关于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>

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228

后端代码如下

@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;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76

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

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/372396
推荐阅读
相关标签
  

闽ICP备14008679号