Просмотр исходного кода

feat: "添加chatgpt的接口"

Leonezhurui 2 лет назад
Родитель
Сommit
2f2132798c

+ 13 - 1
src/main/java/com/njuzr/eaibackend/controller/AIController.java

@@ -4,6 +4,7 @@ import com.njuzr.eaibackend.dto.AIDTO;
 import com.njuzr.eaibackend.po.AIDialogue;
 import com.njuzr.eaibackend.po.AIEntry;
 import com.njuzr.eaibackend.service.AIDialogueService;
+import com.njuzr.eaibackend.service.AIRequestService;
 import com.njuzr.eaibackend.vo.AIDialogueVO;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
@@ -25,9 +26,12 @@ import org.springframework.web.bind.annotation.*;
 public class AIController {
     private final AIDialogueService aiDialogueService;
 
+    private final AIRequestService aiRequestService;
+
     @Autowired
-    public AIController(AIDialogueService aiDialogueService) {
+    public AIController(AIDialogueService aiDialogueService, AIRequestService aiRequestService) {
         this.aiDialogueService = aiDialogueService;
+        this.aiRequestService = aiRequestService;
     }
 
     @PreAuthorize("hasRole('ROLE_STUDENT') or hasRole('ROLE_TEACHER')")
@@ -85,4 +89,12 @@ public class AIController {
         return MyResponse.success(entry);
     }
 
+    @PostMapping("/chatgpt")
+    public MyResponse requestChatGPT(
+            @RequestBody AIDTO aidto
+    ) {
+        AIRequestService.AIResponse res = aiRequestService.requestChatGPT(aidto.getMessages());
+        return MyResponse.success(res);
+    }
+
 }

+ 2 - 0
src/main/java/com/njuzr/eaibackend/service/AIDialogueService.java

@@ -153,6 +153,8 @@ public class AIDialogueService {
             res = aiRequestService.requestChatGLM(aidto.getMessages());
         } else if (modelType.equals("QWen14B")) {
             res = aiRequestService.requestQWen(aidto.getMessages());
+        } else if (modelType.equals("ChatGPT")) {
+            res = aiRequestService.requestChatGPT(aidto.getMessages());
         } else {
             throw new MyException(HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase()+":"+"模型不支持");
         }

+ 21 - 0
src/main/java/com/njuzr/eaibackend/service/AIRequestService.java

@@ -6,6 +6,7 @@ import com.njuzr.eaibackend.utils.WebClientUtil;
 import lombok.AllArgsConstructor;
 import lombok.Data;
 import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Value;
 import org.springframework.http.HttpStatus;
 import org.springframework.stereotype.Service;
 
@@ -20,11 +21,31 @@ import java.util.List;
 @Slf4j
 @Service
 public class AIRequestService {
+
+    @Value("${openai.chatgpt.model}")
+    private String model;
+
+    @Value("${openai.chatgpt.api.key}")
+    private String key;
+
+    private final WebClientUtil chatgptClient = new WebClientUtil("https://api.openai.com");
     private final WebClientUtil chatglmClient = new WebClientUtil("http://10.58.0.2:6678");
     private final WebClientUtil qwenClient = new WebClientUtil("http://10.58.0.2:6679");
 
     private final String prefix = "/v1/chat/completions";
 
+    public AIResponse requestChatGPT(List<AIEntry> messages) {
+        MyRequestObject requestObject = new MyRequestObject(model, messages);
+
+        try {
+            return chatgptClient.postWithToken(prefix, requestObject, AIResponse.class, key);
+        } catch (Exception e) {
+            log.error("WebClient请求失败,AI请求失败~");
+            throw new MyException(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()+":"+"服务器请求AI出错");
+        }
+    }
+
+
     public AIResponse requestChatGLM(List<AIEntry> messages) {
         MyRequestObject requestObject = new MyRequestObject("ChatGLM3", messages);
 

+ 24 - 0
src/main/java/com/njuzr/eaibackend/utils/WebClientUtil.java

@@ -3,13 +3,17 @@ package com.njuzr.eaibackend.utils;
 import io.netty.handler.ssl.SslContextBuilder;
 import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
 import lombok.extern.slf4j.Slf4j;
+import org.springframework.http.HttpHeaders;
 import org.springframework.http.MediaType;
 import org.springframework.http.client.reactive.ReactorClientHttpConnector;
 import org.springframework.web.reactive.function.client.WebClient;
 import org.springframework.web.reactive.function.client.WebClientResponseException;
 import reactor.netty.http.client.HttpClient;
+import reactor.netty.transport.ProxyProvider;
 
 import java.nio.file.Path;
+import java.util.HashMap;
+import java.util.function.Consumer;
 
 /**
  * @author: Leonezhurui
@@ -38,7 +42,13 @@ public class WebClientUtil {
 //                .baseUrl(baseUrl)
 //                .build();
 
+        HttpClient httpClient = HttpClient.create()
+                .proxy(proxy -> proxy.type(ProxyProvider.Proxy.HTTP)
+                        .host("127.0.0.1")
+                        .port(7890));
+
         this.webClient = WebClient.builder()
+                .clientConnector(new ReactorClientHttpConnector(httpClient))
                 .baseUrl(baseUrl)
                 .build();
     }
@@ -102,5 +112,19 @@ public class WebClientUtil {
     }
 
 
+    public <T, R> T  postWithToken(String uri, R request, Class<T> responseType, String key) {
+        try {
+            return this.webClient.post()
+                    .uri(uri)
+                    .header("Authorization", "Bearer " + key)
+                    .bodyValue(request)
+                    .retrieve()
+                    .bodyToMono(responseType)
+                    .block(); // 转换为阻塞调用
+        } catch (WebClientResponseException e) {
+            log.error("WebClient发送POST请求失败:" + e.getMessage());
+            throw new RuntimeException("Failed to post data: " + e.getMessage(), e);
+        }
+    }
 
 }

+ 6 - 0
src/main/resources/application-dev.yaml

@@ -41,3 +41,9 @@ aliyun:
 logging:
   config: classpath:log4j2-dev.xml
 
+openai:
+  chatgpt:
+    model: gpt-3.5-turbo
+    api:
+      key: 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
+