liusuyi
2026-05-18 8a7b666f0bed7c1dc03767166c7ecd602552a5c8
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
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();
    }
}