Java SpringBoot集成ChatGPT实现AI聊天

前言

ChatGPT已经组件放开了,现在都可以基于它写插件了。但是说实话我还真没想到可以用它干嘛,也许可以用它结合文字语音开发一个老人小孩需要的智能的说话陪伴啥的。
今天我就先分享下SpringBoot结合ChatGPT,先看看对话效果。

一、依赖引入

这个基本上没啥依赖引入哦,我这里就是一个干干净净的SpringBoot项目,引入Hutool的工具包就行了。看看我的整体依赖吧,直接上pom.XML文件。

  1. <?xml version=“1.0” encoding=“UTF-8”?>
  2. <project xmlns=“http://maven.apache.org/POM/4.0.0” xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”
  3.      xsi:schemaLocation=“http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd”>
  4.      <modelVersion>4.0.0</modelVersion>
  5.      <parent>
  6.          <groupId>org.springframework.boot</groupId>
  7.          <artifactId>spring-boot-starter-parent</artifactId>
  8.          <version>3.0.5</version>
  9.          <relativePath/> <!– lookup parent from repository –>
  10.      </parent>
  11.      <groupId>com.xiaotian</groupId>
  12.      <artifactId>superapi</artifactId>
  13.      <version>0.0.1-SNAPSHOT</version>
  14.      <name>superapi</name>
  15.      <description>superapi</description>
  16.      <properties>
  17.          <Java.version>17</java.version>
  18.          <skipTests>true</skipTests>
  19.      </properties>
  20.      <dependencies>
  21.  
  22.          <dependency>
  23.              <groupId>org.springframework.boot</groupId>
  24.              <artifactId>spring-boot-starter-webflux</artifactId>
  25.          </dependency>
  26.  
  27.          <!– Fastjson –>
  28.          <dependency>
  29.              <groupId>com.alibaba</groupId>
  30.              <artifactId>fastjson</artifactId>
  31.              <version>1.2.83</version>
  32.          &lt;/dependency>
  33.  
  34.          <dependency>
  35.              <groupId>cn.hutool</groupId>
  36.              <artifactId>hutool-all</artifactId>
  37.              <version>5.7.21</version>
  38.          </dependency>
  39.  
  40.  
  41.          <dependency>
  42.              <groupId>org.projectlombok</groupId>
  43.              <artifactId>lombok</artifactId>
  44.              <optional>true</optional>
  45.          </dependency>
  46.          <dependency>
  47.              <groupId>org.springframework.boot</groupId>
  48.              <artifactId>spring-boot-starter-test</artifactId>
  49.              <scope>test</scope>
  50.          </dependency>
  51.          <dependency>
  52.              <groupId>io.projectreactor</groupId>
  53.              <artifactId>reactor-test</artifactId>
  54.              <scope>test</scope>
  55.          </dependency>
  56.      </dependencies>
  57.  
  58.      <build>
  59.          <plugins>
  60.              <plugin>
  61.                  <groupId>org.springframework.boot</groupId>
  62.                  <artifactId>spring-boot-maven-plugin</artifactId>
  63.                  <configuration>
  64.                      <excludes>
  65.                      <exclude>
  66.                      <groupId>org.projectlombok</groupId>
  67.                      <artifactId>lombok</artifactId>
  68.                      </exclude>
  69.                      </excludes>
  70.                  </configuration>
  71.              </plugin>
  72.          </plugins>
  73.      </build>
  74.  
  75. </project>
  76.  

二、接口开发

1.项目结构

-1

2.配置文件

  1. ChatGPT:
  2.      connecttimeout: 60000 # HTTP请求连接超时时间
  3.      readtimeout: 60000 # HTTP请求读取超时时间
  4.      variables: # 自定义变量:
  5.      apiKey: youApiKey # 你的 OpenAI 的 API KEY
  6.      model: textdavinci003 # ChartGPT 的模型
  7.      maxTokens: 50 # 最大 Token 数
  8.      temperature: 0.5 # 该值越大每次返回的结果越随机,即相似度越小

3.接口实现代码

GPTRequest

  1. package com.xiaotian.superapi.chatgpt.entity;
  2.  
  3. import lombok.Data;
  4.  
  5. @Data
  6. public class GPTRequest {
  7.      /**
  8.          * 问题
  9.          */
  10.      private String askStr;
  11.  
  12.      /**
  13.          * 回答
  14.          */
  15.      private String replyStr;
  16. }
  17.  

GPTResponse

  1. package com.xiaotian.superapi.chatgpt.entity;
  2.  
  3. import lombok.Data;
  4.  
  5. import java.util.List;
  6.  
  7. /**
  8.      * GPT-3 返回对象
  9.      * @author zhengwen
  10.      */
  11. @Data
  12. public class GPTResponse {
  13.  
  14.      private String id;
  15.  
  16.      private String object;
  17.  
  18.      private String created;
  19.  
  20.      private String model;
  21.  
  22.      private List<GPTChoice> choices;
  23. }

