当前位置:   article > 正文

java编写chatgpt回调接口_java如何写gpt接口

java如何写gpt接口

使用ChatGpt 3.5

package com.example.chatgpt_callback.controller;

import com.example.chatgpt_callback.utils.*;
import lombok.extern.slf4j.Slf4j;
import java.util.Map;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@Slf4j
@RestController
public class CallbackController {
    private static final String model = "gpt-3.5-turbo"; //"gpt-4";
    private static final String apiKey =  "xxx";
    private static final int maxTokens = 4000;
    @RequestMapping("/gptdata")
    public String sourcedata(@RequestBody Map body) throws Exception {
        try {
            String dataEncrypt = JSON.toJSONString(body);
            JSONObject jsonObject = JSONObject.parseObject(dataEncrypt);
            String sourceBodyContent = jsonObject.getString("bodyContent");
            String userData = jsonObject.getString("user_data");
            //获取包含"暂未关联到可用方案"数据信息.接入gpt进行问答
            boolean otherData = sourceBodyContent.contains("暂未关联到可用方案");
            if ( otherData ) {
                //GPT3.5使用方式
                ChatGpt3 chatGpt3= new ChatGpt3();
                String targetData = chatGpt3.chaGpt3Result(userData,apiKey,model,maxTokens,dataEncrypt);
                //达芬奇003模型调用
//                ChatGptDavinci chatGptDavinci = new ChatGptDavinci();
//                String targetData = chatGptDavinci.chaGptResult(userData,apiKey,model,maxTokens,dataEncrypt);
                log.info("gpt响应内容:{}",targetData);
                return targetData;

            }else {
                log.info("gpt响应内容:{}",dataEncrypt);
                return dataEncrypt;
            }
        }catch (Exception e){
            log.error("处理异常:{}",e);
        }
        return "响应异常!";
    }

}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49

访问gpt3.5

package com.example.chatgpt_callback.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.extern.slf4j.Slf4j;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

