anderx лет назад: 2
Родитель
Сommit
4dc5113172

+ 83 - 0
src/main/java/com/goafanti/baiduAI/BaiduChatErrorEnums.java

@@ -0,0 +1,83 @@
+package com.goafanti.baiduAI;
+
+import com.goafanti.common.enums.AchievementAuditStatus;
+import org.apache.commons.lang3.StringUtils;
+
+import java.util.HashMap;
+import java.util.Map;
+
+public enum BaiduChatErrorEnums {
+
+    FWQCW(1,"服务器内部错误"),
+    FWQBKY(2,"服务暂不可用"),
+    APINOT(3,"调用的API不存在"),
+    JQCCX(4,"集群超限额。"),
+    WFWQX(6,"无权限访问该用户数据"),
+    TKER(13,"获取token失败。"),
+    IAMNOT(14,"IAM鉴权失败。"),
+    APPNOT(15,"应用不存在或者创建失败。"),
+    MAXER(17,"每天请求量超限额"),
+    QPSER(18,"QPS超限额"),
+    TKCXWX(19,"无效的access_token参数"),
+    TKWX(100,"access_token无效"),
+    TKGQ(110,"access token过期"),
+    FWQNCW(111,"服务内部错误。"),
+    RCER(336000,"入参格式有误"),
+    BODYER(336002,"入参body不是标准的JSON格式。"),
+    PRAMER(336003,"参数校验不合法"),
+    RSGDER(336100,"互动的人过多,请您稍后重新向我提问。"),
+    OTHER(0,"未知错误");
+
+
+    private Integer code;
+    private String msg;
+
+    public Integer getCode() {
+        return code;
+    }
+
+    public void setCode(Integer code) {
+        this.code = code;
+    }
+
+    public String getMsg() {
+        return msg;
+    }
+
+    public void setMsg(String msg) {
+        this.msg = msg;
+    }
+
+    private BaiduChatErrorEnums(Integer code, String msg){
+        this.code=code;
+        this.msg=msg;
+    }
+
+    private static Map<String, BaiduChatErrorEnums> status = new HashMap<String, BaiduChatErrorEnums>();
+
+    static {
+        for (BaiduChatErrorEnums value : BaiduChatErrorEnums.values()) {
+            status.put(value.getMsg(), value);
+        }
+    }
+
+    public static BaiduChatErrorEnums getStatus(String code) {
+        if (containsType(code)) {
+            return status.get(code);
+        }
+        return OTHER;
+    }
+    public static boolean containsType(String code) {
+        return status.containsKey(code);
+    }
+
+    public static String BycodeGetMsg(Integer code){
+        for (BaiduChatErrorEnums value : status.values()) {
+            if (code.equals(value.getCode())){
+                return value.msg;
+            }
+        }
+        return OTHER.msg;
+    }
+
+}

+ 23 - 0
src/main/java/com/goafanti/baiduAI/bo/OutChatER.java

@@ -0,0 +1,23 @@
+package com.goafanti.baiduAI.bo;
+
+public class OutChatER extends OutSendChat{
+    private Integer errorCode;
+    private String errorMsg;
+
+
+    public Integer getErrorCode() {
+        return errorCode;
+    }
+
+    public void setErrorCode(Integer errorCode) {
+        this.errorCode = errorCode;
+    }
+
+    public String getErrorMsg() {
+        return errorMsg;
+    }
+
+    public void setErrorMsg(String errorMsg) {
+        this.errorMsg = errorMsg;
+    }
+}

+ 44 - 0
src/main/java/com/goafanti/baiduAI/bo/OutSendChatOK.java

