package com.ard.agent.service;
|
|
import com.alibaba.cloud.ai.graph.RunnableConfig;
|
import com.alibaba.cloud.ai.graph.agent.ReactAgent;
|
import com.alibaba.cloud.ai.graph.exception.GraphRunnerException;
|
import com.ard.common.security.utils.SecurityUtils;
|
import jakarta.annotation.Resource;
|
import lombok.extern.slf4j.Slf4j;
|
import org.springframework.ai.chat.messages.AssistantMessage;
|
import org.springframework.ai.content.Content;
|
import org.springframework.stereotype.Service;
|
import reactor.core.publisher.Flux;
|
|
@Slf4j
|
@Service
|
public class AIChatService {
|
|
@Resource(name = "unifiedAgent")
|
private ReactAgent unifiedAgent;
|
|
/**
|
* 唯一流式聊天入口
|
*/
|
public Flux<String> streamChat(String userMessage) {
|
try {
|
return unifiedAgent.streamMessages(userMessage, runnableConfig())
|
.filter(msg -> msg instanceof AssistantMessage)
|
.map(Content::getText)
|
.doOnError(error -> log.error("Agent执行出错: {}", error.getMessage()));
|
} catch (GraphRunnerException e) {
|
throw new RuntimeException(e);
|
}
|
}
|
|
/**
|
* 唯一同步聊天入口
|
*/
|
public String chat(String userMessage) throws GraphRunnerException {
|
AssistantMessage response = unifiedAgent.call(userMessage, runnableConfig());
|
return response.getText();
|
}
|
|
private RunnableConfig runnableConfig() {
|
return RunnableConfig.builder()
|
.threadId(currentThreadId())
|
.build();
|
}
|
|
private String currentThreadId() {
|
Long userId;
|
try {
|
userId = SecurityUtils.getUserId();
|
} catch (Exception e) {
|
userId = null;
|
}
|
return userId == null ? "anonymous" : userId.toString();
|
}
|
}
|