首页 > 其他分享 >深度学习--调用chatgot接口实现

深度学习--调用chatgot接口实现

时间:2023-05-20 23:25:46浏览次数:35  
标签:String chatgot -- org 接口 new apache import com

首先,对于段落文字进行提取主要信息,第一反应要是电脑像人脑就行了,就想到chatgpt进行识别,以下为我识别的文字进行gpt转换。

实验结果成立,现在只需要将接口调用,将识别文字传入后,进行字符串拼接,加上:“提取支付时间,消费类型,消费内容”,传入gpt后,将结果返回,输入到程序上,进行识别即可。

理论成立,调查资料,先利用java实现

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ttpfx.vo.ChatGptMessage;
import com.ttpfx.vo.ChatGptRequestParameter;
import com.ttpfx.vo.ChatGptResponseParameter;
import com.ttpfx.vo.Choices;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.HttpHeaders;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
* @author ttpfx
* @date 2023/3/23
*/
public class CustomChatGpt {
/**
* 自己chatGpt的ApiKey
*/
private String apiKey;
/**
* 使用的模型
*/
private String model = "gpt-3.5-turbo-0301";
/**
* 对应的请求接口
*/
private String url = "https://api.openai.com/v1/chat/completions";
/**
* 默认编码
*/
private Charset charset = StandardCharsets.UTF_8;


/**
* 创建一个ChatGptRequestParameter,用于携带请求参数
*/
private ChatGptRequestParameter chatGptRequestParameter = new ChatGptRequestParameter();

/**
* 相应超时时间,毫秒
*/
private int responseTimeout = 1000;

public void setResponseTimeout(int responseTimeout) {
this.responseTimeout = responseTimeout;
}

public CustomChatGpt(String apiKey) {
this.apiKey = apiKey;
}

public String getAnswer(CloseableHttpClient client, String question) {

// 创建一个HttpPost
HttpPost httpPost = new HttpPost(url);
// 创建一个ObjectMapper,用于解析和创建json
ObjectMapper objectMapper = new ObjectMapper();

// 设置请求参数
chatGptRequestParameter.addMessages(new ChatGptMessage("user", question));
HttpEntity httpEntity = null;
try {
// 对象转换为json字符串
httpEntity = new StringEntity(objectMapper.writeValueAsString(chatGptRequestParameter), charset);
} catch (JsonProcessingException e) {
System.out.println(question + "->json转换异常");
return null;
}
httpPost.setEntity(httpEntity);


// 设置请求头
httpPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
// 设置登录凭证
httpPost.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + apiKey);

// 用于设置超时时间
RequestConfig config = RequestConfig
.custom()
.setResponseTimeout(responseTimeout, TimeUnit.MILLISECONDS)
.build();
httpPost.setConfig(config);
try {
// 提交请求
return client.execute(httpPost, response -> {
// 得到返回的内容
String resStr = EntityUtils.toString(response.getEntity(), charset);
// 转换为对象
ChatGptResponseParameter responseParameter = objectMapper.readValue(resStr, ChatGptResponseParameter.class);
String ans = "";
// 遍历所有的Choices(一般都只有一个)
for (Choices choice : responseParameter.getChoices()) {
ChatGptMessage message = choice.getMessage();
chatGptRequestParameter.addMessages(new ChatGptMessage(message.getRole(), message.getContent()));
String s = message.getContent().replaceAll("\n+", "\n");
ans += s;
}
// 返回信息
return ans;
});
} catch (IOException e) {
e.printStackTrace();
}
// 发生异常,移除刚刚添加的ChatGptMessage
chatGptRequestParameter.getMessages().remove(chatGptRequestParameter.getMessages().size()-1);
return "您当前的网络无法访问";
}
}

public class Test {

public static void main(String[] args) throws IOException {

CloseableHttpClient httpClient = HttpClients.createDefault();
String apiKey = "自己的ApiKey";
CustomChatGpt customChatGpt = new CustomChatGpt(apiKey);
// 根据自己的网络设置吧
customChatGpt.setResponseTimeout(20000);
while (true) {
System.out.print("\n请输入问题(q退出):");
String question = new Scanner(System.in).nextLine();
if ("q".equals(question)) break;
long start = System.currentTimeMillis();
String answer = customChatGpt.getAnswer(httpClient, question);
long end = System.currentTimeMillis();
System.out.println("该回答花费时间为:" + (end - start) / 1000.0 + "秒");
System.out.println(answer);
}
httpClient.close();
}
}

