广州市综治平台后端
xusd
2025-06-07 36306491396230522fa20585c2621a7fc899849a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
package cn.huge.module.ai.service;
 
import cn.huge.base.common.exception.ServiceException;
import cn.huge.base.common.utils.GuavaCacheUtils;
import cn.huge.base.common.utils.ObjectUtils;
import cn.huge.base.common.utils.ReturnSucUtils;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
 
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
 
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class AiDifyService {
    
    @Value("${dify.url}")
    private String difyUrl;
    
    @Value("${dify.getMediateStrategyApi}")
    private String getMediateStrategyApi;
    
    @Value("${dify.getMediateCaseDialogApi}")
    private String getChatApi;
 
    @Value("${dify.getPropertyDialogApi}")
    private String getPropertyDialogApi;
    
    @Value("${dify.user}")
    private String user;
    
    /**
     * 发送 http post 请求,参数以原生字符串进行提交,因为ai请求时间过长,在此另外实现一个请求方法
     * @param url 请求地址
     * @param stringJson json字符串数据
     * @param headers 请求头
     * @param encode 编码
     * @return
     * @throws Exception
     */
    public static String httpPostRaw(String url, String stringJson, Map<String, String> headers, String encode) throws Exception{
        if(encode == null){
            encode = "utf-8";
        }
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        //设置请求和传输超时时间,这里将时间设置为五分钟
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(300000).setConnectTimeout(300000).build();
        HttpPost httpost = new HttpPost(url);
        httpost.setConfig(requestConfig);
        //设置header
        httpost.setHeader("Content-type", "application/json");
        if (ObjectUtils.isNotEmpty(headers)) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpost.setHeader(entry.getKey(),entry.getValue());
            }
        }
        //组织请求参数
        StringEntity stringEntity = new StringEntity(stringJson, encode);
        httpost.setEntity(stringEntity);
        String content = null;
        CloseableHttpResponse httpResponse = null;
        try {
            //响应信息
            httpResponse = closeableHttpClient.execute(httpost);
            HttpEntity entity = httpResponse.getEntity();
            content = EntityUtils.toString(entity, encode);
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("网络连接异常,请稍候重试!", e);
        }finally{
            try {
                if (httpResponse != null) {
                    httpResponse.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {  //关闭连接、释放资源
            closeableHttpClient.close();
        } catch (IOException e) {
            e.printStackTrace();
            throw new Exception("网络连接异常,请稍候重试!", e);
        }
        return content;
    }
    
    /**
     * 获取案件调解策略
     * 处理流程:
     * 1. 优先从缓存获取调解策略
     * 2. 如无缓存记录,则请求AI服务生成调解策略
     * 3. 将生成的调解策略保存到缓存
     *
     * @param caseText 案件描述文本
     * @return ReturnSucUtils封装的调解策略结果
     */
    public Object getMediateStrategy(String caseText) {
        String cacheKey = "getMediateStrategy" + caseText.hashCode();
        
        try {
            // 先从缓存获取
            Object cacheAi = GuavaCacheUtils.getCacheAi(cacheKey);
            if (ObjectUtils.isNotEmpty(cacheAi)) {
                return ReturnSucUtils.getRepInfo("请求成功", cacheAi);
            }
 
            // 参数校验
            if (!validateRequest(caseText)) {
                return ReturnSucUtils.getRepInfo("参数错误", null);
            }
 
            // 请求AI服务并处理结果
            JSONObject responseObj = requestAiMediateStrategy(caseText);
            
            if (responseObj != null) {
                try {
                    // 从响应中正确提取调解策略
                    String mediateStrategy = responseObj.getJSONObject("data")
                                                        .getJSONObject("outputs")
                                                        .getString("text");
                    if (mediateStrategy != null) {
                        // 清理调解策略中的指定字符
                        if (mediateStrategy.contains("输出格式") || 
                            mediateStrategy.contains("```json{") || 
                            mediateStrategy.contains("}```") || 
                            mediateStrategy.contains("\"content\":\"")) {
                            
                            mediateStrategy = mediateStrategy.replace("输出格式", "").replace("```json{", "")
                                            .replace("}```", "")
                                            .replace("\"content\":\"", "");
                        }
                        // 将调解策略保存到缓存
                        GuavaCacheUtils.putCacheAi(cacheKey, mediateStrategy);
                        return ReturnSucUtils.getRepInfo("请求成功", mediateStrategy);
                    }
                } catch (Exception e) {
                    log.error("解析AI调解策略响应失败: {}", e.getMessage(), e);
                    log.error("返回的JSON格式: {}", responseObj);
                }
            }
            
            return ReturnSucUtils.getRepInfo("调解策略生成失败", null);
        } catch (Exception e) {
            log.error("获取案件调解策略失败: {}", e.getMessage(), e);
            return ReturnSucUtils.getRepInfo("调解策略生成异常", null);
        }
    }
 
    /**
     * 验证请求参数
     */
    private boolean validateRequest(String caseText) {
        if (caseText == null || caseText.trim().isEmpty()) {
            log.warn("输入参数为空,caseText: {}", caseText);
            return false;
        }
        return true;
    }
 
    /**
     * 请求AI调解策略服务
     * @param caseText 案件描述文本
     * @return AI服务响应结果
     */
    private JSONObject requestAiMediateStrategy(String caseText) {
        try {
            // 构建请求参数
            Map<String, Object> requestBody = new HashMap<>();
            Map<String, Object> inputs = new HashMap<>();
            inputs.put("caseText", caseText);
            requestBody.put("inputs", inputs);
            requestBody.put("response_mode", "blocking");
            requestBody.put("user", user);
 
            // 设置请求头
            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", "Bearer " + getMediateStrategyApi);
 
            // 发送请求到Dify服务
            String response = httpPostRaw(difyUrl + "/workflows/run",
                    JSONObject.toJSONString(requestBody), headers, "utf-8");
            
            return JSONObject.parseObject(response);
        } catch (Exception e) {
            log.error("请求AI调解策略服务失败: {}", e.getMessage(), e);
            return null;
        }
    }
 
    /**
     * 提供流式对话功能
     * 该方法通过WebClient向Dify服务发送流式对话请求,并以流式方式返回AI的回答
     *
     * @param caseText 案件详情文本
     * @param query 用户的提问
     * @param conversationId 对话ID,第一次对话时为空,多轮对话时需要传入
     * @param responseMode 响应模式,可选值为"streaming"或"blocking"
     * @return StreamingResponseBody 流式响应对象
     */
    public StreamingResponseBody streamChat(String caseText, String query, String conversationId, String responseMode) {
        try {
            // 验证responseMode参数
            if (responseMode == null || responseMode.isEmpty()) {
                responseMode = "streaming"; // 默认使用streaming模式
            } else if (!responseMode.equals("streaming") && !responseMode.equals("blocking")) {
                log.warn("不支持的响应模式: {}, 将使用默认的streaming模式", responseMode);
                responseMode = "streaming";
            }
            
            // 构建请求体
            Map<String, Object> requestBody = new HashMap<>();
            Map<String, Object> inputs = new HashMap<>();
            inputs.put("case_text", caseText);
            requestBody.put("inputs", inputs);
            requestBody.put("query", query);
            requestBody.put("response_mode", responseMode);
            requestBody.put("user", user);
            
            // 如果存在对话ID,则添加到请求中
            if (conversationId != null && !conversationId.isEmpty()) {
                requestBody.put("conversation_id", conversationId);
            }
            
            // 创建WebClient,用于发送HTTP请求
            WebClient client = WebClient.builder()
                    .baseUrl(difyUrl + "/chat-messages")
                    .defaultHeader("Content-Type", "application/json")
                    .defaultHeader("Authorization", "Bearer " + getChatApi)
                    .build();
            
            // 返回一个StreamingResponseBody对象,用于处理流式响应
            return outputStream -> client.post()
                    .contentType(MediaType.APPLICATION_JSON)
                    .body(BodyInserters.fromValue(requestBody))
                    .retrieve()
                    .bodyToFlux(DataBuffer.class)
                    .doOnNext(dataBuffer -> {
                        // 将响应数据缓冲区转换为字节数组并写入输出流
                        byte[] bytes = new byte[dataBuffer.readableByteCount()];
                        dataBuffer.read(bytes);
                        try {
                            outputStream.write(bytes);
                            // 刷新输出流以确保数据立即发送
                            outputStream.flush();
                        } catch (IOException e) {
                            log.error("流式写入数据失败: {}", e.getMessage(), e);
                        }
                    })
                    .doOnError(e -> {
                        log.error("流式对话请求失败: {}", e.getMessage(), e);
                    })
                    .blockLast();
        } catch (Exception e) {
            log.error("AI流式对话服务异常: {}", e.getMessage(), e);
            throw new ServiceException("AiDifyService.streamChat", e);
        }
    }
 
    /**
     * 提供阻塞式对话功能,直接返回完整回答
     * 该方法通过HTTP请求向Dify服务发送阻塞式对话请求,并返回完整的AI回答
     *
     * @param caseText 案件详情文本
     * @param query 用户的提问
     * @param conversationId 对话ID,第一次对话时为空,多轮对话时需要传入
     * @return 包含AI回答和对话ID的Map对象
     */
    public Map<String, Object> blockingChat(String caseText, String query, String conversationId) {
        try {
            // 构建请求体
            Map<String, Object> requestBody = new HashMap<>();
            Map<String, Object> inputs = new HashMap<>();
            inputs.put("case_text", caseText);
            requestBody.put("inputs", inputs);
            requestBody.put("query", query);
            requestBody.put("response_mode", "blocking");
            requestBody.put("user", user);
            
            // 如果存在对话ID,则添加到请求中
            if (conversationId != null && !conversationId.isEmpty()) {
                requestBody.put("conversation_id", conversationId);
            }
            
            // 设置请求头
            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", "Bearer " + getChatApi);
            
            // 发送请求到Dify服务
            String response = httpPostRaw(difyUrl + "/chat-messages",
                    JSONObject.toJSONString(requestBody), headers, "utf-8");
            
            // 解析响应
            JSONObject responseObj = JSONObject.parseObject(response);
            
            // 提取关键信息
            Map<String, Object> result = new HashMap<>();
            
            // 提取对话ID
            if (responseObj.containsKey("conversation_id")) {
                result.put("conversationId", responseObj.getString("conversation_id"));
            }
            
            // 提取回答内容
            if (responseObj.containsKey("answer")) {
                result.put("answer", responseObj.getString("answer"));
            } else if (responseObj.containsKey("data") && responseObj.getJSONObject("data").containsKey("answer")) {
                result.put("answer", responseObj.getJSONObject("data").getString("answer"));
            }
            
            return result;
        } catch (Exception e) {
            log.error("AI阻塞式对话服务异常: {}", e.getMessage(), e);
            throw new ServiceException("AiDifyService.blockingChat", e);
        }
    }
 
    /**
     * 提供阻塞式财产对话功能,直接返回完整回答
     * 该方法通过HTTP请求向Dify服务发送阻塞式对话请求,并返回完整的AI回答
     *
     * @param caseText 案件详情文本
     * @param query 用户的提问
     * @param conversationId 对话ID,第一次对话时为空,多轮对话时需要传入
     * @param checkRationality 可选参数,开启AI服务内部的请求合理性检查,默认不传
     * @return 包含AI回答和对话ID的Map对象
     */
    public Map<String, Object> blockingPropertyChat(String query, String conversationId, String checkRationality) {
        try {
            // 构建请求体
            Map<String, Object> requestBody = new HashMap<>();
            Map<String, Object> inputs = new HashMap<>();
            // 如果传入checkRationality且不为空,则添加到请求体
            if (checkRationality != null && !checkRationality.isEmpty()) {
                inputs.put("checkRationality", checkRationality);
            }
            requestBody.put("inputs", inputs);
            requestBody.put("query", query);
            requestBody.put("response_mode", "blocking");
            requestBody.put("user", user);
 
            // 如果存在对话ID,则添加到请求中
            if (conversationId != null && !conversationId.isEmpty()) {
                requestBody.put("conversation_id", conversationId);
            }
 
            // 设置请求头
            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", "Bearer " + getPropertyDialogApi);
 
            // 发送请求到Dify服务
            String response = httpPostRaw(difyUrl + "/chat-messages",
                    JSONObject.toJSONString(requestBody), headers, "utf-8");
 
            // 解析响应
            JSONObject responseObj = JSONObject.parseObject(response);
 
            // 提取关键信息
            Map<String, Object> result = new HashMap<>();
 
            // 提取对话ID
            if (responseObj.containsKey("conversation_id")) {
                result.put("conversationId", responseObj.getString("conversation_id"));
            }
 
            // 提取回答内容
            if (responseObj.containsKey("answer")) {
                result.put("answer", responseObj.getString("answer"));
            } else if (responseObj.containsKey("data") && responseObj.getJSONObject("data").containsKey("answer")) {
                result.put("answer", responseObj.getJSONObject("data").getString("answer"));
            }
 
            return result;
        } catch (Exception e) {
            log.error("AI阻塞式财产对话服务异常: {}", e.getMessage(), e);
            throw new ServiceException("AiDifyService.blockingPropertyChat", e);
        }
    }
}