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();
        }
    }
}
相关推荐
IT爱学堂1 小时前
java版数据结构和算法+AI算法和技能学习指南
java·开发语言
evans在进步2 小时前
LeetCode 394:字符串解码——Java 单栈模拟与嵌套解析详解
java·python·leetcode
苍何2 小时前
偷偷分享 DeepSeek Harness 热榜挖到的 2 个实⽤插件
后端
神奇小汤圆2 小时前
面试官问:"你们上线前怎么测Agent系统?上线后怎么知道它好不好?"
后端
FfHUCisI2 小时前
Golang - 信号量模式(Semaphore Pattern)
开发语言·后端·golang
神奇小汤圆2 小时前
Redis 和 MySQL 如何保证数据一致性?先更新数据库还是先删缓存,延迟双删、MQ、Canal 一次讲透
后端
m0_547486662 小时前
《Java程序设计与实践 》全套PPT课件2026
java·开发语言
土司大王3 小时前
LeetCode hto100——字母异位词分组
java·算法·leetcode
犹豫的果冻布丁3 小时前
从零给 DeepSeek Harness 写一个壁纸皮肤插件(已开源)
前端·后端
weixin_431600443 小时前
NestJS 入门(10):日志——为什么常用 Winston?
后端·学习·日志·nest.js·winston