但是这代码实现,但是国内网址实现不了,甚至打不开,对于国内,要通过香港的ip地址进行转换,然后通过这个调用国外openai,正在努力实现,有了一个思路。

 

标签:String,chatgot,--,org,接口,new,apache,import,com
From: https://www.cnblogs.com/wudisanrenzu/p/17417993.html

相关文章

  • Java 网络编程 —— 实现非阻塞式的客户端
    创建阻塞的EchoClient客户程序一般不需要同时建立与服务器的多个连接,因此用一个线程,按照阻塞模式运行就能满足需求publicclassEchoClient{privateSocketChannelsocketChannel=null;publicEchoClient()throwsIOException{socketChannel......
  • redis-cli 使用lua脚本笔记
    前言众所周知,redis可以执行lua脚本,至于为什么要用lua脚本来操作redis,自行百度咯先来讲一下最简单的方式,关于如何在javaspringboot里用lua脚本,请查看我另一篇文章:https://www.cnblogs.com/daen/p/17418024.html更为详细的资料请参考以下文章https://blog.csdn.net/jiayibingd......
  • git命令
    git命令1.常用命令gitclone+要拉取的代码地址gitpulloriginmaster同步主分支gitlog查看loggitinit构建本地仓库gitstatus查看仓库状态gitadd文件将修改的内容添加到暂存区gitcommit-m+修改日志将修改的内容提交到仓库gitpush推送到......
  • 线性dp
    P1725琪露诺一道线性dp的题目状态设置:f[i]:表示到达位置i时的最大价值状态转移:f[i]=max(f[i],f[j]+a[i])(i-r=<j<=i-l)这样做显然枚举状态是O(n)转移也需要O(n),所以时间复杂度是O(n^2)的显然会T状态我们是一定要枚举的,我们能优化的只有转移的计算量,我们需要快速找到......
  • Set集合
    set集合一直以来,JS只能使用数组和对象来保存多个数据,缺乏像其他语言那样拥有丰富的集合类型。因此,ES6新增了两种集合类型(set和map),用于在不同的场景中发挥作用。set用于存放不重复的数据如何创建set集合newSet();//创建一个没有任何内容的set集合newSet(iterable);......
  • 光谱仪DIY制作
    一、光谱仪理论概览    光谱仪是一种用来测量光线中光学成分的仪器。它能够用来帮助科学家分析物质材料中的基本成份,或者也可以用来分析来自于远距离恒星、行星发出的光谱。    光谱仪的基本概念在于通过捕捉一束狭缝当中的未知波长光束,由于光束中不同波长的光束通过......
  • synchronized原理
    `synchronized`是Java中用来实现线程同步的关键字,它的主要作用是对代码块或方法进行加锁,保证在同一时刻只有一个线程能够执行被加锁的代码块或方法,从而避免多个线程同时访问共享资源导致的数据不一致问题。`synchronized`的实现原理是基于Java对象头中的monitor(监视器)实......
  • 2023.5.20
    今天学习了yolov5技术,但是配置还没弄好。哎。具体学习连接:yolov5环境准备  ......
  • .NET UTF-8与UTF-8-BOM编码
    MSDoc:UTF8Encoding类BOM与错误检测参数成员BOM错误检测Encoding.UTF8是无(替换回退)UTF8Encoding.UTF8Encoding()否无(替换回退)UTF8Encoding.UTF8Encoding(Boolean)可配置无(替换回退)UTF8Encoding.UTF8Encoding(Boolean,Boolean)可配置可配置......
  • 关于Java接口实现问题
    publicinterfaceInterfaceClass{/***jdk1.7只能有抽象方法,子类是**抽象类**时,方法就可以实现也可以不实现*/publicabstractvoidmethod();/***jdk1.8新增静态方法,默认方法**静态方法子类不能实现*/publicstaticvoidmethod1(){}/**......