java接入Chatgpt(文字聊天)

前言:

目前智能AI比较火热,国外的chatgpt,国内的文言一心,由网友需求,将接入案例记录分享,复制可以修改key可以直接使用

不熟悉或者不理解可以加入微信  nlks2023交流,文字聊天简单版,

        String querySimInfo = "https://api.openai.com/v1/audio/translations";
String key = "sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
//发送请求需要的参数
Map<String, Object> mapSimInfo = new HashMap<>();
List<Map<String,Object>> mapList=new ArrayList<>();
Map<String, Object> messageMap = new HashMap<>();
messageMap.put("role","user");
messageMap.put("content","How many people in China are called Zhang Jian");
mapList.add(messageMap);
mapSimInfo.put("model", "gpt-3.5-turbo");
mapSimInfo.put("messages", mapList);
mapSimInfo.put("temperature", 0.7);
JSONObject jsonObject = new JSONObject(mapSimInfo);
String body = jsonObject.toString();
PostMethod postMethod = new PostMethod(querySimInfo);
postMethod.setRequestHeader("Content-Type", "multipart/form-data");
postMethod.setRequestHeader("Authorization", "Bearer "+key);
StringRequestEntity requestEntity = new StringRequestEntity(body, "application/json", "UTF-8");
postMethod.setRequestEntity(requestEntity);
HttpClient httpClient = new HttpClient();
int response = httpClient.executeMethod(postMethod); // 执行POST方法
String result = postMethod.getResponseBodyAsString();//返回结果
logger.info("result===="+result);
HashMap hashMap = JSON.parseObject(result, HashMap.class);
String msg = (String) hashMap.get("msg");
logger.info("msg==="+msg);
logger.info("response===="+response);
}

 

posted @ 2023-05-19 14:57  心愿路自平  阅读(278)  评论(0编辑  收藏  举报