liusuyi
2026-05-18 0b8c8d8986a35c3e36db1503125e2dff79d6d10e
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
package com.ard.agent.config;
 
import com.alibaba.cloud.ai.graph.agent.ReactAgent;
import com.alibaba.cloud.ai.graph.agent.hook.modelcalllimit.ModelCallLimitHook;
import com.alibaba.cloud.ai.graph.checkpoint.savers.MemorySaver;
import com.ard.agent.tool.MonitorTools;
import jakarta.annotation.Resource;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.support.ToolCallbacks;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
@Configuration
public class AgentConfig {
 
    @Resource
    @Qualifier("ollamaChatModel")
    private ChatModel chatModel;
    @Resource
    private MonitorTools monitorTools;
    @Resource
    private ChatMemory chatMemory;  // 注入聊天记忆
 
 
    // 增强版的系统提示词,专门为 ReAct 模式优化
    private static final String SYSTEM_PROMPT = """
            你是摄像头管理助手,拥有调用工具和查询知识库的能力。
            
            ## 工作方式
            你需要通过「思考 → 行动 → 观察」的循环来完成任务:
            
            1. **思考 (Thought)**:分析用户需求,判断下一步该做什么
            2. **行动 (Action)**:决定调用哪个工具
               - getCameraDetail: 查询单个摄像机详情
               - searchCameras: 按条件搜索摄像机
               - updateCameraInfo: 修改摄像机信息
               - 知识库查询: 获取操作指南/故障排查手册
            3. **观察 (Observation)**:分析工具返回的结果
            4. **重复**:直到获得足够信息回答用户
            
            ## 工具使用原则
            - 涉及摄像机实时状态、修改操作 → 必须调用工具
            - 询问操作指南、故障排查 → 使用知识库
            - 复杂任务需要多个步骤时,自动规划并依次调用工具
            
            ## 输出格式
            使用 Markdown 格式输出:
            - ## 标题
            - - 列表项
            - **加粗** 强调
            - 表格用于数据展示
            
            ## 重要提醒
            不要编造信息,所有数据必须来自工具调用或知识库。
            """;
    ModelCallLimitHook hook = ModelCallLimitHook.builder()
            .runLimit(5)  // 限制最多调用 5 次
            .exitBehavior(ModelCallLimitHook.ExitBehavior.ERROR)  // 超出限制时抛出异常
            .build();
 
    @Bean
    public ReactAgent cameraAgent() {
        return ReactAgent.builder()
                .name("cameraAgent") // Agent 的名称
                .model(chatModel)      // 设置底层的大语言模型
                .hooks(hook)
                .instruction(SYSTEM_PROMPT) // 系统提示词,定义角色和行为
                .tools(ToolCallbacks.from(monitorTools))       // 注册可用的工具
                .saver(new MemorySaver())      // 2. 核心:用 MemorySaver 实现记忆
                .enableLogging(true)   // 开启日志,方便调试观察思考过程
                .build();
    }
}