SpringBoot调用ChatGPT-API实现智能对话

目录

一、说明

二、代码

2.1、对话测试

2.2、单次对话

2.3、连续对话

2.4、AI绘画


一、说明

我们在登录chatgpt官网进行对话是不收费的,但需要魔法。在调用官网的API时,在代码层面上使用,通过API KEY进行对话是收费的,不过刚注册的小伙伴有免费5美金的体验额度,在不调用绘画模型,只是做为简单的问答,个人使用是没问题的。

ChatGPT官网

API使用情况

二、代码

2.1、对话测试

Gpt35TurboVO

import lombok.Data;@Data
public class Gpt35TurboVO {private String role;     // 角色一般为 userprivate String content;  // 询问内容
}

Controller

    @GetMapping(value = "/test", produces = "text/event-stream;charset=UTF-8")public String test(@RequestParam String message) {//回复用户String apikey = "sk-****";//请求ChatGPT的URLString url = "https://api.openai.com/v1/chat/completions";Gpt35TurboVO gpt35TurboVO = new Gpt35TurboVO();gpt35TurboVO.setRole("user");gpt35TurboVO.setContent(message);List<Gpt35TurboVO> objects = new ArrayList<>();objects.add(gpt35TurboVO);Map<Object, Object> objectObjectHashMap = new HashMap<>();objectObjectHashMap.put("model", "gpt-3.5-turbo");  //使用的模型objectObjectHashMap.put("messages", objects);       //提问信息objectObjectHashMap.put("stream", false);            //流objectObjectHashMap.put("temperature", 0);          //GPT回答温度(随机因子)objectObjectHashMap.put("frequency_penalty", 0);    //重复度惩罚因子objectObjectHashMap.put("presence_penalty", 0.6);   //控制主题的重复度String postData = JSONUtil.toJsonStr(objectObjectHashMap);String result2 = HttpRequest.post(url).header("Authorization", "Bearer " + apikey)//头信息,多个头信息多次调用此方法即可.header("Content-Type", "application/json").body(postData)//表单内容.timeout(200000)//超时,毫秒.execute().body();System.out.println(result2);return result2;}

返回结果

2.2、单次对话

ChatBotSingleQuestionVO

import lombok.Data;/*** 应用管理-单次提问-VO* @author lf* @date 2023/8/18*/
@Data
public class ChatBotSingleQuestionVO {/*** 用户输入的询问内容*/private String prompt;/*** 角色扮演ID*/private Integer rolePlayId;}

Redis锁工具类

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;import java.util.concurrent.TimeUnit;/*** redis锁工具类** @author ruoyi*/
@Component
public class RedisLock {@Autowiredprivate RedissonClient redissonClient;/*** 获取锁** @param lockKey 锁实例key* @return 锁信息*/public RLock getRLock(String lockKey) {return redissonClient.getLock(lockKey);}/*** 加锁** @param lockKey 锁实例key* @return 锁信息*/public RLock lock(String lockKey) {RLock lock = getRLock(lockKey);lock.lock();return lock;}/*** 加锁** @param lockKey   锁实例key* @param leaseTime 上锁后自动释放锁时间* @return true=成功;false=失败*/public Boolean tryLock(String lockKey, long leaseTime) {return tryLock(lockKey, 0, leaseTime, TimeUnit.SECONDS);}/*** 加锁** @param lockKey   锁实例key* @param leaseTime 上锁后自动释放锁时间* @param unit      时间颗粒度* @return true=加锁成功;false=加锁失败*/public Boolean tryLock(String lockKey, long leaseTime, TimeUnit unit) {return tryLock(lockKey, 0, leaseTime, unit);}/*** 加锁** @param lockKey   锁实例key* @param waitTime  最多等待时间* @param leaseTime 上锁后自动释放锁时间* @param unit      时间颗粒度* @return true=加锁成功;false=加锁失败*/public Boolean tryLock(String lockKey, long waitTime, long leaseTime, TimeUnit unit) {RLock rLock = getRLock(lockKey);boolean tryLock = false;try {tryLock = rLock.tryLock(waitTime, leaseTime, unit);} catch (InterruptedException e) {return false;}return tryLock;}/*** 释放锁** @param lockKey 锁实例key*/public void unlock(String lockKey) {RLock lock = getRLock(lockKey);lock.unlock();}/*** 释放锁** @param lock 锁信息*/public void unlock(RLock lock) {lock.unlock();}
}

Controller

    @PostMapping("/chatBotSingleQuestion/api")public AjaxResult chatBotSingleQuestion(@RequestBody ChatBotSingleQuestionVO chatBotSingleQuestionVO) {String answerContent = iChatBotSingleQuestionService.chatBotSingleQuestion(chatBotSingleQuestionVO);return success("success", answerContent);}

Impl

    /*** 应用管理-用户单次提问-不支持续问对话* @param chatBotSingleQuestionVO* @return*/@Override@Transactionalpublic String chatBotSingleQuestion(ChatBotSingleQuestionVO chatBotSingleQuestionVO) {if (Objects.isNull(chatBotSingleQuestionVO.getRolePlayId())){throw new RuntimeException("参数不可为空");}String lockName = "QA_" + SecurityUtils.getUserId();//回答的内容String answerContent = "";try{RLock rLock = redisLock.getRLock(lockName);boolean locked = rLock.isLocked();if (locked) {throw new RuntimeException("正在回复中...");}//对同一用户访问加锁redisLock.lock(lockName);this.chatBefore(chatBotSingleQuestionVO);InputStream is = this.sendRequestBeforeChat(chatBotSingleQuestionVO);String line = "";BufferedReader reader = new BufferedReader(new InputStreamReader(is));while ((line = reader.readLine()) != null) {//首先对行数据进行处理if (StrUtil.isNotBlank(line) &&!StrUtil.equals(line, "event: answer") &&!StrUtil.equals(line, "event: chatResponse") &&!StrUtil.contains(line, "data: {\"quoteLen\"")) {line = CollectionUtil.removeEmpty(StrUtil.split(line, "data: ")).get(0);if (!StrUtil.contains(line, "[DONE]")) {String oneWord = catchTextGpt(line);if (StrUtil.isNotBlank(oneWord)) {answerContent = answerContent + oneWord;}}WebSocketService.sendInfo(line, SecurityUtils.getUserId() + "");TimeUnit.MILLISECONDS.sleep(50);}}//处理完了后将次条聊天记录进行记录if (StrUtil.isNotBlank(answerContent)) {//保存聊天记录this.saveDialogueProcess(chatBotSingleQuestionVO, answerContent);//更新提问次数this.upddateAppModel(chatBotSingleQuestionVO);}is.close();reader.close();} catch (Exception e) {throw new RuntimeException(e.getMessage());}finally {redisLock.unlock(lockName);}return answerContent;}

sendRequestBeforeChat方法

    /*** 这块为问询,不包含对话模式** @param chatBotSingleQuestionVO* @return* @throws Exception*/@Transactionalpublic InputStream sendRequestBeforeChat(ChatBotSingleQuestionVO chatBotSingleQuestionVO) throws Exception {InputStream in = null;// 通知内容添加文本铭感词汇过滤//其余错误见返回码说明//正常返回0//违禁词检测this.disableWordCheck(chatBotSingleQuestionVO.getPrompt());String apikeyRefresh = getOpenAiKey();if (StrUtil.isBlank(apikeyRefresh)) {throw new RuntimeException("无可用key");}List<Gpt35TurboVO> chatContext = this.getChatContext(chatBotSingleQuestionVO);String requestUrl = iTbKeyManagerService.getproxyUrl();Map<Object, Object> objectObjectHashMap = new HashMap<>();objectObjectHashMap.put("model", "gpt-3.5-turbo");objectObjectHashMap.put("messages", chatContext);objectObjectHashMap.put("stream", true);objectObjectHashMap.put("temperature", 0);objectObjectHashMap.put("frequency_penalty", 0);objectObjectHashMap.put("presence_penalty", 0.6);String bodyJson = JSONUtil.toJsonStr(objectObjectHashMap);URL url = new URL(requestUrl); // 接口地址HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();urlConnection.setRequestMethod("POST");urlConnection.setDoOutput(true);urlConnection.setDoInput(true);urlConnection.setUseCaches(false);urlConnection.setRequestProperty("Connection", "Keep-Alive");urlConnection.setRequestProperty("Charset", "UTF-8");urlConnection.setRequestProperty("Authorization", "Bearer " + apikeyRefresh);urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");byte[] dataBytes = bodyJson.getBytes();urlConnection.setRequestProperty("Content-Length", String.valueOf(dataBytes.length));OutputStream os = urlConnection.getOutputStream();os.write(dataBytes);in = new BufferedInputStream(urlConnection.getInputStream());os.flush();os.close();return in;}

catchTextGpt方法

    /*** 处理单独打印的文字** @param str* @return*/public String catchTextGpt(String str) {String choices = JsonUtil.parseMiddleData(str, "choices");JSONArray jsonArray = JSONUtil.parseArray(choices);String string = jsonArray.getByPath("[0].delta").toString();String content = JsonUtil.parseMiddleData(string, "content");return content;}

getChatContext方法

    /*** 角色扮演* @param chatBotSingleQuestionVO* @return 结果*/public List<Gpt35TurboVO> getChatContext(ChatBotSingleQuestionVO chatBotSingleQuestionVO) {List<Gpt35TurboVO> messages = new ArrayList<>();//首先获取角色,设置默认角色String default_role_content = iconfigService.selectConfigByKey("default_role");if (StrUtil.isBlank(default_role_content)) {default_role_content = "我是一个全能机器人,可以回答你任何问题";}TbAppModel tbAppModel = iTbAppModelService.selectTbAppModelById(Long.valueOf(chatBotSingleQuestionVO.getRolePlayId()));if (!Objects.isNull(tbAppModel)){default_role_content = tbAppModel.getAppModelContent();}//小程序专用//是否通过微信小程序审核的设定语String is_open_pass_wx_promt = iconfigService.selectConfigByKey("is_open_pass_wx_promt");if (StrUtil.isNotBlank(is_open_pass_wx_promt) && !StrUtil.equals(is_open_pass_wx_promt, "0")) {String pass_wx_promt = iconfigService.selectConfigByKey("pass_wx_promt");default_role_content = default_role_content + "。并且你必须遵循:" + pass_wx_promt;}//设定系统所扮演的角色Gpt35TurboVO gpt35TurboVOSys = new Gpt35TurboVO();gpt35TurboVOSys.setRole("system");gpt35TurboVOSys.setContent(default_role_content);messages.add(gpt35TurboVOSys);//最后查询用户最新询问的问题Gpt35TurboVO gpt35TurboUser = new Gpt35TurboVO();gpt35TurboUser.setRole("user");gpt35TurboUser.setContent(chatBotSingleQuestionVO.getPrompt());messages.add(gpt35TurboUser);return messages;}

getOpenAiKey方法

    /*** 查询key是否可用* @return 结果*/public String getOpenAiKey() {//模仿查到的key集合TbKeyManager tbKeyManager = new TbKeyManager();tbKeyManager.setIsUse(1);//可用的keyList<TbKeyManager> tbKeyManagers = iTbKeyManagerService.selectTbKeyManagerList(tbKeyManager);//判断是否key额度用完if (CollectionUtil.isEmpty(tbKeyManagers) || tbKeyManagers.size() <= 0) {throw new RuntimeException("key额度耗尽");}//获取第一个key,然后将第一个key存入缓存String key = tbKeyManagers.get(0).getSecretKey();redisTemplate.opsForValue().set("apikey", key);//检查keychangeKey(tbKeyManagers.get(0));return key;}

2.3、连续对话

Controller

    @PostMapping(value = "/chatBotNoId/api")public AjaxResult continuousDialogue(@RequestBody StreamParametersVO streamParametersVO) {String answerContent = iChatGtpService.continuousDialogueSocketStream(streamParametersVO);return success("success", answerContent);}

Impl

    /*** 用户直接发起连续对话,系统同意创建对话主题,用户不用手动新建主题** @param streamParametersVO*/@Overridepublic String continuousDialogueSocketStream(StreamParametersVO streamParametersVO) {//判断是否isNewOpen填写参数,表示是否先开对话if (Objects.isNull(streamParametersVO.getIsNewOpen())) {throw new RuntimeException("isNewOpen参数未填");}if (streamParametersVO.getIsNewOpen()) {//新开对话,创建新的对话主题tbModelTable = new TbModelTable();//主题名称tbModelTable.setModelName("Dialogue_" + SecurityUtils.getUserId() + "_" + DateTime.now());//设置模板角色if (Objects.nonNull(streamParametersVO.getDialogueRoleId())) {tbModelTable.setId(Long.valueOf(streamParametersVO.getDialogueRoleId()));} else {tbModelTable.setId(1L);}tbDialogueMain = tbDialogueMainService.creatNewDig(tbModelTable);} else {//非新开对话,查询本次的对话主题TbDialogueMain tbDialogueMainParam = new TbDialogueMain();//设置模板角色if (Objects.nonNull(streamParametersVO.getDialogueRoleId())) {tbDialogueMainParam.setDialogueRoleId(Long.valueOf(streamParametersVO.getDialogueRoleId()));} else {tbDialogueMainParam.setDialogueRoleId(1L);}tbDialogueMainParam.setUserId(SecurityUtils.getUserId());List<TbDialogueMain> tbDialogueMains = iTbDialogueMainService.selectTbDialogueMainList(tbDialogueMainParam);if (CollectionUtil.isEmpty(tbDialogueMains)) {//创建新的对话主题tbModelTable = new TbModelTable();//主题名称tbModelTable.setModelName("Dialogue_" + SecurityUtils.getUserId() + "_" + DateTime.now());//设置模板角色tbModelTable.setId(Long.valueOf(streamParametersVO.getDialogueRoleId()));tbDialogueMain = tbDialogueMainService.creatNewDig(tbModelTable);} else {tbDialogueMain = tbDialogueMains.get(0);}}//设置对话IDstreamParametersVO.setDialogueId(tbDialogueMain.getId());String lockName = "chat_" + SecurityUtils.getUserId();//回答的内容String answerContent = "";try {RLock rLock = redisLock.getRLock(lockName);boolean locked = rLock.isLocked();if (locked) {throw new RuntimeException("正在回复中...");}//对同一用户访问加锁redisLock.lock(lockName);//进来做校验TbDialogueMain tbDialogueMain = this.paramVerify(streamParametersVO);String userId = SecurityUtils.getUserId() + "";//将提问数据封装为流,并请求OpenAI的接口InputStream inputStream = this.sendRequestBefore(streamParametersVO, tbDialogueMain);String line = null;BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));while ((line = reader.readLine()) != null) {//首先对行数据进行处理if (StrUtil.isNotBlank(line) &&!StrUtil.equals(line, "event: answer") &&!StrUtil.equals(line, "event: chatResponse") &&!StrUtil.contains(line, "data: {\"quoteLen\"")) {line = CollectionUtil.removeEmpty(StrUtil.split(line, "data: ")).get(0);if (StrUtil.contains(line, "[DONE]")) {} else {String oneWord = catchTextGpt(line);if (StrUtil.isNotBlank(oneWord)) {answerContent = answerContent + oneWord;}}WebSocketService.sendInfo(line, userId);TimeUnit.MILLISECONDS.sleep(50);}}//处理完了后,将此条聊天记录进行保存if (StrUtil.isNotBlank(answerContent)) {//保存聊天记录this.saveDig(streamParametersVO, answerContent);}inputStream.close();reader.close();} catch (Exception e) {throw new RuntimeException(e.getMessage());} finally {//解锁redisLock.unlock(lockName);//清除正在问话的标识redisTemplate.delete(SecurityUtils.getUserId() + "");}return answerContent;}

sendRequestBefore方法

    /*** 这块为 - 流对话模式的封装** @param streamParametersVO* @param tbDialogueMain* @return* @throws Exception*/@Transactionalpublic InputStream sendRequestBefore(StreamParametersVO streamParametersVO, TbDialogueMain tbDialogueMain) throws Exception {InputStream in = null;//提问内容String prompt = streamParametersVO.getPrompt();// 获取当前的用户String userId = SecurityUtils.getUserId() + "";Object o = redisTemplate.opsForValue().get(userId);if (!Objects.isNull(o)) {throw new RuntimeException("正在回复");}redisTemplate.opsForValue().set(userId, true, 30, TimeUnit.SECONDS);if (StrUtil.isBlank(prompt)) {throw new RuntimeException("输入内容为空");}// 通知内容添加文本铭感词汇过滤// 其余错误见返回码说明// 违禁词检测 正常返回0this.disableWordCheck(prompt);String apikeyRefresh = getOpenAiKey();if (StrUtil.isBlank(apikeyRefresh)) {throw new RuntimeException("无可用key");}//处理提问内容(指定系统角色+对话上下文+最新的提问内容)List<Gpt35TurboVO> chatContext = this.getChatDigContext(streamParametersVO, tbDialogueMain);String requestUrl = iTbKeyManagerService.getproxyUrl();Map<Object, Object> objectObjectHashMap = new HashMap<>();objectObjectHashMap.put("model", "gpt-3.5-turbo");objectObjectHashMap.put("messages", chatContext);objectObjectHashMap.put("stream", true);objectObjectHashMap.put("temperature", 0);objectObjectHashMap.put("frequency_penalty", 0);objectObjectHashMap.put("presence_penalty", 0.6);String bodyJson = JSONUtil.toJsonStr(objectObjectHashMap);URL url = new URL(requestUrl); // 接口地址HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();urlConnection.setRequestMethod("POST");urlConnection.setDoOutput(true);urlConnection.setDoInput(true);urlConnection.setUseCaches(false);urlConnection.setRequestProperty("Connection", "Keep-Alive");urlConnection.setRequestProperty("Charset", "UTF-8");urlConnection.setRequestProperty("Authorization", "Bearer " + apikeyRefresh);urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");byte[] dataBytes = bodyJson.getBytes();urlConnection.setRequestProperty("Content-Length", String.valueOf(dataBytes.length));OutputStream os = urlConnection.getOutputStream();os.write(dataBytes);in = new BufferedInputStream(urlConnection.getInputStream());os.flush();os.close();return in;}

getChatDigContext方法

    /*** 获取对话上下文** @param streamParametersVO* @return*/public List<Gpt35TurboVO> getChatDigContext(StreamParametersVO streamParametersVO, TbDialogueMain tbDialogueMain) {List<Gpt35TurboVO> messages = new ArrayList<>();//首先获取角色,默认角色String default_role_content = iconfigService.selectConfigByKey("default_role");if (StrUtil.isBlank(default_role_content)) {default_role_content = "我是一个全能机器人,可以回答你任何问题";}//根据用户传递过来的Id查询角色模型数据TbModelTable tbModelTable = iTbModelTableService.selectTbModelTableById(tbDialogueMain.getDialogueRoleId());if (!Objects.isNull(tbModelTable)) {default_role_content = tbModelTable.getModelContent();}//小程序专用//是否通过微信小程序审核的设定语String is_open_pass_wx_promt = iconfigService.selectConfigByKey("is_open_pass_wx_promt");if (StrUtil.isNotBlank(is_open_pass_wx_promt) && !StrUtil.equals(is_open_pass_wx_promt, "0")) {String pass_wx_promt = iconfigService.selectConfigByKey("pass_wx_promt");default_role_content = default_role_content + "。并且你必须遵循:" + pass_wx_promt;}//设定系统所扮演的角色Gpt35TurboVO gpt35TurboVOSys = new Gpt35TurboVO();gpt35TurboVOSys.setRole("system");gpt35TurboVOSys.setContent(default_role_content);messages.add(gpt35TurboVOSys);//然后查询当前对话的上下文数据TbDialogueProcessTbDialogueProcess tbDialogueProcess = new TbDialogueProcess();tbDialogueProcess.setSessionId(streamParametersVO.getDialogueId());tbDialogueProcess.setUserId(SecurityUtils.getUserId());String default_context_num = iconfigService.selectConfigByKey("default_context_num");if (StrUtil.isBlank(default_context_num) || !NumberUtil.isNumber(default_context_num)) {default_context_num = "10";}tbDialogueProcess.setLimitNum(Integer.valueOf(default_context_num));//根据对话ID和用户ID查询到对话列表-根据时间倒叙获取后几条设定的数据List<TbDialogueProcess> tbDialogueProcessesDesc = iTbDialogueProcessService.selectTbDialogueProcessListByLimitDesc(tbDialogueProcess);if (CollectionUtil.isNotEmpty(tbDialogueProcessesDesc)) {//获取到倒数10条数据后将数据正序配好List<TbDialogueProcess> tbDialogueProcesses = tbDialogueProcessesDesc.stream().sorted(Comparator.comparing(TbDialogueProcess::getCreateTime)).collect(Collectors.toList());for (TbDialogueProcess tbDialogueProcessfor : tbDialogueProcesses) {Gpt35TurboVO gpt35TurboUser = new Gpt35TurboVO();//用户询问的问题gpt35TurboUser.setRole("user");gpt35TurboUser.setContent(tbDialogueProcessfor.getAskContent());messages.add(gpt35TurboUser);//机器人回答的问题Gpt35TurboVO gpt35TurAssistant = new Gpt35TurboVO();gpt35TurAssistant.setRole("assistant");gpt35TurAssistant.setContent(tbDialogueProcessfor.getAnswerContent());messages.add(gpt35TurAssistant);}}//最后查询用户最新询问的问题Gpt35TurboVO gpt35TurboUser = new Gpt35TurboVO();gpt35TurboUser.setRole("user");gpt35TurboUser.setContent(streamParametersVO.getPrompt());messages.add(gpt35TurboUser);return messages;}

2.4、AI绘画

Controller

    @PostMapping("/image/api")public AjaxResult imageApi(@RequestBody StreamImageParametersVO streamImageParametersVO) {String answerContent = iChatGptImageService.imageSocketStream(streamImageParametersVO);return success("success",answerContent);}

Impl

    @Overridepublic String imageSocketStream(StreamImageParametersVO imageParametersVO) {String lockName = "image_" + SecurityUtils.getUserId();String answerContent = "";try{RLock rLock = redisLock.getRLock(lockName);boolean locked = rLock.isLocked();if (locked){throw new RuntimeException("回复中");}//对同一用户访问加锁redisLock.lock(lockName);//校验是否输入内容,次数扣减this.imageBefore(imageParametersVO);String userId = SecurityUtils.getUserId() + "";InputStream is = this.sendRequestBeforeImage(imageParametersVO);String line = null;BufferedReader reader = new BufferedReader(new InputStreamReader(is));while((line = reader.readLine()) != null){//数据处理if (StrUtil.isNotBlank(line) &&!StrUtil.equals(line, "event: answer") &&!StrUtil.equals(line, "event: chatResponse") &&!StrUtil.contains(line, "data: {\"quoteLen\"")) {line = CollectionUtil.removeEmpty(StrUtil.split(line, "data: ")).get(0);if (StrUtil.contains(line, "[DONE]")){}else{String oneWord = catchUrlImage(line);if (StrUtil.isNotBlank(oneWord)){answerContent = answerContent + oneWord;}}WebSocketService.sendInfo(line,userId);TimeUnit.MILLISECONDS.sleep(50);}}//处理完之后将次条聊天记录进行记录if (StrUtil.isNotBlank(answerContent)){//保存聊天记录this.saveDialogueLog(imageParametersVO, answerContent);}is.close();reader.close();}catch (Exception e){throw new RuntimeException(e.getMessage());}finally {//解锁redisLock.unlock(lockName);redisTemplate.delete(SecurityUtils.getUserId() + "");}return saveImageUrl(jsonImageUrl(answerContent));}

sendRequestBeforeImage方法

    /*** 问询,不包含对话模式*/@Transactionalpublic InputStream sendRequestBeforeImage(StreamImageParametersVO imageParametersVO) throws Exception{InputStream in = null;//通知内容添加文本敏感词汇过滤//其余错误见返回码说明//正常返回0//违禁词检测this.disbleWordImageCheck(imageParametersVO.getPrompt());String apikeyRefresh =  getOpenAiKey();if (StrUtil.isBlank(apikeyRefresh)){throw new RuntimeException("无可用key");}//        List<Gpt35TurboVO> imageContext = this.getImageContext(imageParametersVO);String requestImageUrl = iTbKeyManagerService.getImageProxyUrl();Map<Object, Object> objectObjecHashtMap = new HashMap<>();objectObjecHashtMap.put("prompt", imageParametersVO.getPrompt());objectObjecHashtMap.put("n", 1);objectObjecHashtMap.put("size", "1024x1024");String bodyJson = JSONUtil.toJsonStr(objectObjecHashtMap);URL url = new URL(requestImageUrl); //接口地址HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();urlConnection.setRequestMethod("POST");urlConnection.setDoOutput(true);urlConnection.setDoInput(true);urlConnection.setUseCaches(false);urlConnection.setRequestProperty("Connection", "Keep-Alive");urlConnection.setRequestProperty("Charset", "UTF-8");urlConnection.setRequestProperty("Authorization", "Bearer " + apikeyRefresh);urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");byte[] dataBytes = bodyJson.getBytes();urlConnection.setRequestProperty("Content-Length", String.valueOf(dataBytes.length));OutputStream os = urlConnection.getOutputStream();os.write(dataBytes);in = new BufferedInputStream(urlConnection.getInputStream());os.flush();os.close();return in;}

catchUrlImage方法

    /*** 对链接地址处理*/public String catchUrlImage(String str){return str;}

图片处理,chatgpt返回的图片有效期是五分钟,我们需要将图片下载至本地或服务器。

    /*** 保存图片返回的结果*/public String saveImageUrl(String jsonUrl){String imageURL = uploadFileImageAi(jsonUrl);// 找到下划线的索引位置int underscoreIndex = imageURL.indexOf('_');String result = "";if (underscoreIndex != -1) {// 截取从下划线的位置开始到字符串的末尾result = imageURL.substring(underscoreIndex - 9);} else {throw new RuntimeException("图片链接截取失败");}return TomcatConfig.getImageAiUrl() + "/" + result;}/*** 图片处理* @param imageUrl* @return*/public String uploadFileImageAi(String imageUrl){//        //服务器文件上传路径String path = TomcatConfig.setUploadImageAiUrl() + Constants.DRAW_PREFIX + "_" + Seq.getId(Seq.uploadSeqType) + ".png";
//        本地文件上传路径
//        String path = "D:\\BaiduNetdiskDownload\\image-use\\" + Constants.DRAW_PREFIX + "_" + Seq.getId(Seq.uploadSeqType) + ".png";try{URL url = new URL(imageUrl);HttpURLConnection connection = (HttpURLConnection) url.openConnection();int responseCode = connection.getResponseCode();if (responseCode == HttpURLConnection.HTTP_OK) {InputStream inputStream = connection.getInputStream();OutputStream outputStream = new FileOutputStream(path);byte[] buffer = new byte[4096];int bytesRead;while ((bytesRead = inputStream.read(buffer)) != -1) {outputStream.write(buffer, 0, bytesRead);}outputStream.close();inputStream.close();} else {throw new RuntimeException("文件无法下载");}}catch (IOException e){e.printStackTrace();}return path;}/*** JSON数据处理* @param imageContent* @return*/public String jsonImageUrl(String imageContent){//解析json字符串JSONObject obj = JSON.parseObject(imageContent);//获取 "data"字段相应的JSON数组JSONArray dataArray = obj.getJSONArray("data");//获取第一个元素路径地址JSONObject dataObject = dataArray.getJSONObject(0);// 返回"url"字段的值return dataObject.getString("url");}

 

 

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/136873.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

基于Java社区生鲜电商平台设计实现(源码+lw+部署文档+讲解等)

博主介绍&#xff1a;✌全网粉丝30W,csdn特邀作者、博客专家、CSDN新星计划导师、Java领域优质创作者,博客之星、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java技术领域和毕业项目实战✌ &#x1f345;文末获取源码联系&#x1f345; &#x1f447;&#x1f3fb; 精彩专…

网络爬虫-----爬虫的分类及原理

目录 爬虫的分类 1.通用网络爬虫&#xff1a;搜索引擎的爬虫 2.聚焦网络爬虫&#xff1a;针对特定网页的爬虫 3.增量式网络爬虫 4.深层网络爬虫 通用爬虫与聚焦爬虫的原理 通用爬虫&#xff1a; 聚焦爬虫&#xff1a; 爬虫的分类 网络爬虫按照系统结构和实现技术&#…

所有人别错过!云计算真的不错,前景钱途并存!

近年来&#xff0c;中国云计算产业发展迅猛&#xff0c;保持30%以上的年均增长率&#xff0c;成为全球增速最快的市场之一&#xff0c;云计算应用领域正向制造、政务、金融、医疗、教育等企业级市场延伸拓展。目前&#xff0c;云计算应用的普及促使开源技术广受关注&#xff0c…

Linux内核源码分析 (B.5)推演 slab 内存池的设计与实现

Linux内核源码分析 (B.5)推演 slab 内存池的设计与实现 文章目录 Linux内核源码分析 (B.5)推演 slab 内存池的设计与实现[toc] 1\. 前文回顾2\. 既然有了伙伴系统&#xff0c;为什么还需要 Slab ?3\. slab 对象池在内核中的应用场景4\. slab, slub, slob 傻傻分不清楚5\. 从一…

C语言的编译过程详解

当我们编译C程序时会发生什么&#xff1f;编译过程中的组件有哪些&#xff0c;编译执行过程是什么样的? 什么是编译 C语言的编译过程就是把我们可以理解的高级语言代码转换为计算机可以理解的机器代码的过程&#xff0c;其实就是一个翻译的过程。 …

低噪声 256 细分微步进电机驱动MS35774/MS35774A(汽车应用级别)

MS35774/MS35774A 是一款高精度、低噪声的两相步进 电机驱动芯片&#xff0c;芯片内置功率 MOSFET&#xff0c;长时间工作的平均电 流可以达到 1.4A&#xff0c;峰值电流 2A。芯片集成了过温保护、欠压 保护、过流保护、短地保护、短电源保护功能。 主要特点 ◼ 2 相步进电机…

揭秘期权卖方稳赚的方法策略!

期权的卖方&#xff08;也称为房东包租婆&#xff09;是指出售期权合约的人&#xff0c;其赚取的费用被称为期权权利金。也就是房租租金&#xff0c;作为卖方&#xff0c;您有义务在期限内按照合约规定的价格出售或购买标的资产&#xff0c;下文介绍期权卖方稳赚的方法策略有哪…

国外发达国家码农是真混得好么?

来看看花旗工作十多年的码农怎么说吧! 美国最大的论坛 Reddit&#xff0c;之前有一个热帖&#xff1a; 一个程序员说自己喝醉了&#xff0c;软件工程师已经当了10年&#xff0c;心里有 好多话想说&#xff0c;“我可能会后悔今天说了这些话。”他洋洋洒洒写了 一大堆&#xff…

Hive内置函数字典

写在前面&#xff1a;HQL同SQL有很多的类似语法&#xff0c;同学熟悉SQL后一般学习起来非常轻松&#xff0c;写一篇文章列举常用函数&#xff0c;方便查找和学习。 1. 执行模式 1.1 Batch Mode 批处理模式 当使用-e或-f选项运行$ HIVE_HOME / bin / hive时&#xff0c;它将以…

数据挖掘十大算法

参考&#xff1a; ICDM&#xff1a;数据挖掘十大算法

1、RocketMQ概述

第1章 RocketMQ概述 一、MQ概述 1、MQ简介 MQ&#xff0c;Message Queue&#xff0c;是一种提供消息队列服务的中间件&#xff0c;也称为消息中间件&#xff0c;是一套提供了消息生 产、存储、消费全过程API的软件系统。消息即数据。一般消息的体量不会很大。 2、MQ用途 从网上…

AI文本创作在百度App发文的实践

作者 | 内容生态端团队 导读 大语言模型&#xff08;LLM&#xff09;指包含数百亿&#xff08;或更多&#xff09;参数的语言模型&#xff0c;这些模型通常在大规模数据集上进行训练&#xff0c;以提高其性能和泛化能力。在内容创作工具接入文心一言AI能力后&#xff0c;可以为…

无涯教程-JavaScript - SIGN函数

描述 SIGN功能确定数字的符号。该函数返回- 如果数字为正,则为1 如果数字为0,则零(0) -1,如果数字为负 语法 SIGN (number)争论 Argument描述Required/OptionalNumberAny real number.Required Notes 如果指定的数字未被识别为数字值,则SIGN返回#VALUE!错误。 适用性 …

阿里云通义千问向全社会开放,近期将开源更大参数规模大模型

9月13日&#xff0c;阿里云宣布通义千问大模型已首批通过备案&#xff0c;并正式向公众开放&#xff0c;广大用户可登录通义千问官网体验&#xff0c;企业用户可以通过阿里云调用通义千问API。 通义千问在技术创新和行业应用上均位居大模型行业前列。IDC最新的AI大模型评估报告…

网络路径监控分析

不间断的连接应该是任何企业的首要任务。然而&#xff0c;确保网络中的源和目标之间持续、不间断的联系一直是网络通信中一个劳动密集型的过程。了解网络路径中的障碍、识别它们并迅速解决它们以维护健康、不间断的网络至关重要。 为什么要监控网络路径 维护网络运行状况是任…

【 Linux】Linux调试器 - gdb

​ ​&#x1f4dd;个人主页&#xff1a;Sherry的成长之路 &#x1f3e0;学习社区&#xff1a;Sherry的成长之路&#xff08;个人社区&#xff09; &#x1f4d6;专栏链接&#xff1a;Linux &#x1f3af;长路漫漫浩浩&#xff0c;万事皆有期待 上一篇博客&#xff1a;【Linux】…

【Springboot】整合kafka

目录 安装zookeeperjdk安装zookeeper安装 安装kafka&#xff08;非集群&#xff09;springboot项目整合配置 安装zookeeper jdk安装 环境准备&#xff1a;CentOS7&#xff0c;jdk1.8 步骤如下&#xff1a; 下载自己需要的版本 这里使用的jdk1.8&#xff0c;获取链接如下 链接…

Spring Boot 自动注入失败的原因

问题 Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type com.sveinn.chatbotdomain.zsxq.service.ZsxqApi available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {ja…

HY57V561620FTP_SDRAM文档总结

文章目录 前言一、sdram简介1、名称解释2、发展历史3、与原先学习的RAM区别4、SDRAM分类 二、HY57V561620FTP1、描述1、内存划分2、特征3、引脚说明4、内部结构介绍5、交流特性6、可能涉及到的命令组合 2、SDRAM 具体操作流程1、整体状态图2、SDRAM指令及时序图3、芯片初始化(这…

MAML在隐式神经表示中的应用

论文 Learned Initializations for Optimizing Coordinate-Based Neural Representations &#x1f383;Abstract1. Introduction2. Related Work3. Overview ⭐4. Results5. Conclusion6. AcknowledgementsA. Implementation details Implicit Neural Representations for Ima…