2026/4/4 4:16:46
网站建设
项目流程
织梦网站管理安装,清远佛冈住房和城乡建设局网站,做美图网站有哪些东西,源码论坛网搭建一、 Agent开发整体大纲主要包括6层1. 用户交互层#xff08;包括web界面#xff0c;cli,api)#xff0c;没太多东西。2. Agent 核心层主要有控制器#xff08;ReAct#xff09;、推理引擎#xff08;Chain-of-Thought)、工具调用#xff08;function call, mcp)、记忆管…一、 Agent开发整体大纲主要包括6层1. 用户交互层包括web界面cli,api)没太多东西。2. Agent 核心层主要有控制器ReAct、推理引擎Chain-of-Thought)、工具调用function call, mcp)、记忆管理、prompt、上下文。其实记忆管理、prompt、上下文都可以归类到context只是做了进一步细分。3. 工具层各种原子化、外调的能力4. LLM 服务层调各种大模型5. 数据存储层比较常用的是向量数据库RAG的存储、缓存系统输入缓存、结果缓存向量数据库对于java boy来说是个新知识点要好好学。6. agent平台能力保障包括性能监控、告警、token调用成本等。二、Agent开发工具类Dify工具Dify 是一个用于构建 AI 工作流的开源平台。通过在可视化画布上编排 AI 模型、连接数据源、数据存储层定义处理流程转化为可运行的软件。输出结果可以是现在通用的chat方式、也可以集成到各种企业软件钉钉、飞书等。https://docs.dify.ai/zh/use-dify/getting-started/introduction这块一般由公司的AI工程基础团队搞定部署一个内部版本的dify,这样其他的java boy就可以在这个基础上拖拖拽拽搞起来了。Agent核心层把dify中的各个节点拆出来就是agent的核心层。主要控制节点有用户输入、LLM、知识检索、工具、输出。有些同学刚开始开发Agent时发现能力都外调了agent就是一个流程编排和传统的流程编排也没什么区别啊Dify vs 传统流程引擎编排工具对比分析本质差异DifyAI 应用的编排平台专注于 AI 能力组合传统流程引擎业务流程的执行引擎专注于任务调度对于java boy来说很容易把各个业务能力都封装到各个tool里面然后用流程引擎串起来而忽略了发挥AI能力。另外一方面对于非技术出身的搞大模型的同学呢又全都依赖于AI能力把一些结构化的数据处理、确定性的一些业务流程也用大模型来进行处理导致上下文过长、输出结果不稳定。为了保障结果的确定性呢开始疯狂加分支了。两者需要结合一下。传统流程引擎如 Camunda、Activiti主要用于业务流程自动化和任务调度编排。1.设计目标与定位维度Dify传统流程引擎核心目标AI 应用构建与编排业务流程自动化主要场景AI 对话、知识问答、内容生成审批流程、数据处理、任务调度技术栈LLM、向量数据库、Embedding关系数据库、消息队列、规则引擎2.节点类型差异Dify 的核心节点用户输入节点接收用户查询、上下文信息LLM 节点调用大语言模型GPT、Claude 等知识检索节点RAG检索增强生成、向量搜索工具节点API 调用、函数执行、外部服务集成输出节点格式化输出、多模态输出流程控制if-else、循环、条件分支传统流程引擎的核心节点任务节点人工任务、自动任务、服务任务网关节点并行网关、排他网关、包容网关事件节点开始事件、结束事件、中间事件数据节点数据对象、数据存储规则引擎业务规则判断、条件分支集成节点数据库操作、消息发送、HTTP 调用3.执行模式差异特性Dify传统流程引擎执行确定性非确定性AI 输出可能不同确定性相同输入相同输出执行方式流式响应异步处理同步/异步、批量处理状态管理对话状态上下文记忆流程实例状态任务状态性能优化Token 优化缓存策略并发控制资源调度4.数据处理方式Dify 的数据流用户输入 → 上下文理解 → 知识检索 → LLM 推理 → 工具调用 → 结果生成非结构化数据文本、图像、语音语义理解向量化、相似度搜索动态生成内容生成、摘要提取流式输出Token 流式返回传统流程引擎的数据流输入数据 → 数据验证 → 规则判断 → 任务执行 → 数据转换 → 结果输出结构化数据数据库记录、JSON、XML数据验证格式校验、业务规则校验确定性处理数据转换、计算、存储批量处理批量导入、批量计算5.集成对象差异集成类型Dify传统流程引擎AI 服务✅ LLM API、Embedding API❌ 通常不涉及知识库✅ 向量数据库、文档库❌ 关系数据库为主业务系统⚠️ 通过 API 集成✅ 深度集成ERP、CRM6.状态管理与持久化Dify对话状态多轮对话上下文记忆管理短期记忆、长期记忆向量存储文档索引、语义检索缓存机制Token 缓存、结果缓存传统流程引擎流程实例状态运行中、已完成、已终止任务状态待处理、处理中、已完成数据持久化流程数据、业务数据历史记录流程历史、审计日志7.错误处理与容错DifyLLM 调用失败重试、降级到备用模型Token 超限上下文压缩、分块处理知识检索失败降级到直接回答工具调用失败错误提示、建议替代方案传统流程引擎任务执行失败重试、补偿事务数据异常回滚、数据修复系统故障流程恢复、状态恢复超时处理超时告警、自动终止8.监控与可观测性监控指标Dify传统流程引擎性能指标Token 使用量、响应时间、成本任务执行时间、吞吐量质量指标回答准确性、用户满意度流程完成率、错误率业务指标对话轮次、知识检索命中率流程耗时、任务积压成本指标API 调用成本、Token 成本资源消耗、系统负载适用场景对比Dify 适合的场景AI 对话应用智能客服、AI 助手知识问答系统企业知识库、文档问答内容生成文章生成、代码生成、摘要提取数据分析助手自然语言查询、数据洞察多模态应用图像理解、语音交互传统流程引擎适合的场景审批流程请假审批、报销审批、合同审批数据处理ETL 流程、数据清洗、报表生成任务调度定时任务、批量作业、工作流调度系统集成系统间数据同步、业务流程打通规则引擎业务规则自动化、决策流程三、工具层Agent核心层架构总览Agent核心层├── Agent控制器 (Agent Controller)│ └── 类似Spring MVC的DispatcherServlet 策略模式├── 推理引擎 (Reasoning Engine)│ └── 类似规则引擎 决策树├── 工具调用器 (Tool Executor)│ └── 类似策略模式 工厂模式 责任链模式├── 记忆管理器 (Memory Manager)│ └── 类似缓存系统 会话管理├── Prompt管理器 (Prompt Manager)│ └── 类似模板引擎 配置管理└── 上下文管理器 (Context Manager)└── 类似ThreadLocal 请求上下文管理1. Agent控制器 (Agent Controller)概念理解Java类比类似DispatcherServlet统一接收请求分发到不同的处理器类似Controller协调各个服务组件类似策略模式根据任务类型选择不同的执行策略核心功能任务分解将复杂任务分解为子任务决策协调决定执行顺序和策略流程控制管理整个Agent的执行流程错误处理处理执行过程中的异常ReAct模式Reasoning Actingwhile循环执行思考 → 行动 → 观察 → 思考 → 行动 → ... 代码示例Java类比代码伪代码RestControllerpublic class AgentController {Autowiredprivate ReasoningEngine reasoningEngine;Autowiredprivate ToolExecutor toolExecutor;Autowiredprivate MemoryManager memoryManager;// 类似RequestMappingPostMapping(/agent/execute)public AgentResponse execute(RequestBody AgentRequest request) {// 1. 任务分解类似任务调度ListTask tasks decomposeTask(request.getInput());// 2. 决策协调类似策略模式ExecutionStrategy strategy selectStrategy(tasks);// 3. 执行流程类似责任链AgentResponse response strategy.execute(tasks);return response;}private ListTask decomposeTask(String input) {// 任务分解逻辑// 类似将复杂业务拆分为多个Service调用}}2. 推理引擎 (Reasoning Engine)概念理解Java类比类似规则引擎Drools、Easy Rules根据规则进行推理类似决策树根据条件进行分支判断类似状态机管理推理状态转换核心功能思考过程分析问题、生成推理步骤决策制定决定下一步行动逻辑推理进行逻辑判断和推理自我反思评估当前状态调整策略️ 推理模式Chain-of-Thought (CoT)问题 → 思考步骤1 → 思考步骤2 → ... → 结论代码示例Java类比代码伪代码ounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(line// 类似规则引擎public class ReasoningEngine {private RuleEngine ruleEngine; // 类似Droolspublic ReasoningResult reason(String question, Context context) {// 1. 构建推理规则类似规则定义ListRule rules buildReasoningRules(question);// 2. 执行推理类似fireRulesReasoningResult result ruleEngine.execute(rules, context);// 3. 记录推理过程logReasoningSteps(result);return result;}private ListRule buildReasoningRules(String question) {// 根据问题构建推理规则// 类似根据业务场景构建Drools规则}}3. 工具调用器 (Tool Executor)概念理解Java类比类似策略模式不同工具使用不同策略类似工厂模式根据工具类型创建执行器类似责任链模式工具调用的链式处理类似适配器模式统一不同工具的接口 核心功能工具注册注册和管理可用工具工具选择根据任务选择合适的工具工具执行执行工具并获取结果错误处理处理工具执行失败的情况️ 工具类型计算工具数学运算、统计分析搜索工具Web搜索、API调用文件工具文件读写、数据处理数据库工具SQL查询、数据操作代码工具代码执行、代码生成 代码示例Java类比代码伪代码public interface Tool {String execute(String input);String getName();String getDescription();}// 工具实现类似Service实现Componentpublic class CalculatorTool implements Tool {Overridepublic String execute(String input) {// 执行计算逻辑return calculate(input);}Overridepublic String getName() {return calculator;}}// 工具执行器类似策略管理器Servicepublic class ToolExecutor {Autowiredprivate ListTool tools; // 自动注入所有工具private MapString, Tool toolMap;PostConstructpublic void init() {// 构建工具映射类似工厂模式toolMap tools.stream().collect(Collectors.toMap(Tool::getName,tool - tool));}public ToolResult execute(String toolName, String input) {Tool tool toolMap.get(toolName);if (tool null) {throw new ToolNotFoundException(toolName);}try {String result tool.execute(input);return ToolResult.success(result);} catch (Exception e) {return ToolResult.failure(e.getMessage());}}}4. 记忆管理器 (Memory Manager)概念理解Java类比类似Session管理管理用户会话状态类似缓存系统Redis、Caffeine存储和检索数据类似ThreadLocal管理线程本地变量类似状态模式管理不同状态的记忆 核心功能短期记忆存储当前对话的上下文长期记忆存储重要的历史信息记忆检索根据上下文检索相关记忆记忆更新更新和删除记忆记忆类型短期记忆Short-term MemoryConversationBufferMemory保存完整对话历史ConversationSummaryMemory保存对话摘要ConversationBufferWindowMemory保存最近N轮对话长期记忆Long-term Memory向量数据库记忆使用向量搜索检索相关记忆数据库记忆存储在关系数据库中文件记忆存储在文件中 代码示例Python实现LangChainounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(linefrom langchain.memory import ConversationBufferMemoryfrom langchain.memory import ConversationSummaryMemoryfrom langchain.memory import VectorStoreRetrieverMemoryfrom langchain.vectorstores import Chromafrom langchain.embeddings import OpenAIEmbeddingsclass MemoryManager:记忆管理器 - 类似Java的Session管理 缓存系统def __init__(self):# 短期记忆类似Sessionself.short_term_memory ConversationBufferMemory(return_messagesTrue,memory_keychat_history)# 长期记忆类似Redis缓存self.long_term_memory Noneself.vector_store Nonedef initialize_long_term_memory(self):初始化长期记忆 - 类似初始化缓存系统embeddings OpenAIEmbeddings()self.vector_store Chroma(embedding_functionembeddings,persist_directory./memory_db)self.long_term_memory VectorStoreRetrieverMemory(retrieverself.vector_store.as_retriever(),memory_keylong_term_history)def save_short_term(self, user_input: str, ai_response: str):保存短期记忆 - 类似Session.setAttributeself.short_term_memory.save_context({input: user_input},{output: ai_response})def save_long_term(self, key: str, value: str):保存长期记忆 - 类似Redis.setif self.long_term_memory:self.long_term_memory.save_context({input: key},{output: value})def retrieve_memories(self, query: str, k: int 5):检索记忆 - 类似缓存查询memories []# 检索短期记忆类似从Session获取short_term self.short_term_memory.load_memory_variables({})if short_term:memories.extend(short_term.get(chat_history, []))# 检索长期记忆类似从Redis查询if self.long_term_memory:long_term self.long_term_memory.load_memory_variables({input: query})if long_term:memories.extend(long_term.get(long_term_history, []))return memories[:k]def clear_short_term(self):清空短期记忆 - 类似Session.invalidateself.short_term_memory.clear()def update_memory(self, key: str, value: str):更新记忆 - 类似缓存更新if self.long_term_memory:self.long_term_memory.save_context({input: key},{output: value})def delete_memory(self, key: str):删除记忆 - 类似缓存删除if self.vector_store:# 删除向量数据库中的记忆# 实现删除逻辑pass# 使用示例memory_manager MemoryManager()memory_manager.initialize_long_term_memory()# 保存短期记忆memory_manager.save_short_term(用户你好, AI你好有什么可以帮助你的)# 保存长期记忆memory_manager.save_long_term(用户偏好, 喜欢简洁的回答)# 检索记忆memories memory_manager.retrieve_memories(用户偏好)print(memories)5. Prompt管理器 (Prompt Manager)概念理解Java类比类似模板引擎Thymeleaf、FreeMarker管理模板类似配置管理Spring Config管理配置类似策略模式不同场景使用不同Prompt类似建造者模式构建复杂的Prompt核心功能Prompt模板管理存储和管理Prompt模板Prompt构建根据上下文构建PromptPrompt优化优化Prompt以提高效果Prompt版本管理管理不同版本的PromptPrompt类型Zero-shot Prompt零样本提示Few-shot Prompt少样本提示Chain-of-Thought Prompt思维链提示Role-based Prompt角色扮演提示代码示例Python实现LangChainounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(lineounter(linefrom langchain.prompts import PromptTemplatefrom langchain.prompts import ChatPromptTemplatefrom typing import Dict, Anyimport jsonclass PromptManager:Prompt管理器 - 类似Java的模板引擎 配置管理def __init__(self):self.templates: Dict[str, PromptTemplate] {} # 模板注册表self.prompt_configs: Dict[str, Dict] {} # Prompt配置def register_template(self, name: str, template: str, input_variables: list):注册Prompt模板 - 类似注册Thymeleaf模板prompt_template PromptTemplate(input_variablesinput_variables,templatetemplate)self.templates[name] prompt_templateprint(fPrompt模板已注册: {name})def build_prompt(self, template_name: str, variables: Dict[str, Any]) - str:构建Prompt - 类似模板引擎渲染if template_name not in self.templates:raise ValueError(f模板不存在: {template_name})template self.templates[template_name]return template.format(**variables)def load_prompt_config(self, config_path: str):加载Prompt配置 - 类似加载Spring配置with open(config_path, r, encodingutf-8) as f:configs json.load(f)for name, config in configs.items():self.prompt_configs[name] configself.register_template(namename,templateconfig[template],input_variablesconfig[input_variables])def get_prompt(self, scenario: str, context: Dict[str, Any]) - str:获取Prompt - 类似根据场景获取模板# 根据场景选择模板template_name self._select_template(scenario)# 构建Promptprompt self.build_prompt(template_name, context)# 优化Prompt可选optimized_prompt self._optimize_prompt(prompt, context)return optimized_promptdef _select_template(self, scenario: str) - str:选择模板 - 类似策略选择template_mapping {qa: qa_template,summarization: summary_template,code_generation: code_template,analysis: analysis_template}return template_mapping.get(scenario, default_template)def _optimize_prompt(self, prompt: str, context: Dict) - str:优化Prompt - 类似模板优化# 可以添加Prompt优化逻辑# 例如压缩、添加示例、调整格式等return prompt# Prompt模板定义示例qa_template 你是一个专业的AI助手。请根据以下上下文回答问题。上下文{context}问题{question}请提供准确、详细的回答few_shot_template 你是一个数据分析专家。请根据以下示例进行分析。示例1输入{example1_input}输出{example1_output}示例2输入{example2_input}输出{example2_output}现在请分析输入{user_input}输出# 使用示例prompt_manager PromptManager()# 注册模板类似配置模板prompt_manager.register_template(nameqa_template,templateqa_template,input_variables[context, question])prompt_manager.register_template(namefew_shot_template,templatefew_shot_template,input_variables[example1_input, example1_output,example2_input, example2_output, user_input])# 构建Prompt类似模板渲染prompt prompt_manager.build_prompt(qa_template,{context: Python是一种编程语言,question: Python是什么})print(prompt)6. 上下文管理器 (Context Manager)概念理解Java类比类似ThreadLocal管理线程本地变量类似RequestContext管理请求上下文类似Spring的Scope管理作用域类似缓存管理管理Token使用和成本核心功能上下文收集收集对话上下文信息Token管理管理Token使用和限制上下文压缩压缩过长的上下文成本优化优化API调用成本上下文类型对话上下文当前对话的历史知识上下文从知识库检索的相关信息工具上下文工具执行的结果系统上下文系统配置和状态代码示例Python实现from langchain.schema import BaseMessagefrom typing import List, Dictimport tiktokenclass ContextManager:上下文管理器 - 类似Java的ThreadLocal 请求上下文def __init__(self, max_tokens: int 4000, model: str gpt-3.5-turbo):self.max_tokens max_tokensself.model modelself.encoding tiktoken.encoding_for_model(model)self.context_history: List[BaseMessage] []def add_context(self, message: BaseMessage):添加上下文 - 类似ThreadLocal.setself.context_history.append(message)def get_context(self) - List[BaseMessage]:获取上下文 - 类似ThreadLocal.getreturn self.context_historydef count_tokens(self, text: str) - int:计算Token数量 - 类似计算资源消耗return len(self.encoding.encode(text))def manage_context(self, new_message: str) - List[BaseMessage]:管理上下文 - 类似上下文压缩和优化# 1. 添加新消息new_tokens self.count_tokens(new_message)# 2. 计算当前上下文Token数current_tokens sum(self.count_tokens(msg.content)for msg in self.context_history)# 3. 如果超过限制进行压缩if current_tokens new_tokens self.max_tokens:self.context_history self._compress_context()return self.context_historydef _compress_context(self) - List[BaseMessage]:压缩上下文 - 类似缓存淘汰策略# 策略1保留最近的N条消息# 策略2保留最重要的消息# 策略3生成摘要# 简单实现保留最近的消息max_messages 10if len(self.context_history) max_messages:# 保留最近的消息return self.context_history[-max_messages:]return self.context_historydef clear_context(self):清空上下文 - 类似ThreadLocal.removeself.context_history.clear()def get_context_summary(self) - Dict:获取上下文摘要 - 类似获取上下文统计total_tokens sum(self.count_tokens(msg.content)for msg in self.context_history)return {message_count: len(self.context_history),total_tokens: total_tokens,remaining_tokens: self.max_tokens - total_tokens,utilization: total_tokens / self.max_tokens}# 使用示例context_manager ContextManager(max_tokens4000)# 添加上下文context_manager.add_context(BaseMessage(content用户你好, typehuman))# 管理上下文context context_manager.manage_context(AI你好有什么可以帮助你的)# 获取摘要summary context_manager.get_context_summary()print(summary)上下文管理流程上下文收集Context Collection├─ 对话历史├─ 知识检索结果└─ 工具执行结果↓Token计算Token Counting├─ 计算当前Token数├─ 预测新增Token数└─ 检查是否超限↓上下文管理Context Management├─ 如果超限压缩上下文├─ 保留重要信息└─ 删除冗余信息↓返回优化后的上下文模块间协作用户输入↓Agent控制器任务分解、决策协调↓推理引擎思考、推理↓Prompt管理器构建Prompt↓上下文管理器管理上下文、Token优化↓LLM API调用↓记忆管理器保存对话历史↓工具调用器执行工具↓结果整合↓返回用户四、向量数据库RAG向量数据库非常重要下篇单独学习。