GPTChoice

  1. package com.xiaotian.superapi.chatgpt.entity;
  2.  
  3. import lombok.Data;
  4.  
  5. /**
  6.      * GPT-3 返回choice对象
  7.      * @author zhengwen
  8.      */
  9. @Data
  10. public class GPTChoice {
  11.  
  12.      private String text;
  13.  
  14.      private Integer index;
  15. }

ChatGPTController

  1. package com.xiaotian.superapi.chatgpt.controller;
  2.  
  3. import cn.hutool.json.JSONUtil;
  4. import com.xiaotian.superapi.chatgpt.entity.GPTRequest;
  5. import com.xiaotian.superapi.chatgpt.service.ChartGPTService;
  6. import jakarta.annotation.Resource;
  7. import lombok.extern.slf4j.Slf4j;
  8. import org.springframework.web.bind.annotation.PostMapping;
  9. import org.springframework.web.bind.annotation.RequestBody;
  10. import org.springframework.web.bind.annotation.RequestMapping;
  11. import org.springframework.web.bind.annotation.RestController;
  12.  
  13. /**
  14.      * GPT-3接口
  15.      *
  16.      * @author zhengwen
  17.      */
  18.  
  19. @Slf4j
  20. @RestController
  21. @RequestMapping(“/chatGpt”)
  22. public class ChatGPTController {
  23.  
  24.      @Resource
  25.      private ChartGPTService chartGPTService;
  26.  
  27.      /**
  28.          * openAI GPT-3
  29.          *
  30.          * @param gptRequest 条件对象
  31.          * @return 出参对象
  32.          */
  33.      @PostMapping(“/askAi”)
  34.      public String askAi(@RequestBody GPTRequest gptRequest) {
  35.  
  36.          String replyStr = chartGPTService.send(gptRequest.getAskStr());
  37.  
  38.          gptRequest.setReplyStr(replyStr);
  39.  
  40.          return JSONUtil.toJsonStr(gptRequest);
  41.      }
  42. }
  43.  

ChartGPTService

  1. package com.xiaotian.superapi.chatgpt.service;
  2.  
  3. public interface ChartGPTService {
  4.  
  5.      String send(String prompt);
  6. }

ChartGPTServiceImpl

  1. package com.xiaotian.superapi.chatgpt.service.impl;
  2.  
  3. import cn.hutool.http.Header;
  4. import cn.hutool.http.HttpResponse;
  5. import cn.hutool.http.HttpUtil;
  6. import cn.hutool.json.JSONObject;
  7. import cn.hutool.json.JSONUtil;
  8. import com.xiaotian.superapi.chatgpt.entity.GPTResponse;
  9. import com.xiaotian.superapi.chatgpt.service.ChartGPTService;
  10. import lombok.extern.slf4j.Slf4j;
  11. import org.springframework.beans.factory.annotation.Value;
  12. import org.springframework.stereotype.Service;
  13.  
  14. import java.util.HashMap;
  15. import java.util.Map;
  16.  
  17. @Slf4j
  18. @Service
  19. public class ChartGPTServiceImpl implements ChartGPTService {
  20.  
  21.      @Value(“${ChatGPT.variables.apiKey}”)
  22.      private String apiKey;
  23.  
  24.      @Value(“${ChatGPT.variables.maxTokens}”)
  25.      private String maxTokens;
  26.  
  27.      @Value(“${ChatGPT.variables.model}”)
  28.      private String model;
  29.  
  30.      @Value(“${ChatGPT.variables.temperature}”)
  31.      private String temperature;
  32.      @Override
  33.      public String send(String prompt) {
  34.          JSONObject bodyJson = new JSONObject();
  35.          bodyJson.put(“prompt”, prompt);
  36.          bodyJson.put(“max_tokens”, Integer.parseInt(maxTokens));
  37.          bodyJson.put(“temperature”, Double.parseDouble(temperature));
  38.          Map<String,Object> headMap = new HashMap<>();
  39.          headMap.put(“Authorization”, “Bearer “ + apiKey);
  40.  
  41.          HttpResponse httpResponse = HttpUtil.createPost(“https://api.openai.com/v1/engines/” + model + “/completions”)
  42.                  .header(Header.AUTHORIZATION, “Bearer “ + apiKey)
  43.                  .body(JSONUtil.toJsonStr(bodyJson))
  44.                  .execute();
  45.          String resStr = httpResponse.body();
  46.          log.info(“resStr: {}”, resStr);
  47.  
  48.          GPTResponse gptResponse = JSONUtil.toBean(resStr, GPTResponse.class);
  49.  
  50.          return gptResponse.getChoices().get(0).getText().replaceAll(“\\n”,“”);
  51.      }
  52. }
  53.  

三、使用

接口信息

url:/chatGpt/askAi
type:post
入参:
{
“askStr”:“今天你吃饭了吗”
}

我的几个示例

下面是几个问的示例:

-2

-3

-4

-5

总结

  • 不得不说ChatGPT确实强大,涉及各学科
  • 这个在加上讯飞语言SDK那妥妥的就是一个”小爱同学“
  • 真要上,这里分享的代码还需要优化打磨哦

到此这篇关于Java SpringBoot集成ChatGPT实现AI聊天的文章就介绍到这了,更多相关SpringBoot ChatGPT实现AI聊天内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

标签

发表评论