java如何调用AI——百度智能云千帆大模型
首先要去官方百度智能大模型申请网上有教程在这里就不展示了,申请成功后,在Java中引入依赖:
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.28</version>
</dependency>
版本号选择自己合适的,接下来就将下面的代码写进自己的类中即可:
package utils;
import com.alibaba.fastjson.JSONObject;
import java.io.*;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpRequest {
/**
* post/GET远程请求接口并得到返回结果
*
* @param requestUrl 请求地址
* @param requestMethod 请求方法post/GET
* @return
*/
public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr,String contentType) {
JSONObject jsonObject = null;
StringBuffer buffer = new StringBuffer();
try {
URL url = new URL(requestUrl);
HttpURLConnection httpUrlConn = (HttpURLConnection)url.openConnection();
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
// 设置请求方式(GET/POST)
httpUrlConn.setRequestMethod(requestMethod);
//设置头信息
// httpUrlConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
httpUrlConn.setRequestProperty("Content-Type",contentType);
httpUrlConn.setRequestProperty("Accept","application/json;charset=UTF-8");
// 设置连接主机服务器的超时时间:15000毫秒
httpUrlConn.setConnectTimeout(15000);
// 设置读取远程返回的数据时间:60000毫秒
httpUrlConn.setReadTimeout(60000);
if ("GET".equalsIgnoreCase(requestMethod)){
httpUrlConn.connect();
}
// 当有数据需要提交时
if (null != outputStr) {
OutputStream outputStream = httpUrlConn.getOutputStream();
// 注意编码格式,防止中文乱码
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
// 将返回的输入流转换成字符串
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 释放资源
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
jsonObject = JSONObject.parseObject(buffer.toString());
} catch (ConnectException ce) {
} catch (Exception e) {
}
return jsonObject;
}
}
package utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
public class GPT {
static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();
public static void main(String []args) throws IOException{
//1、获取token
String access_token = new GPT().getWenxinToken();
//2、访问数据
String requestMethod = "POST";
//设置要传的信息
String body = URLEncoder.encode("junshi","UTF-8");
String url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/eb-instant?access_token="+access_token;//post请求时格式
//测试:访问聚合数据的地区新闻api
HashMap<String, String> msg = new HashMap<>();
msg.put("role","user");
msg.put("content", "请问1+1等于几?");
ArrayList<HashMap> messages = new ArrayList<>();
messages.add(msg);
HashMap<String, Object> requestBody = new HashMap<>();
requestBody.put("messages", messages);
String outputStr = JSON.toJSONString(requestBody);
JSON json = HttpRequest.httpRequest(url,requestMethod,outputStr,"application/json");
System.out.println(json);
}
public String getWenxinToken() throws IOException {
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "");
Request request = new Request.Builder()
.url("https://aip.baidubce.com/oauth/2.0/token?client_id=*********&client_secret=*********&grant_type=client_credentials") //按官网要求填写你申请的key和相关秘钥
.method("POST", body)
.addHeader("Content-Type", "application/json")
.addHeader("Accept", "application/json")
.build();
Response response = HTTP_CLIENT.newCall(request).execute();
String s = response.body().string();
JSONObject objects = JSONArray.parseObject(s);
String msg = objects.getString("access_token");
return msg;
}
}
调用测试一下 :
package utils;
import java.io.IOException;
public class MainClass {
public static void main(String[] args) throws IOException {
try {
GPT GPT = new GPT();
GPT.main(args);
} catch (IOException e) {
e.printStackTrace();
}
}
}