wangyunpeng 1 روز پیش
والد
کامیت
a7fd6c4604

+ 93 - 0
api-module/src/main/java/com/tzld/piaoquan/api/component/DeepSeekApiService.java

@@ -0,0 +1,93 @@
+package com.tzld.piaoquan.api.component;
+
+import com.alibaba.fastjson.JSONArray;
+import com.alibaba.fastjson.JSONObject;
+import com.tzld.piaoquan.api.model.dto.AIOfficialApiResponse;
+import com.tzld.piaoquan.api.model.dto.AIResult;
+import com.tzld.piaoquan.growth.common.utils.MapBuilder;
+import lombok.extern.slf4j.Slf4j;
+import okhttp3.*;
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.http.util.TextUtils;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.PostConstruct;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.TimeUnit;
+
+@Service
+@Slf4j
+public class DeepSeekApiService {
+
+    private OkHttpClient client;
+
+    @PostConstruct
+    public void init() {
+        client = new OkHttpClient().newBuilder()
+                .connectTimeout(5, TimeUnit.MINUTES)
+                .readTimeout(5, TimeUnit.MINUTES)
+                .writeTimeout(5, TimeUnit.MINUTES)
+                .build();
+    }
+
+    public AIResult requestOfficialApi(String prompt, String model, Double temperature, Boolean isJSON) {
+        AIResult result = new AIResult();
+        result.setSuccess(false);
+        if (TextUtils.isBlank(prompt) || TextUtils.isBlank(prompt.trim())) {
+            result.setFailReason("prompt is empty");
+            return result;
+        }
+
+        try {
+            JSONArray jsonArray = new JSONArray();
+            JSONObject message = new JSONObject();
+            message.put("role", "user");
+            message.put("content", prompt);
+            jsonArray.add(message);
+
+            Map<Object, Object> bodyParam = MapBuilder
+                    .builder()
+                    .put("model", Optional.ofNullable(model).orElse("deepseek-chat"))
+                    .put("temperature", Optional.ofNullable(temperature).orElse(0.3))
+                    .put("messages", jsonArray)
+                    .build();
+            if (isJSON) {
+                JSONObject formatJSON = new JSONObject();
+                formatJSON.put("type", "json_object");
+                bodyParam.put("response_format", formatJSON);
+            }
+
+            MediaType mediaType = MediaType.parse("application/json");
+            RequestBody body = RequestBody.create(mediaType, JSONObject.toJSONString(bodyParam));
+            Request request = new Request.Builder()
+                    .url("https://api.deepseek.com/chat/completions")
+                    .method("POST", body)
+                    .addHeader("Content-Type", "application/json")
+                    .addHeader("Accept", "application/json")
+                    .addHeader("Authorization", "Bearer sk-62d7b2c37f824735aa4985852c919c1f")
+                    .build();
+            Response response = client.newCall(request).execute();
+
+            String responseContent = response.body().string();
+            result.setResponseStr(responseContent);
+            log.info("deepseek api responseContent = {}", responseContent);
+            if (response.isSuccessful()) {
+                AIOfficialApiResponse obj = JSONObject.parseObject(responseContent, AIOfficialApiResponse.class);
+                if (CollectionUtils.isNotEmpty(obj.getChoices())) {
+                    result.setSuccess(true);
+                    result.setResponse(obj);
+                } else {
+                    result.setFailReason("response empty");
+                }
+            } else {
+                JSONObject json = JSONObject.parseObject(responseContent);
+                result.setFailReason("request error code:" + response.code() + " message:" + json.getString("error"));
+            }
+        } catch (Exception e) {
+            log.error("deepseek official api fail: " + e.getMessage());
+            result.setFailReason(e.getMessage());
+        }
+        return result;
+    }
+}

+ 39 - 0
api-module/src/main/java/com/tzld/piaoquan/api/model/dto/AIOfficialApiResponse.java

@@ -0,0 +1,39 @@
+package com.tzld.piaoquan.api.model.dto;
+
+import lombok.Data;
+
+import java.util.List;
+
+@Data
+public class AIOfficialApiResponse {
+
+    private String id;
+    private String object;
+    private long created;
+    private String model;
+    private List<Choice> choices;
+    private Usage usage;
+
+
+    @Data
+    public static class Choice {
+        private long index;
+        private Message message;
+        private String finishReason;
+    }
+
+
+    @Data
+    public static class Message {
+        private String role;
+        private String content;
+    }
+
+    @Data
+    public static class Usage {
+        private long promptTokens;
+        private long completionTokens;
+        private long totalTokens;
+    }
+
+}

+ 11 - 0
api-module/src/main/java/com/tzld/piaoquan/api/model/dto/AIResult.java

@@ -0,0 +1,11 @@
+package com.tzld.piaoquan.api.model.dto;
+
+import lombok.Data;
+
+@Data
+public class AIResult {
+    private boolean success;
+    private AIOfficialApiResponse response;
+    private String failReason;
+    private String responseStr;
+}

+ 50 - 0
common-module/src/main/java/com/tzld/piaoquan/growth/common/utils/MapBuilder.java

@@ -0,0 +1,50 @@
+package com.tzld.piaoquan.growth.common.utils;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Objects;
+
+/**
+ * @author: TanJingyu
+ * @create:2023-06-12 13:28:18
+ **/
+public class MapBuilder {
+
+    private MapBuilder() {
+    }
+
+    public static <K, V> Builder<K, V> builder() {
+        return new Builder<>(null);
+    }
+
+    public static <K, V> Builder<K, V> builder(Map<K, V> map) {
+        return new Builder<>(map);
+    }
+
+    public static class Builder<K, V> {
+        private Map<K, V> resultMap = new HashMap<>();
+
+        private Builder(Map<K, V> map) {
+            if (Objects.nonNull(map)) {
+                resultMap = map;
+            }
+        }
+
+        public Builder<K, V> put(K k, V v) {
+            resultMap.put(k, v);
+            return this;
+        }
+
+        public Map<K, V> build() {
+            return resultMap;
+        }
+    }
+
+
+    public static void main(String[] args) {
+        Map<String, Object> build = MapBuilder.<String, Object>builder().put("name", "忘记")
+                .put("age", 23)
+                .build();
+        System.out.println(build);
+    }
+}