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();
        }
    }
}
相关推荐
leobertlan2 小时前
2025年终总结
前端·后端·程序员
面向Google编程2 小时前
从零学习Kafka:数据存储
后端·kafka
易安说AI3 小时前
Claude Opus 4.6 凌晨发布,我体验了一整晚,说说真实感受。
后端
易安说AI3 小时前
Ralph Loop 让Claude无止尽干活的牛马...
前端·后端
易安说AI3 小时前
用 Claude Code 远程分析生产日志,追踪 Claude Max 账户被封原因
后端
JH30734 小时前
SpringBoot 优雅处理金额格式化:拦截器+自定义注解方案
java·spring boot·spring
颜酱4 小时前
图结构完全解析:从基础概念到遍历实现
javascript·后端·算法
Coder_Boy_5 小时前
技术让开发更轻松的底层矛盾
java·大数据·数据库·人工智能·深度学习
invicinble5 小时前
对tomcat的提供的功能与底层拓扑结构与实现机制的理解
java·tomcat
较真的菜鸟5 小时前
使用ASM和agent监控属性变化
java