/**
* 聊天端点
*/
String chatEndpoint = "https://api.openai.com/v1/chat/completions";
/**
* api密匙
*/
String apiKey = "sk-A84JvQtrsES3Vd*******************QHKQIyeHBQQJMy";
/**
* 发送消息
*
* @param txt 内容
* @return {@link String}
*/
public String chat(String txt) {
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("model", "gpt-3.5-turbo");
List<Map<String, String>> dataList = new ArrayList<>();
dataList.add(new HashMap<String, String>(){{
put("role", "user");
put("content", txt);
}});
paramMap.put("messages", dataList);
paramMap.put("temperature", 0.5); // 控制生成文本的随机性,数值越大越随机
paramMap.put("max_tokens", 60); // 控制生成文本的长度
paramMap.put("stop", "\n"); // 控制生成文本的停止条件
JSONObject message = null;
System.out.print("666");
try {
String body = HttpRequest.post(chatEndpoint)
.header("Authorization", "Bearer " + apiKey)
.header("Content-Type", "application/json")
.body(JSONUtil.toJsonStr(paramMap))
.setHttpProxy("127.0.0.1", 10800) // 设置代理(很关键)
.execute()
.body();
JSONObject jsonObject = JSONUtil.parseObj(body);
JSONArray choices = jsonObject.getJSONArray("choices");
JSONObject result = choices.get(0, JSONObject.class, Boolean.TRUE);
message = result.getJSONObject("message");
} catch (HttpException e) {
return "出现了异常";
} catch (ConvertException e) {
return "出现了异常";
}
System.out.println(message);
return message.getStr("content");
}
[笔记] 帮公司实习生做毕设调试ChatGPT访问

2023-8-17 3:16:50更新
收藏
THE END