Selaa lähdekoodia

fix:修复大语言模型接入问题

lllgodenough 11 kuukautta sitten
vanhempi
commit
e48cd035f1

+ 6 - 0
pom.xml

@@ -230,6 +230,12 @@
             <version>1.12.378</version>
         </dependency>
 
+        <dependency>
+            <groupId>com.theokanning.openai-gpt3-java</groupId>
+            <artifactId>service</artifactId>
+            <version>0.18.2</version>
+        </dependency>
+
     </dependencies>
 
     <build>

+ 17 - 5
src/main/java/com/njuzr/eaibackend/config/DeepSeekConfig.java

@@ -1,11 +1,12 @@
 package com.njuzr.eaibackend.config;
 
-import org.apache.http.impl.client.CloseableHttpClient;
-import org.apache.http.impl.client.HttpClients;
+import okhttp3.OkHttpClient;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.Configuration;
 
+import java.util.concurrent.TimeUnit;
+
 /**
  * @author Liululin
  * @date 2025/9/11 - 20:53
@@ -19,7 +20,7 @@ public class DeepSeekConfig {
     @Value("${deepseek.api.base-url}")
     private String baseUrl;
 
-    @Value("${deepseek.api.model")
+    @Value("${deepseek.api.model}")
     private String model;
 
     public Double getTemperature() {
@@ -41,8 +42,19 @@ public class DeepSeekConfig {
         return baseUrl;
     }
 
+    public static OkHttpClient httpClient;
+
     @Bean
-    public CloseableHttpClient httpClient() {
-        return HttpClients.createDefault();
+    public OkHttpClient httpClient() {
+       if(httpClient == null){
+           httpClient = new OkHttpClient.Builder()
+                   .connectTimeout(30, TimeUnit.SECONDS)     // 连接超时
+                   .readTimeout(120, TimeUnit.SECONDS)       // 读取超时(关键!)
+                   .writeTimeout(30, TimeUnit.SECONDS)       // 写入超时
+                   .build();
+       }
+       return httpClient;
     }
+
+
 }

+ 49 - 31
src/main/java/com/njuzr/eaibackend/service/DeepSeekService.java

@@ -1,14 +1,16 @@
 package com.njuzr.eaibackend.service;
-
 import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.gson.Gson;
 import com.njuzr.eaibackend.config.DeepSeekConfig;
+import com.njuzr.eaibackend.config.ECloudEosConfig;
+import com.njuzr.eaibackend.exception.MyException;
 import com.njuzr.eaibackend.po.AIEntry;
+import com.njuzr.eaibackend.service.DeepSeekService;
+import com.njuzr.eaibackend.service.impl.CourseServiceImpl;
+
 import lombok.extern.slf4j.Slf4j;
-import org.apache.http.client.methods.CloseableHttpResponse;
-import org.apache.http.client.methods.HttpPost;
-import org.apache.http.entity.StringEntity;
-import org.apache.http.impl.client.CloseableHttpClient;
-import org.apache.http.util.EntityUtils;
+import okhttp3.*;
+
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 
@@ -25,49 +27,65 @@ import java.util.Map;
 @Slf4j
 public class DeepSeekService {
 
-    private final CloseableHttpClient httpClient;
     private final ObjectMapper objectMapper;
 
     public DeepSeekService(
-                           CloseableHttpClient httpClient,
-                           ObjectMapper objectMapper) {
-        this.httpClient = httpClient;
+
+            ObjectMapper objectMapper) {
         this.objectMapper = objectMapper;
     }
 
     @Autowired
     DeepSeekConfig deepSeekConfig;
 
+    private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
+
     public String chatCompletion(List<AIEntry> message) throws IOException {
-        HttpPost httpPost = new HttpPost(deepSeekConfig.getBaseUrl());
-        // 设置请求头
-        httpPost.setHeader("Content-Type", "application/json");
-        httpPost.setHeader("Authorization", "Bearer " + deepSeekConfig.getApiKey());
-        System.out.println(deepSeekConfig.getApiKey());
-        // 构建请求体
+        OkHttpClient okHttpClient = deepSeekConfig.httpClient();
         Map<String, Object> requestBody = new HashMap<>();
         requestBody.put("model", deepSeekConfig.getModel());
         requestBody.put("messages", message);
         requestBody.put("temperature", deepSeekConfig.getTemperature());
+        requestBody.put("stream", false);
+        Gson gson = new Gson();
+        RequestBody body = RequestBody.create(JSON, gson.toJson(requestBody));
+        // 构建请求
+        Request request = new Request.Builder()
+                .url(deepSeekConfig.getBaseUrl())
+                .addHeader("Authorization", "Bearer " + deepSeekConfig.getApiKey())
+                .addHeader("Content-Type", "application/json")
+                .post(body)
+                .build();
 
-        StringEntity entity = new StringEntity(objectMapper.writeValueAsString(requestBody));
-        System.out.println("请求体:" + entity.getContent().toString());
-        httpPost.setEntity(entity);
+        // 发送请求
+        try (Response response = okHttpClient.newCall(request).execute()) {
+            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
 
-        // 执行请求
-        try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
-            String responseBody = EntityUtils.toString(response.getEntity());
+            // 解析并打印结果
+            String responseBody = response.body().string();
             System.out.println(responseBody);
-            Map<String, Object> responseMap = objectMapper.readValue(responseBody, Map.class);
-
-            // 解析响应
-            List<Map<String, Object>> choices = (List<Map<String, Object>>) responseMap.get("choices");
-            if (choices != null && !choices.isEmpty()) {
-                Map<String, Object> res = (Map<String, Object>) choices.get(0).get("message");
-                return (String) res.get("content");
-            }
-            return "未获取到有效响应";
+            ResponseData data = gson.fromJson(responseBody, ResponseData.class);
+            System.out.println("\n回答内容:");
+            System.out.println(data.choices[0].message.content);
+            return data.choices[0].message.content;
+        } catch (IOException e) {
+            System.out.println(e.getMessage());
+            throw new MyException(400, "获取回答失败" + e.getMessage());
+        }
+    }
+
+    // 内部类用于解析返回 JSON
+    static class ResponseData {
+        Choice[] choices;
+
+        static class Choice {
+            Message message;
+        }
+
+        static class Message {
+            String content;
         }
     }
 }
 
+

+ 83 - 10
src/test/java/com/njuzr/eaibackend/EaiBackendApplicationTests.java

@@ -1,19 +1,25 @@
 package com.njuzr.eaibackend;
 
 import com.amazonaws.services.s3.model.ObjectListing;
+import com.google.gson.Gson;
+import com.njuzr.eaibackend.config.DeepSeekConfig;
 import com.njuzr.eaibackend.config.ECloudEosConfig;
-import com.njuzr.eaibackend.controller.MyResponse;
 import com.njuzr.eaibackend.po.AIEntry;
 import com.njuzr.eaibackend.service.DeepSeekService;
 import com.njuzr.eaibackend.service.impl.CourseServiceImpl;
+
+import okhttp3.*;
+
 import org.junit.jupiter.api.Test;
-import org.junit.jupiter.params.shadow.com.univocity.parsers.common.input.LineSeparatorDetector;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.boot.test.context.SpringBootTest;
-
 import java.io.IOException;
 import java.util.ArrayList;
+import java.util.HashMap;
 import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
 
 @SpringBootTest
 class EaiBackendApplicationTests {
@@ -27,11 +33,18 @@ class EaiBackendApplicationTests {
     @Autowired
     ECloudEosConfig eCloudEosConfig;
 
+    @Autowired
+    DeepSeekConfig deepSeekConfig;
 
 
+    private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
 
     @Test
     void contextLoads() {
+
+
+
+
         List<AIEntry> list = new ArrayList<>();
         list.add(new AIEntry("user","你好"));
         try {
@@ -40,17 +53,77 @@ class EaiBackendApplicationTests {
             System.out.println(e.getMessage());
         }
 
-        // 列出存储桶中的对象
-        ObjectListing objectListing = eCloudEosConfig.eosClient().listObjects(eCloudEosConfig.getBucketName());
-        List<String> files = new ArrayList<>();
-        objectListing.getObjectSummaries().forEach(objectSummary -> {
-            System.out.println(objectSummary.getKey());
-        });
 
+        // API配置
+//        String apiKey = "E-OYKpcDb_L5WjdVPw2sZ-08ds4Vv-hBRe-lAV9tnqI";
+//        String baseUrl = "https://zhenze-huhehaote.cmecloud.cn/v1/chat/completions";
+//        String model = "deepseek-v3";
+//        MediaType JSON = MediaType.get("application/json; charset=utf-8");
+//
+//        // 创建 OkHttpClient
+//        OkHttpClient client = new OkHttpClient.Builder()
+//                .connectTimeout(30, TimeUnit.SECONDS)     // 连接超时
+//                .readTimeout(120, TimeUnit.SECONDS)       // 读取超时(关键!)
+//                .writeTimeout(30, TimeUnit.SECONDS)       // 写入超时
+//                .build();
+//
+//        // 构建请求体
+//        Gson gson = new Gson();
+//        RequestBody requestBody = RequestBody.create(JSON, """
+//            {
+//                "model": "deepseek-v3",
+//                "messages": [
+//                    {"role": "system", "content": "You are a helpful assistant"},
+//                    {"role": "user", "content": "请简单介绍下苏州"}
+//                ],
+//                "max_tokens": 1024,
+//                "temperature": 0.7,
+//                "stream": false
+//            }
+//            """);
+//
+//        // 构建请求
+//        Request request = new Request.Builder()
+//                .url(baseUrl)
+//                .addHeader("Authorization", "Bearer " + apiKey)
+//                .addHeader("Content-Type", "application/json")
+//                .post(requestBody)
+//                .build();
+//
+//        // 发送请求
+//        try (Response response = client.newCall(request).execute()) {
+//            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
+//
+//            // 解析并打印结果
+//            String responseBody = response.body().string();
+//            System.out.println(responseBody);
+//
+//            // 可选:解析 JSON 获取 message.content
+//            // 使用 Gson 解析响应中的 choices[0].message.content
+//            ResponseData data = gson.fromJson(responseBody, ResponseData.class);
+//            System.out.println("\n回答内容:");
+//            System.out.println(data.choices[0].message.content);
+//        } catch (IOException e) {
+//            System.out.println(e.getMessage());
+//            e.printStackTrace();
+//        }
+//    }
+//
+//    // 内部类用于解析返回 JSON
+//    static class ResponseData {
+//        Choice[] choices;
+//
+//        static class Choice {
+//            Message message;
+//        }
+//
+//        static class Message {
+//            String content;
+//        }
     }
 
+    }
 
 
-}