对话、重新生成、评价完成
This commit is contained in:
@@ -4,8 +4,9 @@ import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import okhttp3.*;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.xyzh.ai.client.dto.*;
|
||||
@@ -26,10 +27,11 @@ import java.util.concurrent.TimeUnit;
|
||||
* @copyright xyzh
|
||||
* @since 2025-11-04
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class DifyApiClient {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(DifyApiClient.class);
|
||||
|
||||
@Autowired
|
||||
private DifyConfig difyConfig;
|
||||
|
||||
@@ -55,7 +57,7 @@ public class DifyApiClient {
|
||||
.retryOnConnectionFailure(false) // 流式不重试
|
||||
.build();
|
||||
|
||||
log.info("DifyApiClient初始化完成,API地址: {}", difyConfig.getApiBaseUrl());
|
||||
logger.info("DifyApiClient初始化完成,API地址: {}", difyConfig.getApiBaseUrl());
|
||||
}
|
||||
|
||||
// ===================== 知识库管理 API =====================
|
||||
@@ -79,14 +81,14 @@ public class DifyApiClient {
|
||||
String responseBody = response.body() != null ? response.body().string() : "";
|
||||
|
||||
if (!response.isSuccessful()) {
|
||||
log.error("创建知识库失败: {} - {}", response.code(), responseBody);
|
||||
logger.error("创建知识库失败: {} - {}", response.code(), responseBody);
|
||||
throw new DifyException("创建知识库失败: " + responseBody);
|
||||
}
|
||||
|
||||
return objectMapper.readValue(responseBody, DatasetCreateResponse.class);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.error("创建知识库异常", e);
|
||||
logger.error("创建知识库异常", e);
|
||||
throw new DifyException("创建知识库异常: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
@@ -108,14 +110,14 @@ public class DifyApiClient {
|
||||
String responseBody = response.body() != null ? response.body().string() : "";
|
||||
|
||||
if (!response.isSuccessful()) {
|
||||
log.error("查询知识库列表失败: {} - {}", response.code(), responseBody);
|
||||
logger.error("查询知识库列表失败: {} - {}", response.code(), responseBody);
|
||||
throw new DifyException("查询知识库列表失败: " + responseBody);
|
||||
}
|
||||
|
||||
return objectMapper.readValue(responseBody, DatasetListResponse.class);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.error("查询知识库列表异常", e);
|
||||
logger.error("查询知识库列表异常", e);
|
||||
throw new DifyException("查询知识库列表异常: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
@@ -137,14 +139,14 @@ public class DifyApiClient {
|
||||
String responseBody = response.body() != null ? response.body().string() : "";
|
||||
|
||||
if (!response.isSuccessful()) {
|
||||
log.error("查询知识库详情失败: {} - {}", response.code(), responseBody);
|
||||
logger.error("查询知识库详情失败: {} - {}", response.code(), responseBody);
|
||||
throw new DifyException("查询知识库详情失败: " + responseBody);
|
||||
}
|
||||
|
||||
return objectMapper.readValue(responseBody, DatasetDetailResponse.class);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.error("查询知识库详情异常", e);
|
||||
logger.error("查询知识库详情异常", e);
|
||||
throw new DifyException("查询知识库详情异常: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
@@ -168,13 +170,13 @@ public class DifyApiClient {
|
||||
try (Response response = httpClient.newCall(httpRequest).execute()) {
|
||||
if (!response.isSuccessful()) {
|
||||
String responseBody = response.body() != null ? response.body().string() : "";
|
||||
log.error("更新知识库失败: {} - {}", response.code(), responseBody);
|
||||
logger.error("更新知识库失败: {} - {}", response.code(), responseBody);
|
||||
throw new DifyException("更新知识库失败: " + responseBody);
|
||||
}
|
||||
log.info("知识库更新成功: {}", datasetId);
|
||||
logger.info("知识库更新成功: {}", datasetId);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.error("更新知识库异常", e);
|
||||
logger.error("更新知识库异常", e);
|
||||
throw new DifyException("更新知识库异常: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
@@ -194,13 +196,13 @@ public class DifyApiClient {
|
||||
try (Response response = httpClient.newCall(httpRequest).execute()) {
|
||||
if (!response.isSuccessful()) {
|
||||
String responseBody = response.body() != null ? response.body().string() : "";
|
||||
log.error("删除知识库失败: {} - {}", response.code(), responseBody);
|
||||
logger.error("删除知识库失败: {} - {}", response.code(), responseBody);
|
||||
throw new DifyException("删除知识库失败: " + responseBody);
|
||||
}
|
||||
log.info("知识库删除成功: {}", datasetId);
|
||||
logger.info("知识库删除成功: {}", datasetId);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.error("删除知识库异常", e);
|
||||
logger.error("删除知识库异常", e);
|
||||
throw new DifyException("删除知识库异常: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
@@ -246,14 +248,14 @@ public class DifyApiClient {
|
||||
String responseBody = response.body() != null ? response.body().string() : "";
|
||||
|
||||
if (!response.isSuccessful()) {
|
||||
log.error("上传文档失败: {} - {}", response.code(), responseBody);
|
||||
logger.error("上传文档失败: {} - {}", response.code(), responseBody);
|
||||
throw new DifyException("上传文档失败: " + responseBody);
|
||||
}
|
||||
|
||||
return objectMapper.readValue(responseBody, DocumentUploadResponse.class);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.error("上传文档异常", e);
|
||||
logger.error("上传文档异常", e);
|
||||
throw new DifyException("上传文档异常: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
@@ -275,14 +277,14 @@ public class DifyApiClient {
|
||||
String responseBody = response.body() != null ? response.body().string() : "";
|
||||
|
||||
if (!response.isSuccessful()) {
|
||||
log.error("查询文档状态失败: {} - {}", response.code(), responseBody);
|
||||
logger.error("查询文档状态失败: {} - {}", response.code(), responseBody);
|
||||
throw new DifyException("查询文档状态失败: " + responseBody);
|
||||
}
|
||||
|
||||
return objectMapper.readValue(responseBody, DocumentStatusResponse.class);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.error("查询文档状态异常", e);
|
||||
logger.error("查询文档状态异常", e);
|
||||
throw new DifyException("查询文档状态异常: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
@@ -304,14 +306,14 @@ public class DifyApiClient {
|
||||
String responseBody = response.body() != null ? response.body().string() : "";
|
||||
|
||||
if (!response.isSuccessful()) {
|
||||
log.error("查询文档列表失败: {} - {}", response.code(), responseBody);
|
||||
logger.error("查询文档列表失败: {} - {}", response.code(), responseBody);
|
||||
throw new DifyException("查询文档列表失败: " + responseBody);
|
||||
}
|
||||
|
||||
return objectMapper.readValue(responseBody, DocumentListResponse.class);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.error("查询文档列表异常", e);
|
||||
logger.error("查询文档列表异常", e);
|
||||
throw new DifyException("查询文档列表异常: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
@@ -332,13 +334,13 @@ public class DifyApiClient {
|
||||
try (Response response = httpClient.newCall(httpRequest).execute()) {
|
||||
if (!response.isSuccessful()) {
|
||||
String responseBody = response.body() != null ? response.body().string() : "";
|
||||
log.error("删除文档失败: {} - {}", response.code(), responseBody);
|
||||
logger.error("删除文档失败: {} - {}", response.code(), responseBody);
|
||||
throw new DifyException("删除文档失败: " + responseBody);
|
||||
}
|
||||
log.info("文档删除成功: {}", documentId);
|
||||
logger.info("文档删除成功: {}", documentId);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.error("删除文档异常", e);
|
||||
logger.error("删除文档异常", e);
|
||||
throw new DifyException("删除文档异常: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
@@ -364,14 +366,14 @@ public class DifyApiClient {
|
||||
String responseBody = response.body() != null ? response.body().string() : "";
|
||||
|
||||
if (!response.isSuccessful()) {
|
||||
log.error("知识库检索失败: {} - {}", response.code(), responseBody);
|
||||
logger.error("知识库检索失败: {} - {}", response.code(), responseBody);
|
||||
throw new DifyException("知识库检索失败: " + responseBody);
|
||||
}
|
||||
|
||||
return objectMapper.readValue(responseBody, RetrievalResponse.class);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.error("知识库检索异常", e);
|
||||
logger.error("知识库检索异常", e);
|
||||
throw new DifyException("知识库检索异常: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
@@ -423,6 +425,9 @@ public class DifyApiClient {
|
||||
JsonNode jsonNode = objectMapper.readTree(data);
|
||||
String event = jsonNode.has("event") ? jsonNode.get("event").asText() : "";
|
||||
|
||||
// 转发所有事件到回调(包含完整数据)
|
||||
callback.onEvent(event, data);
|
||||
|
||||
switch (event) {
|
||||
case "message":
|
||||
case "agent_message":
|
||||
@@ -441,25 +446,27 @@ public class DifyApiClient {
|
||||
jsonNode.get("message").asText() : "未知错误";
|
||||
callback.onError(new DifyException(errorMsg));
|
||||
return;
|
||||
// 其他事件(workflow_started、node_started、node_finished等)
|
||||
// 已通过onEvent转发,这里不需要额外处理
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("流式响应处理异常", e);
|
||||
logger.error("流式响应处理异常", e);
|
||||
callback.onError(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFailure(Call call, IOException e) {
|
||||
log.error("流式对话请求失败", e);
|
||||
logger.error("流式对话请求失败", e);
|
||||
callback.onError(e);
|
||||
}
|
||||
});
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("流式对话异常", e);
|
||||
logger.error("流式对话异常", e);
|
||||
callback.onError(e);
|
||||
}
|
||||
}
|
||||
@@ -486,14 +493,14 @@ public class DifyApiClient {
|
||||
String responseBody = response.body() != null ? response.body().string() : "";
|
||||
|
||||
if (!response.isSuccessful()) {
|
||||
log.error("阻塞式对话失败: {} - {}", response.code(), responseBody);
|
||||
logger.error("阻塞式对话失败: {} - {}", response.code(), responseBody);
|
||||
throw new DifyException("阻塞式对话失败: " + responseBody);
|
||||
}
|
||||
|
||||
return objectMapper.readValue(responseBody, ChatResponse.class);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.error("阻塞式对话异常", e);
|
||||
logger.error("阻塞式对话异常", e);
|
||||
throw new DifyException("阻塞式对话异常: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
@@ -516,17 +523,57 @@ public class DifyApiClient {
|
||||
try (Response response = httpClient.newCall(httpRequest).execute()) {
|
||||
if (!response.isSuccessful()) {
|
||||
String responseBody = response.body() != null ? response.body().string() : "";
|
||||
log.error("停止对话失败: {} - {}", response.code(), responseBody);
|
||||
logger.error("停止对话失败: {} - {}", response.code(), responseBody);
|
||||
throw new DifyException("停止对话失败: " + responseBody);
|
||||
}
|
||||
log.info("对话停止成功: {}", taskId);
|
||||
logger.info("对话停止成功: {}", taskId);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.error("停止对话异常", e);
|
||||
logger.error("停止对话异常", e);
|
||||
throw new DifyException("停止对话异常: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交消息反馈
|
||||
* @param messageId Dify消息ID
|
||||
* @param rating 评分(like/dislike/null)
|
||||
* @param userId 用户ID
|
||||
* @param apiKey API密钥
|
||||
*/
|
||||
public void submitMessageFeedback(String messageId, String rating, String userId, String feedback, String apiKey) {
|
||||
String url = difyConfig.getFullApiUrl("/messages/" + messageId + "/feedbacks");
|
||||
|
||||
try {
|
||||
FeedbackRequest feedbackRequest = new FeedbackRequest(rating, userId, feedback);
|
||||
String jsonBody = objectMapper.writeValueAsString(feedbackRequest);
|
||||
|
||||
Request httpRequest = new Request.Builder()
|
||||
.url(url)
|
||||
.header("Authorization", "Bearer " + getApiKey(apiKey))
|
||||
.header("Content-Type", "application/json")
|
||||
.post(RequestBody.create(jsonBody, MediaType.parse("application/json")))
|
||||
.build();
|
||||
|
||||
try (Response response = httpClient.newCall(httpRequest).execute()) {
|
||||
String responseBody = response.body() != null ? response.body().string() : "";
|
||||
|
||||
if (!response.isSuccessful()) {
|
||||
logger.error("提交消息反馈失败: {} - {}", response.code(), responseBody);
|
||||
throw new DifyException("提交消息反馈失败: " + responseBody);
|
||||
}
|
||||
if (responseBody!="success") {
|
||||
logger.error("提交消息反馈失败: {} - {}", response.code(), responseBody);
|
||||
throw new DifyException("提交消息反馈失败: " + responseBody);
|
||||
}
|
||||
logger.info("消息反馈提交成功: {} - {}", messageId, rating);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
logger.error("提交消息反馈异常", e);
|
||||
throw new DifyException("提交消息反馈异常: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
// ===================== 对话历史 API =====================
|
||||
|
||||
/**
|
||||
@@ -563,14 +610,14 @@ public class DifyApiClient {
|
||||
String responseBody = response.body() != null ? response.body().string() : "";
|
||||
|
||||
if (!response.isSuccessful()) {
|
||||
log.error("获取对话历史失败: {} - {}", response.code(), responseBody);
|
||||
logger.error("获取对话历史失败: {} - {}", response.code(), responseBody);
|
||||
throw new DifyException("获取对话历史失败: " + responseBody);
|
||||
}
|
||||
|
||||
return objectMapper.readValue(responseBody, MessageHistoryResponse.class);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.error("获取对话历史异常", e);
|
||||
logger.error("获取对话历史异常", e);
|
||||
throw new DifyException("获取对话历史异常: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
@@ -605,14 +652,14 @@ public class DifyApiClient {
|
||||
String responseBody = response.body() != null ? response.body().string() : "";
|
||||
|
||||
if (!response.isSuccessful()) {
|
||||
log.error("获取对话列表失败: {} - {}", response.code(), responseBody);
|
||||
logger.error("获取对话列表失败: {} - {}", response.code(), responseBody);
|
||||
throw new DifyException("获取对话列表失败: " + responseBody);
|
||||
}
|
||||
|
||||
return objectMapper.readValue(responseBody, ConversationListResponse.class);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.error("获取对话列表异常", e);
|
||||
logger.error("获取对话列表异常", e);
|
||||
throw new DifyException("获取对话列表异常: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
@@ -639,14 +686,14 @@ public class DifyApiClient {
|
||||
String responseBody = response.body() != null ? response.body().string() : "";
|
||||
|
||||
if (!response.isSuccessful()) {
|
||||
log.error("GET请求失败: {} - {} - {}", url, response.code(), responseBody);
|
||||
logger.error("GET请求失败: {} - {} - {}", url, response.code(), responseBody);
|
||||
throw new DifyException("GET请求失败[" + response.code() + "]: " + responseBody);
|
||||
}
|
||||
|
||||
return responseBody;
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.error("GET请求异常: {}", url, e);
|
||||
logger.error("GET请求异常: {}", url, e);
|
||||
throw new DifyException("GET请求异常: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
@@ -676,14 +723,14 @@ public class DifyApiClient {
|
||||
String responseBody = response.body() != null ? response.body().string() : "";
|
||||
|
||||
if (!response.isSuccessful()) {
|
||||
log.error("POST请求失败: {} - {} - {}", url, response.code(), responseBody);
|
||||
logger.error("POST请求失败: {} - {} - {}", url, response.code(), responseBody);
|
||||
throw new DifyException("POST请求失败[" + response.code() + "]: " + responseBody);
|
||||
}
|
||||
|
||||
return responseBody;
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.error("POST请求异常: {}", url, e);
|
||||
logger.error("POST请求异常: {}", url, e);
|
||||
throw new DifyException("POST请求异常: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
@@ -713,14 +760,14 @@ public class DifyApiClient {
|
||||
String responseBody = response.body() != null ? response.body().string() : "";
|
||||
|
||||
if (!response.isSuccessful()) {
|
||||
log.error("PATCH请求失败: {} - {} - {}", url, response.code(), responseBody);
|
||||
logger.error("PATCH请求失败: {} - {} - {}", url, response.code(), responseBody);
|
||||
throw new DifyException("PATCH请求失败[" + response.code() + "]: " + responseBody);
|
||||
}
|
||||
|
||||
return responseBody;
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.error("PATCH请求异常: {}", url, e);
|
||||
logger.error("PATCH请求异常: {}", url, e);
|
||||
throw new DifyException("PATCH请求异常: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
@@ -745,14 +792,14 @@ public class DifyApiClient {
|
||||
String responseBody = response.body() != null ? response.body().string() : "";
|
||||
|
||||
if (!response.isSuccessful()) {
|
||||
log.error("DELETE请求失败: {} - {} - {}", url, response.code(), responseBody);
|
||||
logger.error("DELETE请求失败: {} - {} - {}", url, response.code(), responseBody);
|
||||
throw new DifyException("DELETE请求失败[" + response.code() + "]: " + responseBody);
|
||||
}
|
||||
|
||||
return responseBody;
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.error("DELETE请求异常: {}", url, e);
|
||||
logger.error("DELETE请求异常: {}", url, e);
|
||||
throw new DifyException("DELETE请求异常: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
@@ -790,5 +837,45 @@ public class DifyApiClient {
|
||||
this.user = user;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 反馈请求的内部类
|
||||
*/
|
||||
private static class FeedbackRequest {
|
||||
private String rating;
|
||||
private String user;
|
||||
|
||||
private String feedback;
|
||||
|
||||
public FeedbackRequest(String rating, String user, String feedback) {
|
||||
this.rating = rating;
|
||||
this.user = user;
|
||||
this.feedback = feedback;
|
||||
}
|
||||
|
||||
public String getRating() {
|
||||
return rating;
|
||||
}
|
||||
|
||||
public void setRating(String rating) {
|
||||
this.rating = rating;
|
||||
}
|
||||
|
||||
public String getUser() {
|
||||
return user;
|
||||
}
|
||||
|
||||
public void setUser(String user) {
|
||||
this.user = user;
|
||||
}
|
||||
|
||||
public String getFeedback() {
|
||||
return feedback;
|
||||
}
|
||||
|
||||
public void setFeedback(String feedback) {
|
||||
this.feedback = feedback;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -20,6 +20,15 @@ public interface StreamCallback {
|
||||
* @param metadata JSON格式的元数据
|
||||
*/
|
||||
void onMessageEnd(String metadata);
|
||||
|
||||
/**
|
||||
* 接收到Dify原始事件(用于转发完整事件数据)
|
||||
* @param eventType 事件类型(如workflow_started、node_started等)
|
||||
* @param eventData 完整的事件JSON数据
|
||||
*/
|
||||
default void onEvent(String eventType, String eventData) {
|
||||
// 默认实现:不处理
|
||||
}
|
||||
|
||||
/**
|
||||
* 流式响应完成
|
||||
|
||||
@@ -11,6 +11,7 @@ import org.xyzh.common.core.page.PageRequest;
|
||||
import org.xyzh.common.dto.ai.TbAiAgentConfig;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @description AI智能体配置控制器
|
||||
@@ -61,7 +62,7 @@ public class AiAgentConfigController {
|
||||
* @since 2025-11-04
|
||||
*/
|
||||
@DeleteMapping("/{id}")
|
||||
public ResultDomain<Boolean> deleteAgent(@PathVariable String id) {
|
||||
public ResultDomain<Boolean> deleteAgent(@PathVariable(name = "id") String id) {
|
||||
log.info("删除智能体: id={}", id);
|
||||
return agentConfigService.deleteAgent(id);
|
||||
}
|
||||
@@ -74,19 +75,19 @@ public class AiAgentConfigController {
|
||||
* @since 2025-11-04
|
||||
*/
|
||||
@GetMapping("/{id}")
|
||||
public ResultDomain<TbAiAgentConfig> getAgent(@PathVariable String id) {
|
||||
public ResultDomain<TbAiAgentConfig> getAgent(@PathVariable(name = "id") String id) {
|
||||
log.info("获取智能体: id={}", id);
|
||||
return agentConfigService.getAgentById(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 获取启用的智能体列表
|
||||
* @return ResultDomain<List<TbAiAgentConfig>>
|
||||
* @return ResultDomain<TbAiAgentConfig>
|
||||
* @author AI Assistant
|
||||
* @since 2025-11-04
|
||||
*/
|
||||
@GetMapping("/enabled")
|
||||
public ResultDomain<List<TbAiAgentConfig>> getEnabledAgents() {
|
||||
public ResultDomain<TbAiAgentConfig> getEnabledAgents() {
|
||||
log.info("获取启用的智能体列表");
|
||||
return agentConfigService.listEnabledAgents();
|
||||
}
|
||||
@@ -94,12 +95,12 @@ public class AiAgentConfigController {
|
||||
/**
|
||||
* @description 查询智能体列表
|
||||
* @param agentConfig 智能体配置
|
||||
* @return ResultDomain<List<TbAiAgentConfig>>
|
||||
* @return ResultDomain<TbAiAgentConfig>
|
||||
* @author AI Assistant
|
||||
* @since 2025-11-04
|
||||
*/
|
||||
@PostMapping("/list")
|
||||
public ResultDomain<List<TbAiAgentConfig>> listAgents(
|
||||
public ResultDomain<TbAiAgentConfig> listAgents(
|
||||
@RequestBody TbAiAgentConfig agentConfig) {
|
||||
log.info("查询智能体列表: agentConfig={}", agentConfig);
|
||||
return agentConfigService.listAgents(agentConfig);
|
||||
@@ -121,34 +122,31 @@ public class AiAgentConfigController {
|
||||
|
||||
/**
|
||||
* @description 更新智能体状态
|
||||
* @param id 智能体ID
|
||||
* @param status 状态(0禁用 1启用)
|
||||
* @param requestBody 请求体(id, status)
|
||||
* @return ResultDomain<Boolean>
|
||||
* @author AI Assistant
|
||||
* @since 2025-11-04
|
||||
*/
|
||||
@PutMapping("/{id}/status")
|
||||
public ResultDomain<Boolean> updateStatus(
|
||||
@PathVariable String id,
|
||||
@RequestParam Integer status) {
|
||||
@PutMapping("/status")
|
||||
public ResultDomain<Boolean> updateStatus(@RequestBody Map<String, Object> requestBody) {
|
||||
String id = (String) requestBody.get("id");
|
||||
Integer status = (Integer) requestBody.get("status");
|
||||
log.info("更新智能体状态: id={}, status={}", id, status);
|
||||
return agentConfigService.updateAgentStatus(id, status);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 更新Dify配置
|
||||
* @param id 智能体ID
|
||||
* @param difyAppId Dify应用ID
|
||||
* @param difyApiKey Dify API Key
|
||||
* @param requestBody 请求体(id, difyAppId, difyApiKey)
|
||||
* @return ResultDomain<Boolean>
|
||||
* @author AI Assistant
|
||||
* @since 2025-11-04
|
||||
*/
|
||||
@PutMapping("/{id}/dify")
|
||||
public ResultDomain<Boolean> updateDifyConfig(
|
||||
@PathVariable String id,
|
||||
@RequestParam String difyAppId,
|
||||
@RequestParam String difyApiKey) {
|
||||
@PutMapping("/dify")
|
||||
public ResultDomain<Boolean> updateDifyConfig(@RequestBody Map<String, Object> requestBody) {
|
||||
String id = (String) requestBody.get("id");
|
||||
String difyAppId = (String) requestBody.get("difyAppId");
|
||||
String difyApiKey = (String) requestBody.get("difyApiKey");
|
||||
log.info("更新Dify配置: id={}, difyAppId={}", id, difyAppId);
|
||||
return agentConfigService.updateDifyConfig(id, difyAppId, difyApiKey);
|
||||
}
|
||||
@@ -163,8 +161,8 @@ public class AiAgentConfigController {
|
||||
*/
|
||||
@GetMapping("/check-name")
|
||||
public ResultDomain<Boolean> checkNameExists(
|
||||
@RequestParam String name,
|
||||
@RequestParam(required = false) String excludeId) {
|
||||
@RequestParam(name = "name") String name,
|
||||
@RequestParam(name = "excludeId", required = false) String excludeId) {
|
||||
log.info("检查名称是否存在: name={}, excludeId={}", name, excludeId);
|
||||
return agentConfigService.checkNameExists(name, excludeId);
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||
import org.xyzh.api.ai.chat.AiChatService;
|
||||
import org.xyzh.api.ai.history.AiChatHistoryService;
|
||||
import org.xyzh.common.core.domain.ResultDomain;
|
||||
@@ -12,6 +13,7 @@ import org.xyzh.common.core.page.PageParam;
|
||||
import org.xyzh.common.dto.ai.TbAiConversation;
|
||||
import org.xyzh.common.dto.ai.TbAiMessage;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@@ -37,22 +39,29 @@ public class AiChatController {
|
||||
|
||||
/**
|
||||
* @description 流式对话(SSE)
|
||||
* @param requestBody 请求体(agentId, conversationId, query, knowledgeIds)
|
||||
* @return ResultDomain<TbAiMessage>
|
||||
* @param agentId 智能体ID
|
||||
* @param conversationId 会话ID
|
||||
* @param query 用户问题
|
||||
* @param knowledgeIds 知识库ID列表(逗号分隔)
|
||||
* @return SseEmitter SSE流式推送对象
|
||||
* @author AI Assistant
|
||||
* @since 2025-11-04
|
||||
*/
|
||||
@PostMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
|
||||
public ResultDomain<TbAiMessage> streamChat(@RequestBody Map<String, Object> requestBody) {
|
||||
String agentId = (String) requestBody.get("agentId");
|
||||
String conversationId = (String) requestBody.get("conversationId");
|
||||
String query = (String) requestBody.get("query");
|
||||
@SuppressWarnings("unchecked")
|
||||
List<String> knowledgeIds = (List<String>) requestBody.get("knowledgeIds");
|
||||
Object callback = requestBody.get("callback");
|
||||
@GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
|
||||
public SseEmitter streamChat(
|
||||
@RequestParam(name = "agentId") String agentId,
|
||||
@RequestParam(name = "conversationId", required = false) String conversationId,
|
||||
@RequestParam(name = "query") String query,
|
||||
@RequestParam(name = "knowledgeIds", required = false) String knowledgeIds) {
|
||||
|
||||
// 解析knowledgeIds
|
||||
List<String> knowledgeIdList = null;
|
||||
if (knowledgeIds != null && !knowledgeIds.isEmpty()) {
|
||||
knowledgeIdList = Arrays.asList(knowledgeIds.split(","));
|
||||
}
|
||||
|
||||
log.info("流式对话: agentId={}, conversationId={}, query={}", agentId, conversationId, query);
|
||||
return chatService.streamChat(agentId, conversationId, query, knowledgeIds, callback);
|
||||
return chatService.streamChatWithSse(agentId, conversationId, query, knowledgeIdList);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -74,34 +83,33 @@ public class AiChatController {
|
||||
return chatService.blockingChat(agentId, conversationId, query, knowledgeIds);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @description 停止对话生成
|
||||
* @param messageId 消息ID
|
||||
* @description 停止对话生成(通过Dify TaskID)
|
||||
* @param requestBody 请求体(taskId, agentId)
|
||||
* @return ResultDomain<Boolean>
|
||||
* @author AI Assistant
|
||||
* @since 2025-11-04
|
||||
* @since 2025-11-05
|
||||
*/
|
||||
@PostMapping("/stop/{messageId}")
|
||||
public ResultDomain<Boolean> stopChat(@PathVariable String messageId) {
|
||||
log.info("停止对话生成: messageId={}", messageId);
|
||||
return chatService.stopChat(messageId);
|
||||
@PostMapping("/stop-by-taskid")
|
||||
public ResultDomain<Boolean> stopChatByTaskId(@RequestBody Map<String, Object> requestBody) {
|
||||
String taskId = (String) requestBody.get("taskId");
|
||||
String agentId = (String) requestBody.get("agentId");
|
||||
log.info("停止对话生成(通过TaskID): taskId={}, agentId={}", taskId, agentId);
|
||||
return chatService.stopChatByTaskId(taskId, agentId);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 重新生成回答
|
||||
* @description 重新生成回答(SSE流式)
|
||||
* @param messageId 原消息ID
|
||||
* @param requestBody 请求体(可包含callback)
|
||||
* @return ResultDomain<TbAiMessage>
|
||||
* @return SseEmitter SSE流式推送对象
|
||||
* @author AI Assistant
|
||||
* @since 2025-11-04
|
||||
* @since 2025-11-05
|
||||
*/
|
||||
@PostMapping("/regenerate/{messageId}")
|
||||
public ResultDomain<TbAiMessage> regenerateAnswer(
|
||||
@PathVariable String messageId,
|
||||
@RequestBody(required = false) Map<String, Object> requestBody) {
|
||||
@GetMapping(value = "/regenerate/{messageId}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
|
||||
public SseEmitter regenerateAnswer(@PathVariable(name = "messageId") String messageId) {
|
||||
log.info("重新生成回答: messageId={}", messageId);
|
||||
Object callback = requestBody != null ? requestBody.get("callback") : null;
|
||||
return chatService.regenerateAnswer(messageId, callback);
|
||||
return chatService.regenerateAnswerWithSse(messageId);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -114,7 +122,7 @@ public class AiChatController {
|
||||
*/
|
||||
@PostMapping("/message/{messageId}/rate")
|
||||
public ResultDomain<Boolean> rateMessage(
|
||||
@PathVariable String messageId,
|
||||
@PathVariable(name = "messageId") String messageId,
|
||||
@RequestBody Map<String, Object> requestBody) {
|
||||
Integer rating = (Integer) requestBody.get("rating");
|
||||
String feedback = (String) requestBody.get("feedback");
|
||||
@@ -148,7 +156,7 @@ public class AiChatController {
|
||||
* @since 2025-11-04
|
||||
*/
|
||||
@GetMapping("/conversation/{conversationId}")
|
||||
public ResultDomain<TbAiConversation> getConversation(@PathVariable String conversationId) {
|
||||
public ResultDomain<TbAiConversation> getConversation(@PathVariable(name = "conversationId") String conversationId) {
|
||||
log.info("获取会话信息: conversationId={}", conversationId);
|
||||
return chatService.getConversation(conversationId);
|
||||
}
|
||||
@@ -174,7 +182,7 @@ public class AiChatController {
|
||||
* @since 2025-11-04
|
||||
*/
|
||||
@DeleteMapping("/conversation/{conversationId}")
|
||||
public ResultDomain<Boolean> deleteConversation(@PathVariable String conversationId) {
|
||||
public ResultDomain<Boolean> deleteConversation(@PathVariable(name = "conversationId") String conversationId) {
|
||||
log.info("删除会话: conversationId={}", conversationId);
|
||||
return chatService.deleteConversation(conversationId);
|
||||
}
|
||||
@@ -182,13 +190,13 @@ public class AiChatController {
|
||||
/**
|
||||
* @description 获取用户的会话列表
|
||||
* @param agentId 智能体ID(可选)
|
||||
* @return ResultDomain<List<TbAiConversation>>
|
||||
* @return ResultDomain<TbAiConversation>
|
||||
* @author AI Assistant
|
||||
* @since 2025-11-04
|
||||
*/
|
||||
@GetMapping("/conversations")
|
||||
public ResultDomain<List<TbAiConversation>> listUserConversations(
|
||||
@RequestParam(required = false) String agentId) {
|
||||
public ResultDomain<TbAiConversation> listUserConversations(
|
||||
@RequestParam(name = "agentId", required = false) String agentId) {
|
||||
log.info("获取用户会话列表: agentId={}", agentId);
|
||||
return chatService.listUserConversations(agentId);
|
||||
}
|
||||
@@ -198,12 +206,12 @@ public class AiChatController {
|
||||
/**
|
||||
* @description 获取会话的消息列表
|
||||
* @param conversationId 会话ID
|
||||
* @return ResultDomain<List<TbAiMessage>>
|
||||
* @return ResultDomain<TbAiMessage>
|
||||
* @author AI Assistant
|
||||
* @since 2025-11-04
|
||||
*/
|
||||
@GetMapping("/conversation/{conversationId}/messages")
|
||||
public ResultDomain<List<TbAiMessage>> listMessages(@PathVariable String conversationId) {
|
||||
public ResultDomain<TbAiMessage> listMessages(@PathVariable(name = "conversationId") String conversationId) {
|
||||
log.info("获取会话消息列表: conversationId={}", conversationId);
|
||||
return chatService.listMessages(conversationId);
|
||||
}
|
||||
@@ -216,7 +224,7 @@ public class AiChatController {
|
||||
* @since 2025-11-04
|
||||
*/
|
||||
@GetMapping("/message/{messageId}")
|
||||
public ResultDomain<TbAiMessage> getMessage(@PathVariable String messageId) {
|
||||
public ResultDomain<TbAiMessage> getMessage(@PathVariable(name = "messageId") String messageId) {
|
||||
log.info("获取消息: messageId={}", messageId);
|
||||
return chatService.getMessage(messageId);
|
||||
}
|
||||
@@ -229,7 +237,7 @@ public class AiChatController {
|
||||
* @since 2025-11-04
|
||||
*/
|
||||
@PostMapping("/conversation/{conversationId}/summary")
|
||||
public ResultDomain<Boolean> generateSummary(@PathVariable String conversationId) {
|
||||
public ResultDomain<Boolean> generateSummary(@PathVariable(name = "conversationId") String conversationId) {
|
||||
log.info("生成会话摘要: conversationId={}", conversationId);
|
||||
return chatService.generateSummaryAsync(conversationId);
|
||||
}
|
||||
@@ -264,7 +272,7 @@ public class AiChatController {
|
||||
*/
|
||||
@PostMapping("/history/search")
|
||||
public PageDomain<TbAiConversation> searchConversations(
|
||||
@RequestParam String keyword,
|
||||
@RequestParam(name = "keyword") String keyword,
|
||||
@RequestBody PageParam pageParam) {
|
||||
log.info("搜索会话: keyword={}", keyword);
|
||||
return chatHistoryService.searchConversations(keyword, pageParam);
|
||||
@@ -272,32 +280,30 @@ public class AiChatController {
|
||||
|
||||
/**
|
||||
* @description 收藏/取消收藏会话
|
||||
* @param conversationId 会话ID
|
||||
* @param isFavorite 是否收藏
|
||||
* @param requestBody 请求体(conversationId, isFavorite)
|
||||
* @return ResultDomain<Boolean>
|
||||
* @author AI Assistant
|
||||
* @since 2025-11-04
|
||||
*/
|
||||
@PutMapping("/history/conversation/{conversationId}/favorite")
|
||||
public ResultDomain<Boolean> toggleFavorite(
|
||||
@PathVariable String conversationId,
|
||||
@RequestParam Boolean isFavorite) {
|
||||
@PutMapping("/history/conversation/favorite")
|
||||
public ResultDomain<Boolean> toggleFavorite(@RequestBody Map<String, Object> requestBody) {
|
||||
String conversationId = (String) requestBody.get("conversationId");
|
||||
Boolean isFavorite = (Boolean) requestBody.get("isFavorite");
|
||||
log.info("{}收藏会话: conversationId={}", isFavorite ? "添加" : "取消", conversationId);
|
||||
return chatHistoryService.toggleFavorite(conversationId, isFavorite);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 置顶/取消置顶会话
|
||||
* @param conversationId 会话ID
|
||||
* @param isPinned 是否置顶
|
||||
* @param requestBody 请求体(conversationId, isPinned)
|
||||
* @return ResultDomain<Boolean>
|
||||
* @author AI Assistant
|
||||
* @since 2025-11-04
|
||||
*/
|
||||
@PutMapping("/history/conversation/{conversationId}/pin")
|
||||
public ResultDomain<Boolean> togglePin(
|
||||
@PathVariable String conversationId,
|
||||
@RequestParam Boolean isPinned) {
|
||||
@PutMapping("/history/conversation/pin")
|
||||
public ResultDomain<Boolean> togglePin(@RequestBody Map<String, Object> requestBody) {
|
||||
String conversationId = (String) requestBody.get("conversationId");
|
||||
Boolean isPinned = (Boolean) requestBody.get("isPinned");
|
||||
log.info("{}置顶会话: conversationId={}", isPinned ? "添加" : "取消", conversationId);
|
||||
return chatHistoryService.togglePin(conversationId, isPinned);
|
||||
}
|
||||
@@ -325,7 +331,7 @@ public class AiChatController {
|
||||
* @since 2025-11-04
|
||||
*/
|
||||
@GetMapping("/history/export/markdown/{conversationId}")
|
||||
public ResultDomain<String> exportAsMarkdown(@PathVariable String conversationId) {
|
||||
public ResultDomain<String> exportAsMarkdown(@PathVariable(name = "conversationId") String conversationId) {
|
||||
log.info("导出会话(Markdown): conversationId={}", conversationId);
|
||||
return chatHistoryService.exportConversationAsMarkdown(conversationId);
|
||||
}
|
||||
@@ -338,7 +344,7 @@ public class AiChatController {
|
||||
* @since 2025-11-04
|
||||
*/
|
||||
@GetMapping("/history/export/json/{conversationId}")
|
||||
public ResultDomain<String> exportAsJson(@PathVariable String conversationId) {
|
||||
public ResultDomain<String> exportAsJson(@PathVariable(name = "conversationId") String conversationId) {
|
||||
log.info("导出会话(JSON): conversationId={}", conversationId);
|
||||
return chatHistoryService.exportConversationAsJson(conversationId);
|
||||
}
|
||||
@@ -346,13 +352,13 @@ public class AiChatController {
|
||||
/**
|
||||
* @description 获取最近对话列表
|
||||
* @param limit 限制数量(可选,默认10)
|
||||
* @return ResultDomain<List<TbAiConversation>>
|
||||
* @return ResultDomain<TbAiConversation>
|
||||
* @author AI Assistant
|
||||
* @since 2025-11-04
|
||||
*/
|
||||
@GetMapping("/history/recent")
|
||||
public ResultDomain<TbAiConversation> getRecentConversations(
|
||||
@RequestParam(defaultValue = "10") Integer limit) {
|
||||
@RequestParam(name = "limit", defaultValue = "10") Integer limit) {
|
||||
log.info("获取最近对话列表: limit={}", limit);
|
||||
return chatHistoryService.getRecentConversations(limit);
|
||||
}
|
||||
@@ -366,7 +372,7 @@ public class AiChatController {
|
||||
*/
|
||||
@GetMapping("/history/statistics")
|
||||
public ResultDomain<Map<String, Object>> getUserChatStatistics(
|
||||
@RequestParam(required = false) String userId) {
|
||||
@RequestParam(name = "userId", required = false) String userId) {
|
||||
log.info("获取用户对话统计: userId={}", userId);
|
||||
return chatHistoryService.getUserChatStatistics(userId);
|
||||
}
|
||||
@@ -379,7 +385,7 @@ public class AiChatController {
|
||||
* @since 2025-11-04
|
||||
*/
|
||||
@GetMapping("/history/conversation/{conversationId}/statistics")
|
||||
public ResultDomain<Map<String, Object>> getConversationStatistics(@PathVariable String conversationId) {
|
||||
public ResultDomain<Map<String, Object>> getConversationStatistics(@PathVariable(name = "conversationId") String conversationId) {
|
||||
log.info("获取会话统计: conversationId={}", conversationId);
|
||||
return chatHistoryService.getConversationStatistics(conversationId);
|
||||
}
|
||||
|
||||
@@ -40,9 +40,9 @@ public class AiFileUploadController {
|
||||
*/
|
||||
@PostMapping("/upload")
|
||||
public ResultDomain<TbAiUploadFile> uploadFile(
|
||||
@RequestParam String knowledgeId,
|
||||
@RequestParam("file") MultipartFile file,
|
||||
@RequestParam(required = false) String indexingTechnique) {
|
||||
@RequestParam(name = "knowledgeId") String knowledgeId,
|
||||
@RequestParam(name = "file") MultipartFile file,
|
||||
@RequestParam(name = "indexingTechnique", required = false) String indexingTechnique) {
|
||||
log.info("上传文件到知识库: knowledgeId={}, fileName={}", knowledgeId, file.getOriginalFilename());
|
||||
return uploadFileService.uploadToKnowledge(knowledgeId, file, indexingTechnique);
|
||||
}
|
||||
@@ -52,15 +52,15 @@ public class AiFileUploadController {
|
||||
* @param knowledgeId 知识库ID
|
||||
* @param files 文件列表
|
||||
* @param indexingTechnique 索引方式(可选)
|
||||
* @return ResultDomain<List<TbAiUploadFile>>
|
||||
* @return ResultDomain<TbAiUploadFile>
|
||||
* @author AI Assistant
|
||||
* @since 2025-11-04
|
||||
*/
|
||||
@PostMapping("/upload/batch")
|
||||
public ResultDomain<List<TbAiUploadFile>> batchUploadFiles(
|
||||
@RequestParam String knowledgeId,
|
||||
@RequestParam("files") MultipartFile[] files,
|
||||
@RequestParam(required = false) String indexingTechnique) {
|
||||
public ResultDomain<TbAiUploadFile> batchUploadFiles(
|
||||
@RequestParam(name = "knowledgeId") String knowledgeId,
|
||||
@RequestParam(name = "files") MultipartFile[] files,
|
||||
@RequestParam(name = "indexingTechnique", required = false) String indexingTechnique) {
|
||||
log.info("批量上传文件: knowledgeId={}, fileCount={}", knowledgeId, files.length);
|
||||
return uploadFileService.batchUploadToKnowledge(knowledgeId, Arrays.asList(files), indexingTechnique);
|
||||
}
|
||||
@@ -73,7 +73,7 @@ public class AiFileUploadController {
|
||||
* @since 2025-11-04
|
||||
*/
|
||||
@GetMapping("/{fileId}")
|
||||
public ResultDomain<TbAiUploadFile> getFile(@PathVariable String fileId) {
|
||||
public ResultDomain<TbAiUploadFile> getFile(@PathVariable(name = "fileId") String fileId) {
|
||||
log.info("获取文件信息: fileId={}", fileId);
|
||||
return uploadFileService.getFileById(fileId);
|
||||
}
|
||||
@@ -81,12 +81,12 @@ public class AiFileUploadController {
|
||||
/**
|
||||
* @description 查询知识库的文件列表
|
||||
* @param knowledgeId 知识库ID
|
||||
* @return ResultDomain<List<TbAiUploadFile>>
|
||||
* @return ResultDomain<TbAiUploadFile>
|
||||
* @author AI Assistant
|
||||
* @since 2025-11-04
|
||||
*/
|
||||
@GetMapping("/list")
|
||||
public ResultDomain<List<TbAiUploadFile>> listFiles(@RequestParam String knowledgeId) {
|
||||
public ResultDomain<TbAiUploadFile> listFiles(@RequestParam(name = "knowledgeId") String knowledgeId) {
|
||||
log.info("查询知识库文件列表: knowledgeId={}", knowledgeId);
|
||||
return uploadFileService.listFilesByKnowledge(knowledgeId);
|
||||
}
|
||||
@@ -112,7 +112,7 @@ public class AiFileUploadController {
|
||||
* @since 2025-11-04
|
||||
*/
|
||||
@DeleteMapping("/{fileId}")
|
||||
public ResultDomain<Boolean> deleteFile(@PathVariable String fileId) {
|
||||
public ResultDomain<Boolean> deleteFile(@PathVariable(name = "fileId") String fileId) {
|
||||
log.info("删除文件: fileId={}", fileId);
|
||||
return uploadFileService.deleteFile(fileId);
|
||||
}
|
||||
@@ -125,7 +125,7 @@ public class AiFileUploadController {
|
||||
* @since 2025-11-04
|
||||
*/
|
||||
@GetMapping("/{fileId}/status")
|
||||
public ResultDomain<TbAiUploadFile> getFileStatus(@PathVariable String fileId) {
|
||||
public ResultDomain<TbAiUploadFile> getFileStatus(@PathVariable(name = "fileId") String fileId) {
|
||||
log.info("查询文件处理状态: fileId={}", fileId);
|
||||
return uploadFileService.getFileStatus(fileId);
|
||||
}
|
||||
@@ -138,7 +138,7 @@ public class AiFileUploadController {
|
||||
* @since 2025-11-04
|
||||
*/
|
||||
@PostMapping("/{fileId}/sync")
|
||||
public ResultDomain<TbAiUploadFile> syncFileStatus(@PathVariable String fileId) {
|
||||
public ResultDomain<TbAiUploadFile> syncFileStatus(@PathVariable(name = "fileId") String fileId) {
|
||||
log.info("同步文件状态: fileId={}", fileId);
|
||||
return uploadFileService.syncFileStatus(fileId);
|
||||
}
|
||||
@@ -146,12 +146,12 @@ public class AiFileUploadController {
|
||||
/**
|
||||
* @description 批量同步知识库的所有文件状态
|
||||
* @param knowledgeId 知识库ID
|
||||
* @return ResultDomain<List<TbAiUploadFile>>
|
||||
* @return ResultDomain<TbAiUploadFile>
|
||||
* @author AI Assistant
|
||||
* @since 2025-11-04
|
||||
*/
|
||||
@PostMapping("/sync/knowledge/{knowledgeId}")
|
||||
public ResultDomain<List<TbAiUploadFile>> syncKnowledgeFiles(@PathVariable String knowledgeId) {
|
||||
public ResultDomain<TbAiUploadFile> syncKnowledgeFiles(@PathVariable(name = "knowledgeId") String knowledgeId) {
|
||||
log.info("批量同步知识库文件状态: knowledgeId={}", knowledgeId);
|
||||
return uploadFileService.syncKnowledgeFiles(knowledgeId);
|
||||
}
|
||||
|
||||
@@ -69,7 +69,7 @@ public class AiKnowledgeController {
|
||||
* @since 2025-11-04
|
||||
*/
|
||||
@DeleteMapping("/{id}")
|
||||
public ResultDomain<Boolean> deleteKnowledge(@PathVariable String id) {
|
||||
public ResultDomain<Boolean> deleteKnowledge(@PathVariable(name = "id") String id) {
|
||||
log.info("删除知识库: id={}", id);
|
||||
return knowledgeService.deleteKnowledge(id);
|
||||
}
|
||||
@@ -82,7 +82,7 @@ public class AiKnowledgeController {
|
||||
* @since 2025-11-04
|
||||
*/
|
||||
@GetMapping("/{id}")
|
||||
public ResultDomain<TbAiKnowledge> getKnowledge(@PathVariable String id) {
|
||||
public ResultDomain<TbAiKnowledge> getKnowledge(@PathVariable(name = "id") String id) {
|
||||
log.info("获取知识库: id={}", id);
|
||||
return knowledgeService.getKnowledgeById(id);
|
||||
}
|
||||
@@ -90,12 +90,12 @@ public class AiKnowledgeController {
|
||||
/**
|
||||
* @description 查询知识库列表
|
||||
* @param filter 过滤条件
|
||||
* @return ResultDomain<List<TbAiKnowledge>>
|
||||
* @return ResultDomain<TbAiKnowledge>
|
||||
* @author AI Assistant
|
||||
* @since 2025-11-04
|
||||
*/
|
||||
@PostMapping("/list")
|
||||
public ResultDomain<List<TbAiKnowledge>> listKnowledges(
|
||||
public ResultDomain<TbAiKnowledge> listKnowledges(
|
||||
@RequestBody(required = false) TbAiKnowledge filter) {
|
||||
log.info("查询知识库列表");
|
||||
return knowledgeService.listKnowledges(filter);
|
||||
@@ -122,23 +122,21 @@ public class AiKnowledgeController {
|
||||
* @since 2025-11-04
|
||||
*/
|
||||
@PostMapping("/{id}/sync")
|
||||
public ResultDomain<TbAiKnowledge> syncFromDify(@PathVariable String id) {
|
||||
public ResultDomain<TbAiKnowledge> syncFromDify(@PathVariable(name = "id") String id) {
|
||||
log.info("同步Dify知识库信息: id={}", id);
|
||||
return knowledgeService.syncFromDify(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 更新知识库权限
|
||||
* @param knowledgeId 知识库ID
|
||||
* @param requestBody 请求体(permissionType, deptIds, roleIds)
|
||||
* @param requestBody 请求体(knowledgeId, permissionType, deptIds, roleIds)
|
||||
* @return ResultDomain<Boolean>
|
||||
* @author AI Assistant
|
||||
* @since 2025-11-04
|
||||
*/
|
||||
@PutMapping("/{knowledgeId}/permission")
|
||||
public ResultDomain<Boolean> updatePermission(
|
||||
@PathVariable String knowledgeId,
|
||||
@RequestBody Map<String, Object> requestBody) {
|
||||
@PutMapping("/permission")
|
||||
public ResultDomain<Boolean> updatePermission(@RequestBody Map<String, Object> requestBody) {
|
||||
String knowledgeId = (String) requestBody.get("knowledgeId");
|
||||
String permissionType = (String) requestBody.get("permissionType");
|
||||
@SuppressWarnings("unchecked")
|
||||
List<String> deptIds = (List<String>) requestBody.get("deptIds");
|
||||
@@ -159,8 +157,8 @@ public class AiKnowledgeController {
|
||||
*/
|
||||
@GetMapping("/{knowledgeId}/permission")
|
||||
public ResultDomain<Boolean> checkPermission(
|
||||
@PathVariable String knowledgeId,
|
||||
@RequestParam String operationType) {
|
||||
@PathVariable(name = "knowledgeId") String knowledgeId,
|
||||
@RequestParam(name = "operationType") String operationType) {
|
||||
log.info("检查知识库权限: knowledgeId={}, operationType={}", knowledgeId, operationType);
|
||||
return knowledgeService.checkKnowledgePermission(knowledgeId, operationType);
|
||||
}
|
||||
@@ -173,7 +171,7 @@ public class AiKnowledgeController {
|
||||
* @since 2025-11-04
|
||||
*/
|
||||
@GetMapping("/{id}/stats")
|
||||
public ResultDomain<TbAiKnowledge> getKnowledgeStats(@PathVariable String id) {
|
||||
public ResultDomain<TbAiKnowledge> getKnowledgeStats(@PathVariable(name = "id") String id) {
|
||||
log.info("获取知识库统计信息: id={}", id);
|
||||
return knowledgeService.getKnowledgeStats(id);
|
||||
}
|
||||
|
||||
@@ -35,8 +35,8 @@ public class DifyProxyController {
|
||||
*/
|
||||
@GetMapping("/datasets/{datasetId}/documents/{documentId}/segments")
|
||||
public ResultDomain<String> getDocumentSegments(
|
||||
@PathVariable String datasetId,
|
||||
@PathVariable String documentId) {
|
||||
@PathVariable(name = "datasetId") String datasetId,
|
||||
@PathVariable(name = "documentId") String documentId) {
|
||||
ResultDomain<String> result = new ResultDomain<>();
|
||||
log.info("获取文档分段列表: datasetId={}, documentId={}", datasetId, documentId);
|
||||
|
||||
@@ -65,9 +65,9 @@ public class DifyProxyController {
|
||||
*/
|
||||
@GetMapping("/datasets/{datasetId}/documents/{documentId}/segments/{segmentId}/child_chunks")
|
||||
public ResultDomain<String> getChildChunks(
|
||||
@PathVariable String datasetId,
|
||||
@PathVariable String documentId,
|
||||
@PathVariable String segmentId) {
|
||||
@PathVariable(name = "datasetId") String datasetId,
|
||||
@PathVariable(name = "documentId") String documentId,
|
||||
@PathVariable(name = "segmentId") String segmentId) {
|
||||
|
||||
log.info("获取子块列表: datasetId={}, documentId={}, segmentId={}",
|
||||
datasetId, documentId, segmentId);
|
||||
@@ -101,10 +101,10 @@ public class DifyProxyController {
|
||||
*/
|
||||
@PatchMapping("/datasets/{datasetId}/documents/{documentId}/segments/{segmentId}/child_chunks/{childChunkId}")
|
||||
public ResultDomain<String> updateChildChunk(
|
||||
@PathVariable String datasetId,
|
||||
@PathVariable String documentId,
|
||||
@PathVariable String segmentId,
|
||||
@PathVariable String childChunkId,
|
||||
@PathVariable(name = "datasetId") String datasetId,
|
||||
@PathVariable(name = "documentId") String documentId,
|
||||
@PathVariable(name = "segmentId") String segmentId,
|
||||
@PathVariable(name = "childChunkId") String childChunkId,
|
||||
@RequestBody Map<String, Object> requestBody) {
|
||||
|
||||
log.info("更新子块: datasetId={}, documentId={}, segmentId={}, childChunkId={}",
|
||||
@@ -138,9 +138,9 @@ public class DifyProxyController {
|
||||
*/
|
||||
@PostMapping("/datasets/{datasetId}/documents/{documentId}/segments/{segmentId}/child_chunks")
|
||||
public ResultDomain<String> createChildChunk(
|
||||
@PathVariable String datasetId,
|
||||
@PathVariable String documentId,
|
||||
@PathVariable String segmentId,
|
||||
@PathVariable(name = "datasetId") String datasetId,
|
||||
@PathVariable(name = "documentId") String documentId,
|
||||
@PathVariable(name = "segmentId") String segmentId,
|
||||
@RequestBody Map<String, Object> requestBody) {
|
||||
|
||||
log.info("创建子块: datasetId={}, documentId={}, segmentId={}",
|
||||
@@ -174,10 +174,10 @@ public class DifyProxyController {
|
||||
*/
|
||||
@DeleteMapping("/datasets/{datasetId}/documents/{documentId}/segments/{segmentId}/child_chunks/{childChunkId}")
|
||||
public ResultDomain<String> deleteChildChunk(
|
||||
@PathVariable String datasetId,
|
||||
@PathVariable String documentId,
|
||||
@PathVariable String segmentId,
|
||||
@PathVariable String childChunkId) {
|
||||
@PathVariable(name = "datasetId") String datasetId,
|
||||
@PathVariable(name = "documentId") String documentId,
|
||||
@PathVariable(name = "segmentId") String segmentId,
|
||||
@PathVariable(name = "childChunkId") String childChunkId) {
|
||||
|
||||
log.info("删除子块: datasetId={}, documentId={}, segmentId={}, childChunkId={}",
|
||||
datasetId, documentId, segmentId, childChunkId);
|
||||
|
||||
@@ -240,8 +240,8 @@ public class AiAgentConfigServiceImpl implements AiAgentConfigService {
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResultDomain<List<TbAiAgentConfig>> listEnabledAgents() {
|
||||
ResultDomain<List<TbAiAgentConfig>> resultDomain = new ResultDomain<>();
|
||||
public ResultDomain<TbAiAgentConfig> listEnabledAgents() {
|
||||
ResultDomain<TbAiAgentConfig> resultDomain = new ResultDomain<>();
|
||||
|
||||
try {
|
||||
TbAiAgentConfig filter = new TbAiAgentConfig();
|
||||
@@ -259,8 +259,8 @@ public class AiAgentConfigServiceImpl implements AiAgentConfigService {
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResultDomain<List<TbAiAgentConfig>> listAgents(TbAiAgentConfig filter) {
|
||||
ResultDomain<List<TbAiAgentConfig>> resultDomain = new ResultDomain<>();
|
||||
public ResultDomain<TbAiAgentConfig> listAgents(TbAiAgentConfig filter) {
|
||||
ResultDomain<TbAiAgentConfig> resultDomain = new ResultDomain<>();
|
||||
|
||||
try {
|
||||
List<TbAiAgentConfig> agents = agentConfigMapper.selectAgentConfigs(filter);
|
||||
|
||||
@@ -7,6 +7,7 @@ import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||
import org.xyzh.ai.client.DifyApiClient;
|
||||
import org.xyzh.ai.client.callback.StreamCallback;
|
||||
import org.xyzh.ai.client.dto.ChatRequest;
|
||||
@@ -24,6 +25,7 @@ import org.xyzh.common.dto.ai.TbAiMessage;
|
||||
import org.xyzh.common.dto.user.TbSysUser;
|
||||
import org.xyzh.system.utils.LoginUtil;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
@@ -58,48 +60,46 @@ public class AiChatServiceImpl implements AiChatService {
|
||||
|
||||
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
// 异步任务线程池
|
||||
// 异步任务线程池(用于异步生成摘要等后台任务)
|
||||
private final ExecutorService executorService = Executors.newFixedThreadPool(3);
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public ResultDomain<TbAiMessage> streamChat(
|
||||
String agentId,
|
||||
String conversationId,
|
||||
String query,
|
||||
List<String> knowledgeIds,
|
||||
Object callbackObj) {
|
||||
|
||||
ResultDomain<TbAiMessage> resultDomain = new ResultDomain<>();
|
||||
StreamCallback callback = (callbackObj instanceof StreamCallback) ? (StreamCallback) callbackObj : null;
|
||||
|
||||
public SseEmitter streamChatWithSse(String agentId, String conversationId, String query, List<String> knowledgeIds) {
|
||||
// 创建SseEmitter,设置超时时间为5分钟
|
||||
SseEmitter emitter = new SseEmitter(5 * 60 * 1000L);
|
||||
|
||||
try {
|
||||
// 1. 参数验证
|
||||
if (!StringUtils.hasText(agentId)) {
|
||||
resultDomain.fail("智能体ID不能为空");
|
||||
return resultDomain;
|
||||
emitter.send(SseEmitter.event().name("error").data("智能体ID不能为空"));
|
||||
emitter.complete();
|
||||
return emitter;
|
||||
}
|
||||
if (!StringUtils.hasText(query)) {
|
||||
resultDomain.fail("问题不能为空");
|
||||
return resultDomain;
|
||||
emitter.send(SseEmitter.event().name("error").data("问题不能为空"));
|
||||
emitter.complete();
|
||||
return emitter;
|
||||
}
|
||||
|
||||
// 2. 获取当前用户
|
||||
// 2. 获取当前用户(在主线程中,可以正常获取)
|
||||
TbSysUser currentUser = LoginUtil.getCurrentUser();
|
||||
if (currentUser == null) {
|
||||
resultDomain.fail("用户未登录");
|
||||
return resultDomain;
|
||||
emitter.send(SseEmitter.event().name("error").data("用户未登录"));
|
||||
emitter.complete();
|
||||
return emitter;
|
||||
}
|
||||
|
||||
// 3. 查询智能体配置
|
||||
TbAiAgentConfig agent = agentConfigMapper.selectAgentConfigById(agentId);
|
||||
if (agent == null || agent.getDeleted()) {
|
||||
resultDomain.fail("智能体不存在");
|
||||
return resultDomain;
|
||||
emitter.send(SseEmitter.event().name("error").data("智能体不存在"));
|
||||
emitter.complete();
|
||||
return emitter;
|
||||
}
|
||||
if (agent.getStatus() != 1) {
|
||||
resultDomain.fail("智能体未启用");
|
||||
return resultDomain;
|
||||
emitter.send(SseEmitter.event().name("error").data("智能体未启用"));
|
||||
emitter.complete();
|
||||
return emitter;
|
||||
}
|
||||
|
||||
// 4. 获取或创建会话
|
||||
@@ -107,168 +107,255 @@ public class AiChatServiceImpl implements AiChatService {
|
||||
if (StringUtils.hasText(conversationId)) {
|
||||
conversation = conversationMapper.selectConversationById(conversationId);
|
||||
if (conversation == null || conversation.getDeleted()) {
|
||||
resultDomain.fail("会话不存在");
|
||||
return resultDomain;
|
||||
emitter.send(SseEmitter.event().name("error").data("会话不存在"));
|
||||
emitter.complete();
|
||||
return emitter;
|
||||
}
|
||||
// 验证会话所属权
|
||||
if (!conversation.getUserID().equals(currentUser.getID())) {
|
||||
resultDomain.fail("无权访问此会话");
|
||||
return resultDomain;
|
||||
emitter.send(SseEmitter.event().name("error").data("无权访问此会话"));
|
||||
emitter.complete();
|
||||
return emitter;
|
||||
}
|
||||
} else {
|
||||
// 创建新会话
|
||||
ResultDomain<TbAiConversation> createResult = createConversation(agentId, null);
|
||||
if (!createResult.isSuccess()) {
|
||||
resultDomain.fail(createResult.getMessage());
|
||||
return resultDomain;
|
||||
emitter.send(SseEmitter.event().name("error").data(createResult.getMessage()));
|
||||
emitter.complete();
|
||||
return emitter;
|
||||
}
|
||||
conversation = createResult.getData();
|
||||
conversationId = conversation.getID();
|
||||
}
|
||||
|
||||
final String finalConversationId = conversation.getID();
|
||||
|
||||
// 5. 创建用户消息记录
|
||||
TbAiMessage userMessage = new TbAiMessage();
|
||||
userMessage.setID(UUID.randomUUID().toString());
|
||||
userMessage.setConversationID(conversationId);
|
||||
userMessage.setConversationID(finalConversationId);
|
||||
userMessage.setAgentID(agentId);
|
||||
userMessage.setRole("user");
|
||||
userMessage.setContent(query);
|
||||
userMessage.setCreateTime(new Date());
|
||||
userMessage.setUpdateTime(new Date());
|
||||
userMessage.setDeleted(false);
|
||||
|
||||
userMessage.setUserID(currentUser.getID());
|
||||
messageMapper.insertMessage(userMessage);
|
||||
|
||||
// 6. 创建AI回复消息记录(初始为空)
|
||||
TbAiMessage aiMessage = new TbAiMessage();
|
||||
aiMessage.setID(UUID.randomUUID().toString());
|
||||
aiMessage.setConversationID(conversationId);
|
||||
aiMessage.setAgentID(agentId);
|
||||
aiMessage.setRole("assistant");
|
||||
aiMessage.setContent(""); // 初始为空,流式更新
|
||||
aiMessage.setCreateTime(new Date());
|
||||
aiMessage.setUpdateTime(new Date());
|
||||
aiMessage.setDeleted(false);
|
||||
|
||||
messageMapper.insertMessage(aiMessage);
|
||||
// 注意:AI消息记录将在获取到Dify的task_id后创建
|
||||
|
||||
// 7. 构建Dify请求
|
||||
ChatRequest chatRequest = new ChatRequest();
|
||||
chatRequest.setQuery(query);
|
||||
chatRequest.setUser(currentUser.getID());
|
||||
|
||||
// 设置会话ID(如果是继续对话)
|
||||
if (StringUtils.hasText(conversation.getDifyConversationId())) {
|
||||
chatRequest.setConversationId(conversation.getDifyConversationId());
|
||||
}
|
||||
|
||||
// 设置知识库检索(如果指定)
|
||||
if (knowledgeIds != null && !knowledgeIds.isEmpty()) {
|
||||
chatRequest.setDatasetIds(knowledgeIds);
|
||||
}
|
||||
|
||||
// 使用agent配置的参数
|
||||
if (agent.getTemperature() != null) {
|
||||
chatRequest.setTemperature(agent.getTemperature().doubleValue());
|
||||
} else {
|
||||
chatRequest.setTemperature(difyConfig.getChat().getDefaultTemperature());
|
||||
}
|
||||
|
||||
if (agent.getMaxTokens() != null) {
|
||||
chatRequest.setMaxTokens(agent.getMaxTokens());
|
||||
} else {
|
||||
chatRequest.setMaxTokens(difyConfig.getChat().getDefaultMaxTokens());
|
||||
}
|
||||
chatRequest.setTemperature(agent.getTemperature() != null ?
|
||||
agent.getTemperature().doubleValue() : difyConfig.getChat().getDefaultTemperature());
|
||||
chatRequest.setMaxTokens(agent.getMaxTokens() != null ?
|
||||
agent.getMaxTokens() : difyConfig.getChat().getDefaultMaxTokens());
|
||||
|
||||
// 8. 调用Dify流式对话
|
||||
final String finalConversationId = conversationId;
|
||||
final String finalAiMessageId = aiMessage.getID();
|
||||
// 6. 调用Dify流式对话
|
||||
final TbAiConversation finalConversation = conversation;
|
||||
StringBuilder fullAnswer = new StringBuilder();
|
||||
AtomicReference<String> difyConversationId = new AtomicReference<>();
|
||||
AtomicReference<String> difyMessageId = new AtomicReference<>();
|
||||
|
||||
try {
|
||||
difyApiClient.streamChat(chatRequest, agent.getDifyApiKey(), new StreamCallback() {
|
||||
@Override
|
||||
public void onMessage(String message) {
|
||||
fullAnswer.append(message);
|
||||
// 转发给前端回调
|
||||
if (callback != null) {
|
||||
callback.onMessage(message);
|
||||
}
|
||||
AtomicReference<String> taskId = new AtomicReference<>(); // 用于存储Dify的task_id
|
||||
AtomicReference<Boolean> messageCreated = new AtomicReference<>(false); // 标记消息是否已创建
|
||||
AtomicReference<Boolean> isStopped = new AtomicReference<>(false); // 标记是否已停止
|
||||
difyApiClient.streamChat(chatRequest, agent.getDifyApiKey(), new StreamCallback() {
|
||||
@Override
|
||||
public void onMessage(String message) {
|
||||
if (isStopped.get()) {
|
||||
return; // 已停止,不再处理
|
||||
}
|
||||
try {
|
||||
fullAnswer.append(message);
|
||||
// 发送消息片段给前端
|
||||
emitter.send(SseEmitter.event().name("message").data(message));
|
||||
} catch (IllegalStateException e) {
|
||||
// SseEmitter已关闭(用户停止生成),标记为已停止
|
||||
isStopped.set(true);
|
||||
log.debug("SSE连接已关闭,停止发送消息");
|
||||
} catch (IOException e) {
|
||||
log.error("发送SSE消息失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onMessageEnd(String metadata) {
|
||||
try {
|
||||
// 解析metadata获取会话ID和消息ID
|
||||
JsonNode json = objectMapper.readTree(metadata);
|
||||
if (json.has("conversation_id")) {
|
||||
difyConversationId.set(json.get("conversation_id").asText());
|
||||
}
|
||||
if (json.has("id")) {
|
||||
difyMessageId.set(json.get("id").asText());
|
||||
}
|
||||
@Override
|
||||
public void onMessageEnd(String metadata) {
|
||||
if (isStopped.get()) {
|
||||
return; // 已停止,不再处理
|
||||
}
|
||||
try {
|
||||
// 解析metadata
|
||||
JsonNode json = objectMapper.readTree(metadata);
|
||||
if (json.has("conversation_id")) {
|
||||
difyConversationId.set(json.get("conversation_id").asText());
|
||||
}
|
||||
if (json.has("id")) {
|
||||
difyMessageId.set(json.get("id").asText());
|
||||
}
|
||||
|
||||
// 更新AI消息内容
|
||||
// 更新AI消息内容(使用task_id作为消息ID)
|
||||
if (taskId.get() != null) {
|
||||
TbAiMessage updateMessage = new TbAiMessage();
|
||||
updateMessage.setID(finalAiMessageId);
|
||||
updateMessage.setID(taskId.get());
|
||||
updateMessage.setContent(fullAnswer.toString());
|
||||
updateMessage.setDifyMessageId(difyMessageId.get());
|
||||
updateMessage.setUpdateTime(new Date());
|
||||
messageMapper.updateMessage(updateMessage);
|
||||
|
||||
// 更新会话的Dify会话ID
|
||||
if (StringUtils.hasText(difyConversationId.get())) {
|
||||
TbAiConversation updateConv = new TbAiConversation();
|
||||
updateConv.setID(finalConversationId);
|
||||
updateConv.setDifyConversationId(difyConversationId.get());
|
||||
updateConv.setMessageCount((conversation.getMessageCount() != null ?
|
||||
conversation.getMessageCount() : 0) + 2); // 用户问题+AI回答
|
||||
updateConv.setUpdateTime(new Date());
|
||||
conversationMapper.updateConversation(updateConv);
|
||||
}
|
||||
|
||||
if (callback != null) {
|
||||
callback.onMessageEnd(metadata);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("处理流式响应metadata失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onComplete() {
|
||||
log.info("流式对话完成: {} - {}", finalConversationId, finalAiMessageId);
|
||||
if (callback != null) {
|
||||
callback.onComplete();
|
||||
// 更新会话的Dify会话ID
|
||||
if (StringUtils.hasText(difyConversationId.get())) {
|
||||
TbAiConversation updateConv = new TbAiConversation();
|
||||
updateConv.setID(finalConversationId);
|
||||
updateConv.setDifyConversationId(difyConversationId.get());
|
||||
updateConv.setMessageCount((finalConversation.getMessageCount() != null ?
|
||||
finalConversation.getMessageCount() : 0) + 2);
|
||||
updateConv.setUpdateTime(new Date());
|
||||
conversationMapper.updateConversation(updateConv);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(Throwable error) {
|
||||
// 发送结束事件(保持兼容)
|
||||
emitter.send(SseEmitter.event().name("end").data(metadata));
|
||||
} catch (IllegalStateException e) {
|
||||
// SseEmitter已关闭,标记为已停止
|
||||
isStopped.set(true);
|
||||
log.debug("SSE连接已关闭,停止处理");
|
||||
} catch (Exception e) {
|
||||
log.error("处理流式响应metadata失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEvent(String eventType, String eventData) {
|
||||
if (isStopped.get()) {
|
||||
return; // 已停止,不再处理
|
||||
}
|
||||
try {
|
||||
// 转发所有Dify原始事件到前端(包含task_id等完整信息)
|
||||
emitter.send(SseEmitter.event().name("dify_" + eventType).data(eventData));
|
||||
log.debug("转发Dify事件: {} - {}", eventType, eventData);
|
||||
|
||||
// 如果还没有创建消息记录,尝试从任何事件中提取task_id
|
||||
if (!messageCreated.get()) {
|
||||
JsonNode json = objectMapper.readTree(eventData);
|
||||
if (json.has("task_id")) {
|
||||
String difyTaskId = json.get("task_id").asText();
|
||||
|
||||
// 只有在taskId为空时才设置并创建消息
|
||||
if (taskId.get() == null) {
|
||||
taskId.set(difyTaskId);
|
||||
|
||||
// 使用task_id作为消息ID,创建AI消息记录
|
||||
TbAiMessage aiMessage = new TbAiMessage();
|
||||
aiMessage.setID(difyTaskId); // 使用Dify的task_id作为消息ID
|
||||
aiMessage.setConversationID(finalConversationId);
|
||||
aiMessage.setAgentID(agentId);
|
||||
aiMessage.setRole("assistant");
|
||||
aiMessage.setContent("");
|
||||
aiMessage.setCreateTime(new Date());
|
||||
aiMessage.setUpdateTime(new Date());
|
||||
aiMessage.setDeleted(false);
|
||||
aiMessage.setUserID("assistant");
|
||||
messageMapper.insertMessage(aiMessage);
|
||||
|
||||
messageCreated.set(true);
|
||||
log.info("AI消息记录已创建(从{}事件提取task_id): {}", eventType, difyTaskId);
|
||||
|
||||
// 发送init事件给前端,包含task_id(作为messageId)
|
||||
Map<String, String> initData = new HashMap<>();
|
||||
initData.put("conversationId", finalConversationId);
|
||||
initData.put("messageId", difyTaskId);
|
||||
emitter.send(SseEmitter.event().name("init").data(initData));
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (IllegalStateException e) {
|
||||
// SseEmitter已关闭,标记为已停止
|
||||
isStopped.set(true);
|
||||
log.debug("SSE连接已关闭,停止转发事件");
|
||||
} catch (IOException e) {
|
||||
log.error("转发Dify事件失败: {}", eventType, e);
|
||||
} catch (Exception e) {
|
||||
log.error("处理Dify事件异常: {}", eventType, e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onComplete() {
|
||||
if (isStopped.get()) {
|
||||
log.debug("SSE连接已关闭,跳过完成处理");
|
||||
return; // 已停止,不再处理
|
||||
}
|
||||
try {
|
||||
log.info("流式对话完成: {} - {}", finalConversationId, taskId.get());
|
||||
emitter.send(SseEmitter.event().name("complete").data("对话完成"));
|
||||
emitter.complete();
|
||||
} catch (IllegalStateException e) {
|
||||
// SseEmitter已关闭
|
||||
isStopped.set(true);
|
||||
log.debug("SSE连接已关闭");
|
||||
} catch (IOException e) {
|
||||
log.error("发送完成事件失败", e);
|
||||
emitter.completeWithError(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(Throwable error) {
|
||||
if (isStopped.get()) {
|
||||
log.debug("SSE连接已关闭,跳过错误处理");
|
||||
return; // 已停止,不再处理
|
||||
}
|
||||
try {
|
||||
log.error("流式对话失败", error);
|
||||
if (callback != null) {
|
||||
callback.onError(error);
|
||||
}
|
||||
emitter.send(SseEmitter.event().name("error").data(error.getMessage()));
|
||||
emitter.completeWithError(error);
|
||||
} catch (IllegalStateException e) {
|
||||
// SseEmitter已关闭
|
||||
isStopped.set(true);
|
||||
log.debug("SSE连接已关闭");
|
||||
} catch (IOException e) {
|
||||
log.error("发送错误事件失败", e);
|
||||
emitter.completeWithError(e);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
resultDomain.success("对话成功", aiMessage);
|
||||
return resultDomain;
|
||||
|
||||
} catch (DifyException e) {
|
||||
log.error("Dify对话失败", e);
|
||||
resultDomain.fail("对话失败: " + e.getMessage());
|
||||
return resultDomain;
|
||||
}
|
||||
// 设置超时和错误回调
|
||||
emitter.onTimeout(() -> {
|
||||
isStopped.set(true);
|
||||
log.warn("SSE连接超时");
|
||||
emitter.complete();
|
||||
});
|
||||
|
||||
emitter.onError(e -> {
|
||||
isStopped.set(true);
|
||||
log.error("SSE连接错误(可能是用户停止生成)", e);
|
||||
emitter.completeWithError(e);
|
||||
});
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("流式对话异常", e);
|
||||
resultDomain.fail("对话异常: " + e.getMessage());
|
||||
return resultDomain;
|
||||
try {
|
||||
emitter.send(SseEmitter.event().name("error").data(e.getMessage()));
|
||||
emitter.completeWithError(e);
|
||||
} catch (IOException ex) {
|
||||
log.error("发送异常事件失败", ex);
|
||||
emitter.completeWithError(ex);
|
||||
}
|
||||
}
|
||||
|
||||
return emitter;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -394,26 +481,24 @@ public class AiChatServiceImpl implements AiChatService {
|
||||
return resultDomain;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public ResultDomain<Boolean> stopChat(String messageId) {
|
||||
public ResultDomain<Boolean> stopChatByTaskId(String taskId, String agentId) {
|
||||
ResultDomain<Boolean> resultDomain = new ResultDomain<>();
|
||||
|
||||
try {
|
||||
if (!StringUtils.hasText(messageId)) {
|
||||
resultDomain.fail("消息ID不能为空");
|
||||
if (!StringUtils.hasText(taskId)) {
|
||||
resultDomain.fail("任务ID不能为空");
|
||||
return resultDomain;
|
||||
}
|
||||
|
||||
// 查询消息
|
||||
TbAiMessage message = messageMapper.selectMessageById(messageId);
|
||||
if (message == null || message.getDeleted()) {
|
||||
resultDomain.fail("消息不存在");
|
||||
|
||||
if (!StringUtils.hasText(agentId)) {
|
||||
resultDomain.fail("智能体ID不能为空");
|
||||
return resultDomain;
|
||||
}
|
||||
|
||||
// 获取智能体API Key
|
||||
TbAiAgentConfig agent = agentConfigMapper.selectAgentConfigById(message.getAgentID());
|
||||
TbAiAgentConfig agent = agentConfigMapper.selectAgentConfigById(agentId);
|
||||
if (agent == null) {
|
||||
resultDomain.fail("智能体不存在");
|
||||
return resultDomain;
|
||||
@@ -421,21 +506,21 @@ public class AiChatServiceImpl implements AiChatService {
|
||||
|
||||
// 调用Dify停止API
|
||||
TbSysUser currentUser = LoginUtil.getCurrentUser();
|
||||
if (currentUser != null && StringUtils.hasText(message.getDifyMessageId())) {
|
||||
if (currentUser != null) {
|
||||
try {
|
||||
difyApiClient.stopChatMessage(
|
||||
message.getDifyMessageId(),
|
||||
taskId,
|
||||
currentUser.getID(),
|
||||
agent.getDifyApiKey()
|
||||
);
|
||||
log.info("对话停止成功: {}", messageId);
|
||||
log.info("对话停止成功,task_id: {}", taskId);
|
||||
resultDomain.success("停止成功", true);
|
||||
} catch (DifyException e) {
|
||||
log.error("停止对话失败", e);
|
||||
resultDomain.fail("停止失败: " + e.getMessage());
|
||||
}
|
||||
} else {
|
||||
resultDomain.fail("消息未关联Dify或用户未登录");
|
||||
resultDomain.fail("用户未登录");
|
||||
}
|
||||
|
||||
return resultDomain;
|
||||
@@ -618,8 +703,8 @@ public class AiChatServiceImpl implements AiChatService {
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResultDomain<List<TbAiConversation>> listUserConversations(String agentId) {
|
||||
ResultDomain<List<TbAiConversation>> resultDomain = new ResultDomain<>();
|
||||
public ResultDomain<TbAiConversation> listUserConversations(String agentId) {
|
||||
ResultDomain<TbAiConversation> resultDomain = new ResultDomain<>();
|
||||
|
||||
try {
|
||||
TbSysUser currentUser = LoginUtil.getCurrentUser();
|
||||
@@ -643,8 +728,8 @@ public class AiChatServiceImpl implements AiChatService {
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResultDomain<List<TbAiMessage>> listMessages(String conversationId) {
|
||||
ResultDomain<List<TbAiMessage>> resultDomain = new ResultDomain<>();
|
||||
public ResultDomain<TbAiMessage> listMessages(String conversationId) {
|
||||
ResultDomain<TbAiMessage> resultDomain = new ResultDomain<>();
|
||||
|
||||
try {
|
||||
if (!StringUtils.hasText(conversationId)) {
|
||||
@@ -703,17 +788,17 @@ public class AiChatServiceImpl implements AiChatService {
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public ResultDomain<TbAiMessage> regenerateAnswer(String messageId, Object callbackObj) {
|
||||
ResultDomain<TbAiMessage> resultDomain = new ResultDomain<>();
|
||||
StreamCallback callback = (callbackObj instanceof StreamCallback) ? (StreamCallback) callbackObj : null;
|
||||
public SseEmitter regenerateAnswerWithSse(String messageId) {
|
||||
// 创建SseEmitter,设置超时时间为5分钟
|
||||
SseEmitter emitter = new SseEmitter(5 * 60 * 1000L);
|
||||
|
||||
try {
|
||||
// 查询原消息
|
||||
TbAiMessage originalMessage = messageMapper.selectMessageById(messageId);
|
||||
if (originalMessage == null || originalMessage.getDeleted()) {
|
||||
resultDomain.fail("消息不存在");
|
||||
return resultDomain;
|
||||
emitter.send(SseEmitter.event().name("error").data("消息不存在"));
|
||||
emitter.complete();
|
||||
return emitter;
|
||||
}
|
||||
|
||||
// 找到用户的原始问题(上一条消息)
|
||||
@@ -731,32 +816,29 @@ public class AiChatServiceImpl implements AiChatService {
|
||||
}
|
||||
|
||||
if (userQuestion == null) {
|
||||
resultDomain.fail("找不到原始问题");
|
||||
return resultDomain;
|
||||
}
|
||||
|
||||
// 重新发起对话
|
||||
if (callback != null) {
|
||||
return streamChat(
|
||||
originalMessage.getAgentID(),
|
||||
originalMessage.getConversationID(),
|
||||
userQuestion.getContent(),
|
||||
null,
|
||||
callback
|
||||
);
|
||||
} else {
|
||||
return blockingChat(
|
||||
originalMessage.getAgentID(),
|
||||
originalMessage.getConversationID(),
|
||||
userQuestion.getContent(),
|
||||
null
|
||||
);
|
||||
emitter.send(SseEmitter.event().name("error").data("找不到原始问题"));
|
||||
emitter.complete();
|
||||
return emitter;
|
||||
}
|
||||
|
||||
// 直接返回streamChatWithSse的结果
|
||||
return streamChatWithSse(
|
||||
originalMessage.getAgentID(),
|
||||
originalMessage.getConversationID(),
|
||||
userQuestion.getContent(),
|
||||
null
|
||||
);
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("重新生成回答异常", e);
|
||||
resultDomain.fail("重新生成失败: " + e.getMessage());
|
||||
return resultDomain;
|
||||
try {
|
||||
emitter.send(SseEmitter.event().name("error").data(e.getMessage()));
|
||||
emitter.completeWithError(e);
|
||||
} catch (IOException ex) {
|
||||
log.error("发送异常事件失败", ex);
|
||||
emitter.completeWithError(ex);
|
||||
}
|
||||
return emitter;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -829,7 +911,49 @@ public class AiChatServiceImpl implements AiChatService {
|
||||
return resultDomain;
|
||||
}
|
||||
|
||||
// 更新评价
|
||||
// 获取智能体配置(需要API Key)
|
||||
TbAiAgentConfig agent = agentConfigMapper.selectAgentConfigById(message.getAgentID());
|
||||
if (agent == null) {
|
||||
resultDomain.fail("智能体不存在");
|
||||
return resultDomain;
|
||||
}
|
||||
|
||||
// 获取当前用户
|
||||
TbSysUser currentUser = LoginUtil.getCurrentUser();
|
||||
if (currentUser == null) {
|
||||
resultDomain.fail("用户未登录");
|
||||
return resultDomain;
|
||||
}
|
||||
|
||||
// 如果有Dify消息ID,同步反馈到Dify
|
||||
if (StringUtils.hasText(message.getDifyMessageId())) {
|
||||
try {
|
||||
// 将评分转换为Dify格式:1=like, -1=dislike, 0=null
|
||||
String difyRating = null;
|
||||
if (rating != null) {
|
||||
if (rating > 0) {
|
||||
difyRating = "like";
|
||||
} else if (rating < 0) {
|
||||
difyRating = "dislike";
|
||||
}
|
||||
// rating == 0 时,difyRating 为 null(取消评价)
|
||||
}
|
||||
|
||||
difyApiClient.submitMessageFeedback(
|
||||
message.getDifyMessageId(),
|
||||
difyRating,
|
||||
currentUser.getID(),
|
||||
feedback,
|
||||
agent.getDifyApiKey()
|
||||
);
|
||||
log.info("Dify消息反馈提交成功: {} - {}", message.getDifyMessageId(), difyRating);
|
||||
} catch (DifyException e) {
|
||||
log.error("提交Dify反馈失败", e);
|
||||
// 不影响本地评价,继续执行
|
||||
}
|
||||
}
|
||||
|
||||
// 更新本地评价
|
||||
TbAiMessage update = new TbAiMessage();
|
||||
update.setID(messageId);
|
||||
update.setRating(rating);
|
||||
|
||||
@@ -354,8 +354,8 @@ public class AiKnowledgeServiceImpl implements AiKnowledgeService {
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResultDomain<List<TbAiKnowledge>> listKnowledges(TbAiKnowledge filter) {
|
||||
ResultDomain<List<TbAiKnowledge>> resultDomain = new ResultDomain<>();
|
||||
public ResultDomain<TbAiKnowledge> listKnowledges(TbAiKnowledge filter) {
|
||||
ResultDomain<TbAiKnowledge> resultDomain = new ResultDomain<>();
|
||||
|
||||
try {
|
||||
List<UserDeptRoleVO> userDeptRoles = LoginUtil.getCurrentDeptRole();
|
||||
|
||||
@@ -186,12 +186,12 @@ public class AiUploadFileServiceImpl implements AiUploadFileService {
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public ResultDomain<List<TbAiUploadFile>> batchUploadToKnowledge(
|
||||
public ResultDomain<TbAiUploadFile> batchUploadToKnowledge(
|
||||
String knowledgeId,
|
||||
List<MultipartFile> files,
|
||||
String indexingTechnique) {
|
||||
|
||||
ResultDomain<List<TbAiUploadFile>> resultDomain = new ResultDomain<>();
|
||||
ResultDomain<TbAiUploadFile> resultDomain = new ResultDomain<>();
|
||||
|
||||
try {
|
||||
if (files == null || files.isEmpty()) {
|
||||
@@ -322,8 +322,8 @@ public class AiUploadFileServiceImpl implements AiUploadFileService {
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResultDomain<List<TbAiUploadFile>> listFilesByKnowledge(String knowledgeId) {
|
||||
ResultDomain<List<TbAiUploadFile>> resultDomain = new ResultDomain<>();
|
||||
public ResultDomain<TbAiUploadFile> listFilesByKnowledge(String knowledgeId) {
|
||||
ResultDomain<TbAiUploadFile> resultDomain = new ResultDomain<>();
|
||||
|
||||
try {
|
||||
if (!StringUtils.hasText(knowledgeId)) {
|
||||
@@ -443,8 +443,8 @@ public class AiUploadFileServiceImpl implements AiUploadFileService {
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResultDomain<List<TbAiUploadFile>> syncKnowledgeFiles(String knowledgeId) {
|
||||
ResultDomain<List<TbAiUploadFile>> resultDomain = new ResultDomain<>();
|
||||
public ResultDomain<TbAiUploadFile> syncKnowledgeFiles(String knowledgeId) {
|
||||
ResultDomain<TbAiUploadFile> resultDomain = new ResultDomain<>();
|
||||
|
||||
try {
|
||||
// 查询知识库的所有文件
|
||||
|
||||
@@ -87,10 +87,7 @@
|
||||
|
||||
<!-- 逻辑删除会话 -->
|
||||
<update id="deleteConversation" parameterType="org.xyzh.common.dto.ai.TbAiConversation">
|
||||
UPDATE tb_ai_conversation
|
||||
SET deleted = 1,
|
||||
delete_time = NOW()
|
||||
WHERE id = #{ID} AND deleted = 0
|
||||
DELETE FROM tb_ai_conversation WHERE id = #{ID}
|
||||
</update>
|
||||
|
||||
<!-- 根据ID查询会话 -->
|
||||
|
||||
Reference in New Issue
Block a user