@Slf4j
public class ChatGpt3 {
    public String chaGptResource(String apiKey, String requestBody) throws Exception {
        // API endpoint URL
        SslUtils.ignoreSsl();
        String apiEndpoint = "https://api.openai.com/v1/chat/completions";
        // Set up the API request
        URL url = new URL(apiEndpoint);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/json");
        con.setRequestProperty("Authorization", "Bearer " + apiKey);
        log.info("请求gptbody: " + requestBody);
        String response = "";
        try {
            con.setDoOutput(true);
            con.getOutputStream().write(requestBody.getBytes());
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                response += inputLine;
            }
            in.close();
            // Print the response
        }catch (Exception e){
            log.error("Gpt响应异常:{}",e);
            response = "{\"choices\":[{\"message\":{\"role\":\"assistant\"," +
                    "\"content\":\"抱歉, 我不太清楚, 请换一个提问的方式!\"}}]}";
            return response;
        }
        log.info("gpt响应具体数据: {}",response);
        return response;
    }
    public String chaGpt3Result(String userData,String apiKey,String model,int maxTokens, String dataEncrypt) throws Exception {
        JSONObject jsonUserData = JSONObject.parseObject(userData);
        String userQuery = jsonUserData.getString("query");
        String userId = jsonUserData.getString("userId");
        //字符串中多个空格替换成1个
        String blank = "\\s+";
        userQuery = userQuery.replaceAll(blank, " ");
        ChatGpt3 chatGpt3 = new ChatGpt3();
        JsonResource jsonResource = new JsonResource();
        log.info("上次缓存结果: " + Guava.GuavaDataGet(userId ));
        String jsonResult = jsonResource.requestBody(model,maxTokens,userId,userQuery);
        String gptData = chatGpt3.chaGptResource(apiKey,jsonResult);
        JSONObject jsonObject = JSONObject.parseObject(gptData);
        JSONArray results = jsonObject.getJSONArray("choices");
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode sourceData = objectMapper.readTree(dataEncrypt);
        JsonNode bodyContent = sourceData.path("bodyContent");
        String targetData = "";
        for (int n = 0; n < results.size(); n++) {
            String textData = results.getJSONObject(n).getString("message");
            JSONObject jsonMessage= JSONObject.parseObject(textData);
            //插入响应gpt数据到缓存
            Guava.GuavaDataSet(userId,textData);
            String jsonContent = jsonMessage.getString("content");
            String regex = "^.*\n\n?";
            String regexextData  = jsonContent.replaceAll(regex, "");
            String blank1 = "\n\n";
            regexextData = regexextData.replaceAll(blank1, "\n");
            //添加gpt响应标识
            StringBuilder sb = new StringBuilder();
            sb.append("【外部数据,仅供参考】 \n");
            sb.append(regexextData);
            String labelGptData = sb.toString();
            if (!bodyContent.isMissingNode()) {
                ((ObjectNode) sourceData).put("bodyContent", labelGptData);
            }

            targetData = objectMapper.writeValueAsString(sourceData);
        }
        return targetData;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89

谷歌缓存使用

package com.example.chatgpt_callback.utils;

import java.util.concurrent.TimeUnit;
import com.fasterxml.jackson.core.JsonProcessingException;;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

public class Guava {
    private static Cache<String, String> cache;
    static {
        // 创建一个缓存对象
        cache = CacheBuilder.newBuilder()
                                .maximumSize(2)
                .expireAfterAccess(120, TimeUnit.SECONDS)
                .build();
    }
    public static  void  GuavaDataSet (String user, String requestValues) throws JsonProcessingException {
        // 创建一个缓存对象,并定义缓存数据的过期时间为120秒

        // 将数据放入缓存
        cache.put(user, requestValues);
    }
    public static String GuavaDataGet (String user) throws JsonProcessingException {

        // 从缓存中获取数据
        String value = cache.getIfPresent(user);
        return value;
    }

}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

封装请求json

package com.example.chatgpt_callback.utils;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class JsonResource {

    public static  String requestBody(String model, int maxTokens, String user, String prompt) throws JsonProcessingException {
        Map<String, Object> reqMap = new HashMap<>();
        reqMap.put("model",model);
        reqMap.put("max_tokens",maxTokens);
        List<Map<String, Object>> messagesList = new ArrayList<>();
        Map<String, Object> messageMap = new HashMap<>();
        messageMap.put("role", "user");
        messageMap.put("content", prompt);
        ObjectMapper objectMapper = new ObjectMapper();
        if (Guava.GuavaDataGet(user) != null ){
            String GuavaDataGetData = Guava.GuavaDataGet(user);
            Map<String, Object> GuavaDataGetDataMap = objectMapper.readValue(GuavaDataGetData, Map.class);
            messagesList.add(GuavaDataGetDataMap);
        }
        messagesList.add(messageMap);
        String messageJson =  objectMapper.writeValueAsString(messageMap);
        log.info("插入缓存"+ messageJson);
        Guava.GuavaDataSet(user,messageJson);
        reqMap.put("messages", messagesList);
        String requestBody = JSON.toJSONString(reqMap);
        return requestBody;
    }

}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
package com.example.chatgpt_callback.utils;



import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class SslUtils {private static void trustAllHttpsCertificates() throws Exception {
    TrustManager[] trustAllCerts = new TrustManager[1];
    TrustManager tm = new miTM();
    trustAllCerts[0] = tm;
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, null);
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}

    static class miTM implements TrustManager,X509TrustManager {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public boolean isServerTrusted(X509Certificate[] certs) {
            return true;
        }

        public boolean isClientTrusted(X509Certificate[] certs) {
            return true;
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType)
                throws CertificateException {
            return;
        }

        public void checkClientTrusted(X509Certificate[] certs, String authType)
                throws CertificateException {
            return;
        }
    }

    /**
     * 忽略HTTPS请求的SSL证书,必须在openConnection之前调用
     * @throws Exception
     */
    public static void ignoreSsl() throws Exception{
        HostnameVerifier hv = new HostnameVerifier() {
            public boolean verify(String urlHostName, SSLSession session) {
                System.out.println("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost());
                return true;
            }
        };
        trustAllHttpsCertificates();
        HttpsURLConnection.setDefaultHostnameVerifier(hv);
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/372389?site
推荐阅读
相关标签
  

闽ICP备14008679号