SpringBoot集成ChatGPT

首先你要有一个openai的账号,然后申请apikey,并且里面有一定的额度。

然后上代码

添加依赖

复制代码
        <dependency>
            <groupId>com.github.plexpt</groupId>
            <artifactId>chatgpt</artifactId>
            <version>4.0.5</version>
        </dependency>

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-http</artifactId>
            <version>5.8.18</version>
        </dependency>

加点魔法

连接

java 复制代码
import cn.hutool.http.*;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.plexpt.chatgpt.util.Proxys;
import org.springframework.web.bind.annotation.*;

import java.net.Proxy;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/xxx")
public class ChatGPTController {
    @GetMapping("/xxx")
    public static void chat(@RequestParam("content")String content) {
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        JSONObject json = new JSONObject();
        json.set("model", "gpt-3.5-turbo");
        JSONObject msg = new JSONObject();
        msg.set("role", "user");
        msg.set("content",content);
        JSONArray array = new JSONArray();
        array.add(msg);
        json.set("messages", array);
        json.set("temperature", 0);
        json.set("max_tokens", 2048);
        json.set("top_p", 1);
        json.set("frequency_penalty", 0.0);
        json.set("presence_penalty", 0.0);
        try {
            Proxy proxy = Proxys.http("地址", 端口号);
            HttpResponse response = HttpRequest.post("https://api.openai.com/v1/chat/completions")
                    .headerMap(headers, false)
                    .bearerAuth("apikey")
                    .setProxy(proxy)
                    .body(String.valueOf(json))
                    .timeout(600000)
                    .execute();
            System.out.println(response.body());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
相关推荐
@淡 定22 分钟前
异常处理最佳实践
java
一起养小猫24 分钟前
LeetCode100天Day1-字符串匹配与Z字形变换
java·leetcode
白宇横流学长26 分钟前
基于SpringBoot实现的冬奥会科普平台设计与实现【源码+文档】
java·spring boot·后端
APIshop37 分钟前
Java爬虫1688详情api接口实战解析
java·开发语言·爬虫
Python编程学习圈1 小时前
Asciinema - 终端日志记录神器,开发者的福音
后端
bing.shao1 小时前
Golang 高并发秒杀系统踩坑
开发语言·后端·golang
壹方秘境1 小时前
一款方便Java开发者在IDEA中抓包分析调试接口的插件
后端
Evan芙1 小时前
Tomcat内存机制以及按场景调优
java·tomcat
总爱写点小BUG2 小时前
打印不同的三角形(C语言)
java·c语言·算法
brzhang2 小时前
A2UI:但 Google 把它写成协议后,模型和交互的最后一公里被彻底补全
前端·后端·架构