浅尝对接 ChatGPT 与 DDD 工程

1. SpringBoot DDD 工程

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

浅尝对接 ChatGPT 与 DDD 工程_第1张图片

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

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 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());
        }
    }
}

你可能感兴趣的:(新技术,chatgpt,java,开发语言)