文心一言API Java简单封装
大模型开发/技术交流
- API
- 社区上线
- 开箱评测
2023.10.071629看过
文心一言大模型API请求简单封装
由于官方未提供 Java 的 SDK,所以根据提供的http封装 成Java 的方法,开箱即用。只支持文心一言的模型(ernie-bot模型)
直接调用 api 即可。
使用
apiConfig apiConfig = new apiConfig();apiConfig.setApiKey("");apiConfig.setSecretKey("");apiService apiService = new apiService();apiService.setApiConfig(apiConfig);messages messages = new messages();messages.setRole("user");messages.setContent("世界上最大的中文搜索引擎");String s = apiService.ErnieBot(messages);System.out.println(s);
因为只有一个API所以没有封装成starter, Spring需要手动创建Bean。结果如下
具体代码为
@Datapublic class apiConfig {private String AppId;private String ApiKey;private String SecretKey;}
@Datapublic class messages {private String role;private String content;}
@Datapublic class apiService {private apiConfig apiConfig;private final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();public String ErnieBot(messages mess){MediaType mediaType = MediaType.parse("application/json");RequestBody body = RequestBody.create(mediaType, "{\"messages\":[" + JSON.toJSONString(mess) + "]}");Request request = new Request.Builder().url("https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token=" + getAccessToken()).method("POST", body).addHeader("Content-Type", "application/json").build();Response response = null;String re = "";try {response = HTTP_CLIENT.newCall(request).execute();re = new JSONObject(response.body().string()).getString("result");} catch (IOException e) {e.printStackTrace();}return re;}/*** 从用户的AK,SK生成鉴权签名(Access Token)** @return 鉴权签名(Access Token)* @throws IOException IO异常*/String getAccessToken(){MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + apiConfig.getApiKey()+ "&client_secret=" + apiConfig.getSecretKey());Request request = new Request.Builder().url("https://aip.baidubce.com/oauth/2.0/token").method("POST", body).addHeader("Content-Type", "application/x-www-form-urlencoded").build();Response response = null;String token = "";try {response = HTTP_CLIENT.newCall(request).execute();token = new JSONObject(response.body().string()).getString("access_token");} catch (IOException e) {e.printStackTrace();}return token;}}
评论