|
@@ -1,5 +1,9 @@
|
|
|
package com.qizhen.healsphere.common.ai;
|
|
|
|
|
|
+import cn.hutool.http.HttpRequest;
|
|
|
+import cn.hutool.http.HttpUtil;
|
|
|
+import cn.hutool.http.Method;
|
|
|
+import com.alibaba.fastjson.JSONObject;
|
|
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
|
import org.springframework.web.client.RestTemplate;
|
|
|
|
|
@@ -17,17 +21,53 @@ public class BaidubceUtil {
|
|
|
private final static ObjectMapper objectMapper = new ObjectMapper();
|
|
|
|
|
|
public static String getChatResponse(String userInput,String accessToken) {
|
|
|
+ int retry = 0;
|
|
|
+ try {
|
|
|
+ return getAnswer(userInput, accessToken);
|
|
|
+ }catch(Exception e){
|
|
|
+ e.printStackTrace();
|
|
|
+ retry++;
|
|
|
+ if(retry>=2){
|
|
|
+ return "";
|
|
|
+ }
|
|
|
+ return getAnswer(userInput, accessToken);
|
|
|
+ }
|
|
|
+
|
|
|
+ }
|
|
|
+
|
|
|
+ private static String getAnswer(String userInput,String accessToken) {
|
|
|
+ Map<String, String> headers = new HashMap<>();
|
|
|
+ headers.put("Content-Type", "application/json");
|
|
|
+
|
|
|
+ // 构建请求体
|
|
|
+ Map<String, Object> requestBody = new HashMap<>();
|
|
|
+ Map messages = new HashMap();
|
|
|
+ messages.put("role","user");
|
|
|
+ messages.put("content",userInput);
|
|
|
+ requestBody.put("messages", new Object[]{messages});
|
|
|
+ HttpRequest request = HttpUtil.createRequest(Method.POST, apiUrl + "?access_token=" + accessToken)
|
|
|
+ .header("Content-Type", "application/json")
|
|
|
+ .body(JSONObject.toJSONString(requestBody)).timeout(60*1000);
|
|
|
+ ;
|
|
|
+ long l = System.currentTimeMillis();
|
|
|
+ String resposne = request.execute().body();
|
|
|
+ String answer = JSONObject.parseObject(resposne).getString("result");
|
|
|
+ System.out.println(answer);
|
|
|
+ return answer;
|
|
|
+ }
|
|
|
+
|
|
|
+ public static String getChatResponse2(String userInput,String accessToken) {
|
|
|
// 构建请求头
|
|
|
Map<String, String> headers = new HashMap<>();
|
|
|
headers.put("Content-Type", "application/json");
|
|
|
-
|
|
|
+
|
|
|
// 构建请求体
|
|
|
Map<String, Object> requestBody = new HashMap<>();
|
|
|
Map messages = new HashMap();
|
|
|
messages.put("role","user");
|
|
|
messages.put("content",userInput);
|
|
|
requestBody.put("messages", new Object[]{messages});
|
|
|
-
|
|
|
+
|
|
|
// 发送POST请求
|
|
|
Map<String, Object> responseMap = restTemplate.postForObject(
|
|
|
apiUrl + "?access_token=" + accessToken,
|
|
@@ -81,7 +121,7 @@ public class BaidubceUtil {
|
|
|
"输入:急性中毒是否酒精中毒的分期?\n" +
|
|
|
"输出:是";
|
|
|
|
|
|
- System.out.println(new BaidubceUtil().getChatResponse(des,accessToken));
|
|
|
+ System.out.println(BaidubceUtil.getChatResponse(des,accessToken));
|
|
|
}
|
|
|
|
|
|
private static List<Knowlege> getData(String accessToken) {
|