Răsfoiți Sursa

support chatgpt generate short desc

fengchang 1 an în urmă
părinte
comite
5d0379e006

+ 4 - 0
hichina-admin-backend/build.gradle

@@ -46,6 +46,10 @@ dependencies {
 	implementation 'com.github.pagehelper:pagehelper-spring-boot-starter:1.4.6'
 	// https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-logging
 	implementation 'org.springframework.boot:spring-boot-starter-logging:3.0.3'
+	// https://mvnrepository.com/artifact/com.theokanning.openai-gpt3-java/api
+	implementation 'com.theokanning.openai-gpt3-java:api:0.12.0'
+	// https://mvnrepository.com/artifact/com.theokanning.openai-gpt3-java/client
+	implementation 'com.theokanning.openai-gpt3-java:client:0.12.0'
 }
 
 tasks.named('test') {

+ 23 - 0
hichina-admin-backend/src/main/java/com/hichina/admin/hichinaadminbackend/controller/DestinationController.java

@@ -6,6 +6,7 @@ import com.hichina.admin.hichinaadminbackend.mapper.ProductSkuGroupDestinationMa
 import com.hichina.admin.hichinaadminbackend.model.DTO.*;
 import com.hichina.admin.hichinaadminbackend.model.Destination;
 import com.hichina.admin.hichinaadminbackend.model.ProductSkuGroupDestinationMapping;
+import com.hichina.admin.hichinaadminbackend.service.HichinaOpenAiService;
 import org.apache.commons.lang3.StringUtils;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.transaction.annotation.Transactional;
@@ -21,6 +22,9 @@ public class DestinationController {
     @Autowired
     private DestinationMapper destinationMapper;
 
+    @Autowired
+    private HichinaOpenAiService hichinaOpenAiService;
+
     @Autowired
     private ProductSkuGroupDestinationMappingMapper productSkuGroupDestinationMappingMapper;
 
@@ -39,6 +43,25 @@ public class DestinationController {
         return ret;
     }
 
+    @PutMapping("/openai-gen-desc/{destinationId}")
+    public HichinaResponse updateDestinationDecriptionWithOpenAI(@PathVariable("destinationId") String destinationId){
+        HichinaResponse ret = new HichinaResponse();
+
+        List<Destination> destinations = destinationMapper.findDestinationById(destinationId);
+        if(destinations.isEmpty()){
+            throw new RuntimeException("Nothing to update");
+        }
+        Destination toUpdate = destinations.get(0);
+        String generatedDescription = hichinaOpenAiService.generateShortDescription(toUpdate.getDestinationName());
+        toUpdate.setDescription(generatedDescription);
+        destinationMapper.update(toUpdate);
+        ret.setOk(true);
+        ret.setData(destinationId);
+        ret.setMessage("成功用openAi生成目的地描述");
+        return ret;
+
+    }
+
     @DeleteMapping("/unbind-skugroup-destination")
     public HichinaResponse unbindSkuGroupAndDestination(@RequestBody SkuGroupDestinationBindRequest request){
         HichinaResponse ret = new HichinaResponse();

+ 5 - 5
hichina-admin-backend/src/main/java/com/hichina/admin/hichinaadminbackend/mapper/DestinationMapper.java

@@ -39,18 +39,18 @@ public interface DestinationMapper {
     @Select("select count(*) from destination where level=#{level}")
     Integer countByLevel(Integer level);
 
-    @Select("select * from destination where destination_name like CONCAT('%',CONCAT(#{query},'%')) or description like CONCAT('%',CONCAT(#{query},'%')) order by created_date desc")
+    @Select("select * from destination where destination_id like CONCAT('%',CONCAT(#{query},'%')) or destination_name like CONCAT('%',CONCAT(#{query},'%')) or description like CONCAT('%',CONCAT(#{query},'%')) order by created_date desc")
     List<Destination> findDestinationsByQuery(String query);
 
-    @Select("select destination_id, destination_name from destination where destination_name like CONCAT('%',CONCAT(#{query},'%')) order by created_date desc")
+    @Select("select destination_id, destination_name from destination where destination_id like CONCAT('%',CONCAT(#{query},'%')) or destination_name like CONCAT('%',CONCAT(#{query},'%')) order by created_date desc")
     List<DestinationShortDTO> findDestinationShortByQuery(String query);
 
-    @Select("select * from destination where destination_name like CONCAT('%',CONCAT(#{query},'%')) or description like CONCAT('%',CONCAT(#{query},'%')) and level=#{level} order by created_date desc")
+    @Select("select * from destination where destination_id like CONCAT('%',CONCAT(#{query},'%')) or destination_name like CONCAT('%',CONCAT(#{query},'%')) or description like CONCAT('%',CONCAT(#{query},'%')) and level=#{level} order by created_date desc")
     List<Destination> findDestinationsByQueryAndLevel(String query, Integer level);
 
-    @Select("select count(*) from destination where destination_name like CONCAT('%',CONCAT(#{query},'%')) or description like CONCAT('%',CONCAT(#{query},'%'))")
+    @Select("select count(*) from destination where destination_id like CONCAT('%',CONCAT(#{query},'%')) or destination_name like CONCAT('%',CONCAT(#{query},'%')) or description like CONCAT('%',CONCAT(#{query},'%'))")
     Integer countByQuery(String query);
 
-    @Select("select count(*) from destination where destination_name like CONCAT('%',CONCAT(#{query},'%')) or description like CONCAT('%',CONCAT(#{query},'%')) and leve=#{level}")
+    @Select("select count(*) from destination where destination_id like CONCAT('%',CONCAT(#{query},'%')) or destination_name like CONCAT('%',CONCAT(#{query},'%')) or description like CONCAT('%',CONCAT(#{query},'%')) and leve=#{level}")
     Integer countByQueryAndLevel(String query, Integer level);
 }

+ 45 - 0
hichina-admin-backend/src/main/java/com/hichina/admin/hichinaadminbackend/service/HichinaOpenAiService.java

@@ -0,0 +1,45 @@
+package com.hichina.admin.hichinaadminbackend.service;
+
+import com.theokanning.openai.OpenAiService;
+import com.theokanning.openai.completion.CompletionChoice;
+import com.theokanning.openai.completion.CompletionRequest;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Service;
+
+import java.util.List;
+
+@Service
+public class HichinaOpenAiService {
+    @Value("${chatgpt.model}")
+    private String model;
+
+    private OpenAiService service;
+
+    @Value("${openai.token}")
+    public void setNameStatic(String tokenAndTimeout){
+        String[] args = tokenAndTimeout.split(",");
+        // key trick: the timeout here is very important
+        service = new OpenAiService(args[0], Integer.parseInt(args[1]));
+    }
+
+    private String generateDescriptionRequest(String destinationName){
+        return String.format("Please give me a travel introduction of %s in 50 words in English", destinationName);
+    }
+
+    public String generateShortDescription(String destinationName){
+        CompletionRequest completionRequest = CompletionRequest.builder()
+                .model(model).topP(1.0).temperature(0.0).maxTokens(100)
+                .prompt(generateDescriptionRequest(destinationName))
+                .echo(false)
+                .user("hichinaadmin")
+                .build();
+
+        List<CompletionChoice> choices = service.createCompletion(completionRequest).getChoices();
+
+        if(choices==null || choices.size()<1){
+            return "机器人犯迷糊了~";
+        }else{
+            return choices.get(0).getText();
+        }
+    }
+}

+ 4 - 1
hichina-admin-backend/src/main/resources/application-dev.properties

@@ -41,4 +41,7 @@ spring.servlet.multipart.max-file-size=3MB
 spring.servlet.multipart.max-request-size=3MB
 
 logging.level.org.springframework.web=DEBUG
-logging.level.org.hibernate=ERROR
+logging.level.org.hibernate=ERROR
+
+chatgpt.model=text-davinci-003
+openai.token=**,20

+ 4 - 1
hichina-admin-backend/src/main/resources/application-qa.properties

@@ -40,4 +40,7 @@ spring.servlet.multipart.max-file-size=3MB
 spring.servlet.multipart.max-request-size=3MB
 
 logging.level.org.springframework.web=DEBUG
-logging.level.org.hibernate=ERROR
+logging.level.org.hibernate=ERROR
+
+chatgpt.model=text-davinci-003
+openai.token=**,20

+ 4 - 1
hichina-admin-front/quasar.config.js

@@ -88,6 +88,9 @@ module.exports = configure(function (ctx) {
         notify: {
           /* look at QuasarConfOptions from the API card */
         },
+        loading: {
+          /* look at QuasarConfOptions from the API card */
+        },
       },
 
       // iconSet: 'material-icons', // Quasar icon set
@@ -101,7 +104,7 @@ module.exports = configure(function (ctx) {
       // directives: [],
 
       // Quasar plugins
-      plugins: ["Notify"],
+      plugins: ["Notify", "Loading"],
     },
 
     // animations: 'all', // --- includes all animations

+ 32 - 1
hichina-admin-front/src/pages/DestinationPage.vue

@@ -71,9 +71,15 @@
             <q-btn
               color="purple"
               dense
-              label="更多详情"
+              label="编辑"
               @click="goDestinationDetail(props.row.destinationId)"
             />
+            <q-btn
+              color="green"
+              dense
+              label="ChatGpt生成简述"
+              @click="chatGptGenerateDesc(props.row.destinationId)"
+            />
           </q-td>
         </template>
         <template v-slot:body-cell-level="props">
@@ -97,6 +103,12 @@ export default {
     const $q = useQuasar();
 
     return {
+      showLoading() {
+        $q.loading.show();
+      },
+      hideLoading() {
+        $q.loading.hide();
+      },
       showNotifyMessageFail(msg) {
         $q.notify({
           message: msg,
@@ -187,6 +199,25 @@ export default {
     this.refreshTable();
   },
   methods: {
+    chatGptGenerateDesc(destId) {
+      this.showLoading();
+      api
+        .put("/api/v1/destination/openai-gen-desc/" + destId)
+        .then((response) => {
+          console.log("generating description with chatgpt");
+          console.log(response.data);
+          if (response.data.ok === true) {
+            this.showNotifyMessageSucceed(response.data.message);
+          } else {
+            this.showNotifyMessageFail(response.data.message);
+          }
+          this.hideLoading();
+        })
+        .catch((e) => {
+          this.showNotifyMessageFail(e.toString());
+          this.hideLoading();
+        });
+    },
     goDestinationDetail(val) {
       this.$refs.destinationCreateDialgRef.toggleEditMode(val);
     },