@@ -0,0 +1,44 @@
+package com.goafanti.baiduAI.bo;
+
+public class OutSendChatOK extends  OutSendChat {
+    private String id;
+    private String object;
+    private String created;
+    private String sentence_id;
+    private String is_end;
+    private String result;
+    private String need_clear_history;
+    private Usage usage;
+
+
+
+    private class Usage {
+        private Integer prompt_tokens;
+        private Integer completion_tokens;
+        private Integer total_tokens;
+
+        public Integer getPrompt_tokens() {
+            return prompt_tokens;
+        }
+
+        public void setPrompt_tokens(Integer prompt_tokens) {
+            this.prompt_tokens = prompt_tokens;
+        }
+
+        public Integer getCompletion_tokens() {
+            return completion_tokens;
+        }
+
+        public void setCompletion_tokens(Integer completion_tokens) {
+            this.completion_tokens = completion_tokens;
+        }
+
+        public Integer getTotal_tokens() {
+            return total_tokens;
+        }
+
+        public void setTotal_tokens(Integer total_tokens) {
+            this.total_tokens = total_tokens;
+        }
+    }
+}

+ 1 - 3
src/main/java/com/goafanti/baiduAI/controller/BaiduAiController.java

@@ -24,9 +24,7 @@ public class BaiduAiController {
     @RequestMapping(value = "/send",method = RequestMethod.POST)
     @RequestMapping(value = "/send",method = RequestMethod.POST)
     public Result sendChat(@RequestBody InputSendChat in){
     public Result sendChat(@RequestBody InputSendChat in){
         Result res =new Result();
         Result res =new Result();
-        String content = baiduAiService.sendChat(in);
-        OutSendChat outSendChat = JSON.parseObject(content, OutSendChat.class);
-        return res.data(outSendChat);
+        return res.data(baiduAiService.sendChat(in));
     }
     }
 
 
 
 

+ 2 - 1
src/main/java/com/goafanti/baiduAI/service/BaiduAiService.java

@@ -1,9 +1,10 @@
 package com.goafanti.baiduAI.service;
 package com.goafanti.baiduAI.service;
 
 
 import com.goafanti.baiduAI.bo.InputSendChat;
 import com.goafanti.baiduAI.bo.InputSendChat;
+import com.goafanti.baiduAI.bo.OutSendChat;
 
 
 public interface BaiduAiService {
 public interface BaiduAiService {
 
 
 
 
-    String sendChat(InputSendChat in);
+    OutSendChat sendChat(InputSendChat in);
 }
 }

+ 52 - 6
src/main/java/com/goafanti/baiduAI/service/impl/BaiduAiServiceImpl.java

@@ -1,8 +1,11 @@
 package com.goafanti.baiduAI.service.impl;
 package com.goafanti.baiduAI.service.impl;
 
 
-import com.goafanti.baiduAI.bo.InputSendChat;
+import com.alibaba.fastjson.JSON;
+import com.goafanti.baiduAI.BaiduChatErrorEnums;
+import com.goafanti.baiduAI.bo.*;
 import com.goafanti.baiduAI.service.BaiduAiService;
 import com.goafanti.baiduAI.service.BaiduAiService;
 import com.goafanti.common.error.BusinessException;
 import com.goafanti.common.error.BusinessException;
+import com.goafanti.common.utils.BaiduChatUtils;
 import com.goafanti.common.utils.HttpUtils;
 import com.goafanti.common.utils.HttpUtils;
 import com.goafanti.common.utils.LoggerUtils;
 import com.goafanti.common.utils.LoggerUtils;
 import com.goafanti.common.utils.RedisUtil;
 import com.goafanti.common.utils.RedisUtil;
@@ -13,6 +16,8 @@ import org.springframework.stereotype.Service;
 import javax.annotation.Resource;
 import javax.annotation.Resource;
 import java.io.IOException;
 import java.io.IOException;
 import java.util.Calendar;
 import java.util.Calendar;
+import java.util.HashMap;
+import java.util.Map;
 
 
 @Service
 @Service
 public class BaiduAiServiceImpl implements BaiduAiService {
 public class BaiduAiServiceImpl implements BaiduAiService {
@@ -22,20 +27,61 @@ public class BaiduAiServiceImpl implements BaiduAiService {
 
 
 
 
     @Autowired
     @Autowired
-    private HttpUtils httpUtils;
+    private BaiduChatUtils baiduChatUtils;
 
 
 
 
     @Override
     @Override
-    public String sendChat(InputSendChat in) {
+    public OutSendChat sendChat(InputSendChat in) {
 
 
             String result = null;
             String result = null;
         try {
         try {
-            result=httpUtils.sendBaiduAI(in);
+
+            result= baiduChatUtils.sendBaiduAI(in);
         } catch (IOException e) {
         } catch (IOException e) {
             e.printStackTrace();
             e.printStackTrace();
-            throw new BusinessException("文言一心调用失败");
+            throw new BusinessException("文言一心调用失败"+e.getLocalizedMessage());
+        }
+        if (in.isStream()){
+            Map<String ,Object> resultMap=JSON.parseObject(result, Map.class);
+            for (String key : SseMap.sseEmitterMap.keySet()) {
+                try {
+                    SseResult sseResult=SseMap.sseEmitterMap.get(key);
+                    Map map=new HashMap();
+//                    map.put("result",resultMap.get("result"));
+//                    String s = JSON.toJSONString(map);
+//                    sseResult.sseEmitter.send(s);
+                    sseResult.sseEmitter.send(result);
+                } catch (IOException e) {
+                    SseMap.sseEmitterMap.remove(key);
+                }
+            }
+            return new OutSendChatOK();
+        }else {
+            OutSendChat outSendChat = pushResultToOutSendChat(result);
+            return outSendChat;
+        }
+
+    }
+
+    private OutSendChat pushResultToOutSendChat(String result) {
+
+        Map<String ,Object> resultMap=JSON.parseObject(result, Map.class);
+        Integer errorCode= (Integer) resultMap.get("error_code");
+        if (errorCode!=null){
+            OutChatER res=new OutChatER();
+            res.setErrorCode(errorCode);
+            if (errorCode.equals("336003")){
+                res.setErrorMsg(BaiduChatErrorEnums.BycodeGetMsg(errorCode)+resultMap.get("error_msg"));
+            }else {
+            res.setErrorMsg(BaiduChatErrorEnums.BycodeGetMsg(errorCode));
+            }
+            return res;
+        }else {
+            OutSendChatOK res=new OutSendChatOK();
+            res=JSON.parseObject(result,OutSendChatOK.class);
+            return res;
         }
         }
-        return result;
+
     }
     }
 
 
 
 

+ 122 - 0
src/main/java/com/goafanti/common/utils/BaiduChatUtils.java

@@ -0,0 +1,122 @@
+package com.goafanti.common.utils;
+
+import com.alibaba.fastjson.JSON;
+import com.goafanti.baiduAI.bo.InputSendChat;
+import com.goafanti.common.error.BusinessException;
+import okhttp3.*;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Component;
+import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
+
+import java.io.IOException;
+import java.util.Calendar;
+import java.util.HashMap;
+import java.util.concurrent.TimeUnit;
+
+
+public class BaiduChatUtils {
+
+    @Value(value = "${baidu.ApiKey}")
+    private   String baiduApiKey=null;
+
+    @Value(value = "${baidu.SecretKey}")
+    private   String baiduSecretKey=null;
+    @Autowired
+    private RedisUtil redisUtil;
+
+    /*文心一言地址*/
+    private static final String BAIDU_CHAT_WXYY_URL="https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token=";
+    /*Ernie-Lite地址*/
+    private static final String BAIDU_CHAT_ERNIE_LITE_URL="https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/eb-instant?access_token=";
+    /*accessToken获取地址*/
+    private static final String BAIDU_ACCESSTOKEN_URL="https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&";
+
+
+    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().connectTimeout(120000, TimeUnit.MILLISECONDS)
+            .readTimeout(120000, TimeUnit.MILLISECONDS)
+            .build();
+
+
+
+    public  String  getBaiduAccessToken() throws IOException {
+        MediaType mediaType = MediaType.parse("application/json");
+        RequestBody body = RequestBody.create(mediaType, "");
+        StringBuffer url= new StringBuffer(BAIDU_ACCESSTOKEN_URL)
+                .append("client_id=").append(baiduApiKey).append("&client_secret=").append(baiduSecretKey);
+        Request request = new Request.Builder()
+                .url(url.toString())
+                .method("POST", body)
+                .addHeader("Content-Type", "application/json")
+                .addHeader("Accept", "application/json")
+                .build();
+        Response response = HTTP_CLIENT.newCall(request).execute();
+        String result=response.body().string();
+        HashMap<String,Object> map = JSON.parseObject(result, HashMap.class);
+        String  accessToken = map.get("access_token").toString();
+        LoggerUtils.debug(getClass(),"获取accessToken="+accessToken);
+        return accessToken;
+    }
+
+    public  String sendBaiduAI(InputSendChat in) throws IOException{
+        String accessToken = getRedisBaiduAccessToken();
+        MediaType mediaType = MediaType.parse("application/json");
+        RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(in));
+        Request request = new Request.Builder()
+                .url(BAIDU_CHAT_WXYY_URL + accessToken)
+                .method("POST", body)
+                .addHeader("Content-Type", "application/json")
+                .build();
+        Response response = HTTP_CLIENT.newCall(request).execute();
+        String result=response.body().string();
+        SseEmitter sseEmitter=new SseEmitter(0l);
+
+
+        return result;
+    }
+
+
+
+
+
+    private String  getRedisBaiduAccessToken() {
+        String redisAccessToken=null;
+        String redisTime=redisUtil.getString("baiduAccessTime");
+        //没有
+        if (redisTime !=null){
+            Calendar cal = Calendar.getInstance();
+            Long redisAccessTime=Long.valueOf(redisTime);
+            if (cal.getTimeInMillis()>redisAccessTime){
+                redisUtil.deleteString("baiduAccessToken");
+                redisUtil.deleteString("baiduAccessTime");
+                redisAccessToken=pushRedisBaiduAccessToken();
+                LoggerUtils.debug(getClass(),"accessToken过期,重新获取");
+            }else {
+                redisAccessToken=  redisUtil.getString("baiduAccessToken");
+                LoggerUtils.debug(getClass(),"accessToken从redis获取");
+            }
+        }else {
+            redisAccessToken=pushRedisBaiduAccessToken();
+            LoggerUtils.debug(getClass(),"accessToken不存在,从百度获取");
+        }
+        return redisAccessToken;
+    }
+
+    private String pushRedisBaiduAccessToken() {
+        String baiduAccessToken;
+        try {
+            baiduAccessToken = getBaiduAccessToken();
+        } catch (IOException e) {
+            throw new BusinessException("baiduAccessToken获取失败");
+        }
+        //获取当前系统时间
+        Calendar cal = Calendar.getInstance();
+        //将时间增加三十天
+        cal.add(Calendar.DATE, 30);
+        //获取改变后的时间
+        Long baiduAccessTime= cal.getTimeInMillis();
+        redisUtil.setString("baiduAccessToken",baiduAccessToken);
+        redisUtil.setString("baiduAccessTime",baiduAccessTime.toString());
+        return baiduAccessToken;
+    }
+}

+ 0 - 91
src/main/java/com/goafanti/common/utils/HttpUtils.java

@@ -32,19 +32,8 @@ import java.util.concurrent.TimeUnit;
 @Component
 @Component
 public class HttpUtils {
 public class HttpUtils {
 
 
-	@Autowired
-	private RedisUtil redisUtil;
 
 
-	@Value(value = "${baidu.ApiKey}")
-	private   String baiduApiKey=null;
 
 
-	@Value(value = "${baidu.SecretKey}")
-	private   String baiduSecretKey=null;
-
-
-	static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().connectTimeout(120000, TimeUnit.MILLISECONDS)
-			.readTimeout(120000, TimeUnit.MILLISECONDS)
-			.build();
 
 
 
 
 	 public static JSONObject httpGet(String url) {
 	 public static JSONObject httpGet(String url) {
@@ -146,86 +135,6 @@ public class HttpUtils {
 
 
 
 
 
 
-	public  String  getBaiduAccessToken() throws IOException {
-				MediaType mediaType = MediaType.parse("application/json");
-				RequestBody body = RequestBody.create(mediaType, "");
-				StringBuffer url= new StringBuffer("https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&")
-					.append("client_id=").append(baiduApiKey).append("&client_secret=").append(baiduSecretKey);
-				Request request = new Request.Builder()
-						.url(url.toString())
-						.method("POST", body)
-						.addHeader("Content-Type", "application/json")
-						.addHeader("Accept", "application/json")
-						.build();
-				Response response = HTTP_CLIENT.newCall(request).execute();
-				String result=response.body().string();
-		HashMap<String,Object> map = JSON.parseObject(result, HashMap.class);
-		String  accessToken = map.get("access_token").toString();
-		LoggerUtils.debug(getClass(),"获取accessToken="+accessToken);
-		return accessToken;
-	}
-
-	public  String sendBaiduAI(InputSendChat in) throws IOException{
-		String accessToken = getRedisBaiduAccessToken();
-		MediaType mediaType = MediaType.parse("application/json");
-		RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(in));
-		Request request = new Request.Builder()
-				.url("https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token=" + accessToken)
-				.method("POST", body)
-				.addHeader("Content-Type", "application/json")
-				.build();
-		Response response = HTTP_CLIENT.newCall(request).execute();
-		String result=response.body().string();
-		SseEmitter sseEmitter=new SseEmitter(0l);
-		SseStreamListener listener=new SseStreamListener(sseEmitter);
-
-
-		return result;
-	}
-
-
-
-
 
 
-	private String  getRedisBaiduAccessToken() {
-		String redisAccessToken=null;
-		String redisTime=redisUtil.getString("baiduAccessTime");
-		//没有
-		if (redisTime !=null){
-			Calendar cal = Calendar.getInstance();
-			Long redisAccessTime=Long.valueOf(redisTime);
-			if (cal.getTimeInMillis()>redisAccessTime){
-				redisUtil.deleteString("baiduAccessToken");
-				redisUtil.deleteString("baiduAccessTime");
-				redisAccessToken=pushRedisBaiduAccessToken();
-				LoggerUtils.debug(getClass(),"accessToken过期,重新获取");
-			}else {
-				redisAccessToken=  redisUtil.getString("baiduAccessToken");
-				LoggerUtils.debug(getClass(),"accessToken从redis获取");
-			}
-		}else {
-			redisAccessToken=pushRedisBaiduAccessToken();
-			LoggerUtils.debug(getClass(),"accessToken不存在,从百度获取");
-		}
-		return redisAccessToken;
-	}
-
-	private String pushRedisBaiduAccessToken() {
-		String baiduAccessToken;
-		try {
-			baiduAccessToken = getBaiduAccessToken();
-		} catch (IOException e) {
-			throw new BusinessException("baiduAccessToken获取失败");
-		}
-		//获取当前系统时间
-		Calendar cal = Calendar.getInstance();
-		//将时间增加三十天
-		cal.add(Calendar.DATE, 30);
-		//获取改变后的时间
-		Long baiduAccessTime= cal.getTimeInMillis();
-        redisUtil.setString("baiduAccessToken",baiduAccessToken);
-        redisUtil.setString("baiduAccessTime",baiduAccessTime.toString());
-		return baiduAccessToken;
-	}
 
 
 }
 }

+ 1 - 0
src/main/resources/spring/spring-shiro.xml

@@ -65,6 +65,7 @@
         <property name="listener" ref="jedisQueueListener"></property>
         <property name="listener" ref="jedisQueueListener"></property>
     </bean>
     </bean>
 	<bean id="HttpUtils" class="com.goafanti.common.utils.HttpUtils"/>
 	<bean id="HttpUtils" class="com.goafanti.common.utils.HttpUtils"/>
+	<bean id="BaiduChatUtils" class="com.goafanti.common.utils.BaiduChatUtils"/>
     <bean id="easemobUtils" class="com.goafanti.easemob.EasemobUtils"/>
     <bean id="easemobUtils" class="com.goafanti.easemob.EasemobUtils"/>