浅尝对接 ChatGPT 与 DDD 工程

文章对比了MVC和DDD两种架构在项目组织结构上的差异,介绍了如何创建SpringBoot的Maven父子工程来管理子模块。同时,详细讲解了如何对接ChatGPTAPI,包括获取API密钥、设置请求头和请求体,以及处理可能出现的网络异常。最后,提供了一个Java代码示例,展示如何调用OpenAI接口进行问答交互。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. SpringBoot DDD 工程

  • MVC 架构与 DDD 架构简单对比
    • MVC 架构:老项目将 controller、service、manager、dao、bean 按照系统模块分在一起,随着项目发展每个包中对象逐渐膨胀,导致维护困难、bug 难查
    • DDD 架构:新项目按照功能模块划分包,每个包维护自己的 controller、service、manager、dao、bean,每次进行开发与维护仅需找到对应功能包即可

在这里插入图片描述

  • 创建 Maven 的父子工程
    • 子工程使用:New Module 创建,每个子工程也是一个 Maven
    • 父子工程 Maven 项目的 <groupId> 相同,<artifactId> 不同
    • 父工程 pom.xml 文件使用 <modules><module> 添加子工程的 <artifactId>
    • 父工程 pom.xml 文件使用 <dependencyManagement> 定义子工程依赖的版本号

2. 对接ChatGPT

  1. ChatGPT 文档:https://platform.openai.com/docs/quickstart/introduction
  2. 创建 API 密钥(注意保密,同时有调用限制,超过需要付费)
  3. 使用 Http Post 连接,注意请求头和请求体参数
  4. 即使挂上全局连接规则,也可能调用超时、SSL 握手失败等异常,可以尝试代理
    javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
    Caused by: java.io.EOFException: SSL peer shut down incorrectly

3. 代码

  • 对接 ChatGPT OpenAI 接口
public class OpenAI implements IOpenAI {

    Logger logger = LoggerFactory.getLogger(OpenAI.class);

    /**
     * 调用 OpenAI 接口回答问题,返回过节
     */
    @Override
    public String doChatGPT(String url, String openAiKey, String question) throws IOException {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        // 代理地址;open.aiproxy.xyz、open2.aiproxy.xyz
        HttpPost httpPost = new HttpPost(url);

        httpPost.setHeader("Content-Type", "application/json");
        httpPost.setHeader("Authorization", "Bearer " + openAiKey);

        String paramJson = "{ \"model\": \"gpt-3.5-turbo\", \"messages\": [{\"role\": \"user\", \"content\": \""
                + question + "\"}], \"temperature\": 0.7, \"max_tokens\": 1024}";
        StringEntity stringEntity = new StringEntity(paramJson, ContentType.create("text/json", "UTF-8"));
        httpPost.setEntity(stringEntity);

        /**
         * 返回参数:
         * answerResponse:HttpResponseProxy{HTTP/1.1 200 OK [Server: nginx/1.18.0 (Ubuntu), Date: Wed, 29 Mar 2023
         * 15:36:21 GMT, Content-Type: application/json, Content-Length: 331, Connection: keep-alive,
         * Access-Control-Allow-Origin: *, Cache-Control: no-cache, must-revalidate, Openai-Model:
         * gpt-3.5-turbo-0301, Openai-Organization: user-bh0urjiu2k9hkov1mvwdxgph, Openai-Processing-Ms: 1515,
         * Openai-Version: 2020-10-01, Strict-Transport-Security: max-age=15724800; includeSubDomains,
         * X-Ratelimit-Limit-Requests: 20, X-Ratelimit-Remaining-Requests: 19, X-Ratelimit-Reset-Requests: 3s,
         * X-Request-Id: da3fb352a87ae33b10d11f309dc1c200] ResponseEntityProxy{[Content-Type: application/json,
         * Content-Length: 331,Chunked: false]}}
         * 2023-03-29 23:36:22.007  INFO 26301 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor  :
         * Shutting down ExecutorService 'applicationTaskExecutor'
         */
        CloseableHttpResponse response = httpClient.execute(httpPost);
        logger.info("response:{}", response);

        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String json = EntityUtils.toString(response.getEntity());
            logger.info("response.getEntity:{}", json);

            OpenAIAnswer openAIAnswer = JSON.parseObject(json, OpenAIAnswer.class);

            StringBuilder answers = new StringBuilder();
            List<Choices> choicesList = openAIAnswer.getChoices();
            for (Choices choices : choicesList) {
                answers.append(choices.getText());
            }

            return openAIAnswer.toString();
        } else {
            throw new RuntimeException("doChatGPT Api Error Code is " + response.getStatusLine().getStatusCode());
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值