ChatGPTApiController.java 4.2 KB
package com.zhonglai.luhui.controller;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.zhonglai.luhui.dto.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "chatGPT接口")
@RestController
@RequestMapping("/chatGPTApi")
public class ChatGPTApiController {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @ApiOperation(value = "测试")
    @PostMapping("/sendMessage")
    public String sendMessage(HttpServletResponse response, @RequestBody ChatGPTApiDto chatGPTApiDto)
    {
        int timeout = 3000000;
        // 设置响应内容类型和编码
        response.setContentType("text/html;charset=UTF-8");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("model","gpt-3.5-turbo-0301");
        jsonObject.put("messages",chatGPTApiDto.getMessageList());

//        String domainName = "api.openai.com";
//        String apiDomain = "openai.yu2le.com/api";
        String domainName = "chatgpt.njlaikun.com";
        String apiDomain = "localhost:8082";

        Map<String,String> map = new HashMap<>();
        if(chatGPTApiDto.getIsfree())
        {
            map.put("Authorization","Bearer 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");
        }else{
            map.put("Authorization","Bearer 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");
        }
        map.put("Content-Type","application/json");
        String str = HttpRequest.post("https://"+domainName+"/v1/chat/completions").setReadTimeout(timeout).timeout(timeout).addHeaders(map).body(jsonObject.toString()).execute().body();
        logger.info("返回的数据:{}",str);
        if(JSONUtil.isTypeJSONObject(str))
        {
            CompletionResult3_5 completionResult = JSONObject.parseObject(str, CompletionResult3_5.class);
            List<CompletionChoice3_5> list = completionResult.getChoices();
            if(null != list && list.size() != 0)
            {
                StringBuffer stringBuffer = new StringBuffer();
                for (CompletionChoice3_5 completionChoice3_5:list)
                {
                    stringBuffer.append(completionChoice3_5.getMessage().getContent());
                    completionChoice3_5.getMessage().setContent(null);
                }
                completionResult.setContentLength( stringBuffer.length());
                completionResult.setRoom_id(chatGPTApiDto.getRoom_id());
                completionResult.setGptMessage_id(chatGPTApiDto.getGptMessage_id());
                completionResult.setUser_id(chatGPTApiDto.getUser_id());
                //通知更新用户信息
                String noticestr = JSONObject.toJSONString(completionResult);
                String rstr = HttpUtil.post("http://"+apiDomain+"/chatGPTStream/upUserFlowPacketRemain",noticestr);
                logger.info("修改返回的数据:{}",rstr);
                //返回结果字符串
                return stringBuffer.toString();
//                writeMessage(stringBuffer,response);
            }
        }
        return str;
    }

    private void writeMessage(StringBuffer stringBuffer,HttpServletResponse response)
    {
        PrintWriter out = null;
        try {
            out = response.getWriter();
            //验证验证码
            if(StringUtils.isNotEmpty(stringBuffer))
            {
                for(int i=0;i<stringBuffer.length();i++)
                {
                    char c = stringBuffer.charAt(i);
                    out.write(c);
                    out.flush(); // 立即将字符输出到客户端
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            if(null != out)
            {
                out.close();
            }
        }
    }

}