注册千帆大模型
首先就是注册百度的千帆大模型平台,第一次注册会送一张20元的优惠卷,可以用这个先免费用一段时间。
创建应用
- 目的:获得apikey和secretkey
- 注册以后进入到百度智能云控制台应用接入(百度智能云控制台 (baidu.com))这里。先在应用接入这里创建应用,接下来会用到你创建这个应用的apikey和secretkey。这个是可以重复访问的。
开通服务
- 目的:开通服务,获得请求地址
- 接下来进入到在线服务。要先开通服务后才能使用他的api接口来访问文心一言。
- 可以先到百度提供的api列表看看你要用哪个服务(api列表 - 千帆大模型平台 | 百度智能云文档 (baidu.com))。api鉴权及调用可以看服务介绍,平台计费可以看价格。选择一个开通付费就行。选择以后,在api鉴权及调用那里点击你选择的服务后面的“创建chat”。我以“ernie-3.5-8k”这个为例。点击进去后这个api采用两种鉴权方式,我用的是访问凭证access_token鉴权。这个要先获得access_token,然后再通过access_token调用api获得回复。待会需要用到文档里面的请求说明信息。不同服务的请求地址不同。
java对接文心一言代码实现
获得token
- 使用文心一言要先获得access_token,然后通过这个access_token再来调用文心一言。
- 百度有提供获得access_token的示例代码(百度智能云控制台 (baidu.com))。下面这个是我自己写的,都一样。
- 这个就要用到刚才创建应用时的apikey和secretkey。
/**
* 需要添加依赖
* <!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
* <dependency>
* <groupid>org.apache.httpcomponents</groupid>
* <artifactid>httpclient</artifactid>
* <version>4.5.14</version>
* </dependency>
*/
public string getwenxintoken() throws ioexception {
closeablehttpclient httpclient = httpclientbuilder.create().build();
string apikey = "";
string secretkey = "";
httppost post = new httppost("https://aip.baidubce.com/oauth/2.0/token?client_id="
+ apikey + "&client_secret=" + secretkey + "&grant_type=client_credentials");
post.addheader("content-type", "application/json");
post.addheader("accept", "application/json");
closeablehttpresponse response = httpclient.execute(post);
string s = entityutils.tostring(response.getentity());
jsonobject objects = jsonarray.parseobject(s);
string token = objects.getstring("access_token");
system.out.println("token:" + token);
return token;
}
获得文心一言回复
- 这个要用到请求说明里基本信息的请求地址。
public void wenxinyiyanapi() throws ioexception {
closeablehttpclient httpclient = httpclientbuilder.create().build();
// 1、获取token,就是调用上面的方法。
string access_token = new apitest().getwenxintoken();
// 2、看你开通的服务请求地址是什么,不一样在这里改。
httppost post = new httppost("https://aip.baidubce.com/rpc/2.0/" +
"ai_custom/v1/wenxinworkshop/chat/completions?access_token=" + access_token);
post.addheader("content-type", "application/json");
post.addheader("accept", "application/json");
// 3、问题内容。
string paramjson = "{\"messages\": [{\"role\": \"user\", " +
"\"content\": \"帮我写一个冒泡排序\"}]\n}";
stringentity stringentity = new stringentity(paramjson,
contenttype.create("application/json", "utf-8"));
post.setentity(stringentity);
closeablehttpresponse response = httpclient.execute(post);
string s = entityutils.tostring(response.getentity());
system.out.println("输出:" + s);
}
发表评论