注册千帆大模型
首先就是注册百度的千帆大模型平台,第一次注册会送一张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); }
tokenapiclijsonbaiduapp百度智能create大模型stemchatjavaparseapi接口在线服务seooauth