Java对接千帆平台Api实现问答
大模型开发/技术交流
- 开箱评测
- 社区上线
- API
2023.10.071733看过
一、开发准备
登录千帆平台并创建应用获取AppID、API Key、Secret Key。
二、代码实现
调用Api要先获取access_token,获取的代码如下
static String getAccessToken() throws IOException {MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY+ "&client_secret=" + SECRET_KEY);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 = HTTP_CLIENT.newCall(request).execute();return new JSONObject(response.body().string()).getString("access_token");}
获取access_token后调用交流的Api并解析结果代码如下
public static final String API_KEY = "AdjLc9****5f7G33";public static final String SECRET_KEY = "tTCd0V****lhkQWs";static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();public static void main(String []args) throws IOException{MediaType mediaType = MediaType.parse("application/json");RequestBody body = RequestBody.create(mediaType, "");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 = HTTP_CLIENT.newCall(request).execute();System.out.println(response.body().string());}
把代码中的API_KEY和SECRET_KEY换成自己创建应用的内容,body中换为要问的话
三、运行
运行结果如下
{"id": "as-prnv3yzqqm","object": "chat.completion","created": 1696657693,"result": "您好!我是百度研发的知识增强大语言模型,中文名是文心一言,英文名是ERNIE Bot。我能够与人对话互动,回答问题,协助创作,高效便捷地帮助人们获取信息、知识和灵感。","is_truncated": false,"need_clear_history": false,"usage": {"prompt_tokens": 2,"completion_tokens": 67,"total_tokens": 69}}
如果有报错请参考官方文档
评论