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();
        }
    }
}
相关推荐
间彧15 分钟前
Spring Boot集成Spring Security 6.x完整指南
java
绝无仅有32 分钟前
面试实战总结:数据结构与算法面试常见问题解析
后端·面试·github
绝无仅有35 分钟前
Docker 面试常见问题及解答
后端·面试·github
程序员爱钓鱼38 分钟前
Go语言100个实战案例-项目实战篇:股票行情数据爬虫
后端·go·trae
IT_陈寒1 小时前
Redis 性能翻倍的 7 个冷门技巧,第 5 个大多数人都不知道!
前端·人工智能·后端
xiezhr1 小时前
用户只需要知道「怎么办」,不需要知道「为什么炸了」
java·api·接口设计规范
xiezhr1 小时前
接口设计18条军规:写给那些半夜被“502”叫醒的人
java·api·restful
你的人类朋友9 小时前
说说签名与验签
后端
databook9 小时前
Manim实现脉冲闪烁特效
后端·python·动效
RainbowSea10 小时前
12. LangChain4j + 向量数据库操作详细说明
java·langchain·ai编程