2026/4/15 8:48:29
网站建设
项目流程
网站网页制作企业,百度一下百度搜索入口,dw网站建设教程视频,.net网站做增删改文章详细介绍了LlamaIndex框架中三种Agent模式(FunctionAgent、ReActAgent、CodeActAgent)的使用方法#xff0c;包括工具调用、上下文记忆实现、人类参与交互(HITL)、多Agent协作及结构化输出等技术要点。通过实战代码示例展示了如何构建和配置Agent#xff0c;以及如何利用…文章详细介绍了LlamaIndex框架中三种Agent模式(FunctionAgent、ReActAgent、CodeActAgent)的使用方法包括工具调用、上下文记忆实现、人类参与交互(HITL)、多Agent协作及结构化输出等技术要点。通过实战代码示例展示了如何构建和配置Agent以及如何利用事件驱动机制实现复杂工作流为开发者提供了构建大模型智能体的完整解决方案。01 前言上一篇介绍了LlamaIndex的工作流Workflow[构建Agents框架LlamaIndex使用实战之Workflow]其通过事件驱动的方式实现了工作流编排其中事件Event和上下文Context是两个核心概念与关键要素。在LlamaIndex中智能体Agent的构建同样基于事件编排机制其运行逻辑正是通过Workflow来实现的。02 相关概念LlamaIndex中定义了三种基本的Agent模式分别是FunctionAgent、ReActAgent、CodeActAgent。它们都继承至BaseWorkflowAgent类而BaseWorkflowAgent又继承至Workflow关系如下所示FunctionAgent使用大模型LLM原生Function Call能力驱动工具调用的Agent工具的调用由LLM直接返回的tool_calls JSON触发。要求模型具有Function Call的能力。ReActAgent借助LLM的提示词思考 - 执行 - 反馈这种文本协议驱动的推理式Agent需要Agent手动解析文本得到工具调用信息。比FunctionAgent适用性更广但是可能因解析工具失败而终止。CodeActAgent允许模型用Python代码执行操作的Agent可以借助LlamaIndex集成的CodeInterpreterTool等工具进行实现。类似OpenAI的Code Interpreter。03 Agent实战下面会依次介绍下Agent的简单使用、如何在Agent中使用上下文Context实现记忆、Human in the loop 人参与交互、多Agent协作、实现Agent结构化输出。示例主要使用FunctionAgent演示。定义一个Agent# pip install llama-index-core llama-index-llms-deepseek from llama_index.core.agent import FunctionAgent from llama_index.llms.deepseek import DeepSeek def multiply(a: float, b: float) - float: Multiply two numbers and returns the product print(execute multiply) return a * b def add(a: float, b: float) - float: Add two numbers and returns the sum print(execute add) return a b llm DeepSeek(modeldeepseek-chat, api_keysk-...) agent FunctionAgent( tools[multiply, add], llmllm, system_promptYou are an agent that can perform basic mathematical operations using tools., verboseTrue, ) # 执行 async def main(): result await agent.run(what is 1 add 1) print(result) if __name__ __main__: import asyncio asyncio.run(main())示例首先定义两个自定义函数作为Agent的工具通过llama-index-llms-deepseek集成并定义DeepSeek作为Agent的llm。然后实例化FunctionAgent并传入工具列表、模型和系统提示词最后调用Agent的run方法。输出如下可以看出Agent借助LLM成功调用了传入的工具execute add 1 1 2LLM提示词在任何以LLM为主的应用中都至关重要查看示例的Agent在调用LLM时提示词首先在代码最上面引入以此打开Debug日志import logging logging.basicConfig(levellogging.DEBUG)然后运行查看完整提示词摘取部分内容# 第一次输入模型提示词 [{role: system, content: You are an agent that can perform basic mathematical operations using tools.}, {role: user, content: what is 1 add 1}] tools: [{type: function, function: {name: multiply, description: multiply(a: float, b: float) - float\nMultiply two numbers and returns the product, parameters: {properties: {a: {title: A, type: number}, b: {title: B, type: number}}, required: [a, b], type: object, additionalProperties: False}, strict: False}}, {type: function, function: {name: add, description: add(a: float, b: float) - float\nAdd two numbers and returns the sum, parameters: {properties: {a: {title: A, type: number}, b: {title: B, type: number}}, required: [a, b], type: object, additionalProperties: False}, strict: False}}] # 第二次输入给模型提示词 # 可以看出第一次模型输出的assistant角色的tool_calls内容 [{role: system, content: You are an agent that can perform basic mathematical operations using tools.}, {role: user, content: what is 1 add 1}, {role: assistant, content: Ill calculate 1 1 for you., tool_calls: [{index: 0, id: call_00_HZ4zYEy8Id5u6hsh7EmUHJ8j, function: {arguments: {a: 1, b: 1}, name: add}, type: function}]}, {role: tool, content: 2, tool_call_id: call_00_HZ4zYEy8Id5u6hsh7EmUHJ8j}]示例中使用了自定义函数作为工具还可以使用LlamaIndex集成的工具通过访问https://llamahub.ai/?tabtools方便查找提供了使用步骤例如通过使用DuckDuckGoSearchToolSpec工具实现搜索功能如下所示# 使用集成的工具 pip install llama-index-tools-duckduckgo from llama_index.tools.duckduckgo import DuckDuckGoSearchToolSpec dd_tools DuckDuckGoSearchToolSpec().to_tool_list() dd_tools.extend([add, multiply]) # 定义Agent的tools toolsdd_toolsAgent也是基于Workflow的事件驱动的上面的示例通过增加调用agent的events属性可以打印出所有相关的事件它们被定义在BaseWorkflowAgent基类中。通过BaseWorkflowAgent类定义的step可以得出流程涉及事件及路径是AgentWorkflowStartEvent - AgentInput - AgentSetup - AgentOutput - StopEvent | AgentInput | ToolCall (ToolCall - ToolCallResult - StopEvent | AgentInput ) | None。竖线表示或的关系圆括号可以理解为子流程。Agent中使用上下文在上一篇Workflow中已经介绍过关于Context诸多用法在Agent中可以通过Context实现短期或者长期的记忆短期记忆通过指定和使用Agent的上下文即可长期记忆需要借助Context的序列化和外部数据库进行存储。# 额外导入包和Workflow一样的 from llama_index.core.workflow import Context # 定义上下文 ctx Context(agent) # 执行 async def main(): result await agent.run(user_msgHi, my name is DJ!, ctxctx) print(result) print(- * 10) response2 await agent.run(user_msgWhats my name?, ctxctx) print(response2) if __name__ __main__: import asyncio asyncio.run(main())示例是在上文示例的基础上更新的定义了Context作为上下文并在agent调用run的时候传入ctx参数输出如下Hi DJ! Nice to meet you. Im here to help you with basic mathematical operations. I can add or multiply numbers for you. What would you like me to help you with today? ---------- Your name is DJ! You introduced yourself at the beginning of our conversation.Human in the loop人类参与循环简写HITL描述的是一种人机交互的过程。在Agent中通过人类参与中间特定环节的输入和决策来驱动Agent按预期的路径执行。# 人类介入 from llama_index.core.agent.workflow import FunctionAgent from llama_index.llms.deepseek import DeepSeek from llama_index.core.workflow import( InputRequiredEvent, HumanResponseEvent, Context, ) llm DeepSeek(modeldeepseek-chat, api_keysk-...) async def add_money(ctx: Context) - str: A task for add money print(ctx.to_dict()) print(starting add_money task) question Are you sure you want to proceed? (yes/no): # 标准写法只用 wait_for_event它自己会把 waiter_event 写到流里 response await ctx.wait_for_event( HumanResponseEvent, waiter_idquestion, waiter_eventInputRequiredEvent( prefixquestion, user_nameUser, # 关键带 user_name ), requirements{user_name: User}, # 关键匹配条件 ) print(fresponse:{response.to_dict()}) # 根据输入处理 if response.response.strip().lower() yes: print(add_money response yes) returnadd_money task completed successfully. else: print(add_money response no) returnadd_money task aborted. # 使用 DeepSeek LLM 创建 workflow agent FunctionAgent( tools[add_money], llmllm, # 使用 DeepSeek system_promptYou are a helpful assistant that can run add_money tools. ) # 执行 async def main(): handler agent.run(user_msgUse the add_money tool to proceed with the me 100 RMB.) async for event in handler.stream_events(): # if isinstance(event, AgentStream): # print(f{event.delta}, end, flushTrue) if isinstance(event, InputRequiredEvent): print(需要人工介入:) response input(event.prefix) print(f人工输入:{response}) handler.ctx.send_event( HumanResponseEvent( responseresponse, user_nameevent.user_name, # 用事件里的名字和 requirements 对上 ) ) print(-*10) # 获取最终结果 response await handler print(f结果: {response}) while True: await asyncio.sleep(1) if __name__ __main__: import asyncio asyncio.run(main())示例首先定义了add_money工具函数代表这是一个危险动作需要人介入确认工具中调用上下文Context的wait_for_event方法设置一个等待的事件HumanResponseEvent并会发起一个InputRequiredEvent事件而后定义FunctionAgent指定了工具、模型和系统提示词最后调用异步迭代器获取stream_events的事件获取InputRequiredEvent事件后引导人类输入并将输入结果包装在HumanResponseEvent中发送。注意HumanResponseEvent会重新唤起tool这里是add_money函数的重新调用即从头开始执行示例输出如下starting add_money task 需要人工介入: Are you sure you want to proceed? (yes/no): yes 人工输入:yes starting add_money task response:{response: yes, user_name: User} add_money response yes ---------- 结果: The add_money task has been completed successfully. The operation to add 100 RMB has been processed.踩一个坑HITL示例执行一直非预期输入yes后Agent直接回复并结束测试时使用的LlamaIndex是0.14.4版本最后升级到0.14.10解决大致原因wait_for_event 当前版本不再「阻塞等待」而是通过抛出一个 “等待事件”专用异常来暂停当前步骤但由于Agent内部工具执行有代码误用了except Exception把这个异常吞掉了导致工作流无法在等待人类输入后重回等待点。相关issuehttps://github.com/run-llama/llama_index/pull/20173相关代码https://github.com/run-llama/llama_index/pull/20173/commits/e1855c6d47b37c7cef40de9b9342d37924eee48d查看版本pip index versions llama-index-core安装最新版pip install --upgrade llama-index-core多智能体LlamaIndex框架定义了三种使用多Agent的模式。1、使用内置的AgentWorkflowAgentWorkflow继承至Workflow通过指定多个Agent和一个root Agent实现多智能体协作和自动交接可以快速上手体验。agent_workflow AgentWorkflow( agents[add_agent, multiply_agent], root_agentadd_agent.name, verboseTrue, ) result await agent_workflow.run(what is 2 multiply 3)2、使用工作流编排工作流编排模式定义常规的Workflow然后通过将子Agent当作工具进行调用借助Workflow执行路径更加稳定。3、自定义执行计划自定义方式最为灵活可以自定义模型调用、解析响应、业务判断、执行路径等。篇幅原因自定义模式示例参考官方文档https://developers.llamaindex.ai/python/framework/understanding/agent/multi_agent/选型建议从AgentWorkflow 起步 - 需求变复杂时切换到 Orchestrator - 真正落地生产时选 Custom Planner。结构化输出在一些基于LLM的应用中需要LLM输出结构化数据便于继续处理后续业务对于结构化输出一些支持FunctionCall的LLM输出会更加稳定而不支持的LLM就要靠提示词输出响应并解析文本响应内容。在LlamaIndex的Agent调用流程中支持两种结构化输出方式不管哪一种Agent的执行流程最后会经过llama_index.core.agent.workflow.base_agent.BaseWorkflowAgent.parse_agent_output处理Agent的结果。此处会判断Agent是否设置了结构化输出如果有则会进一步处理示例如下# 结构化输出 # 1、方式一使用output_cls指定输出模型Pydantic BaseModel输出为结构化数据 # 2、方式二使用structured_output_fn自定义解析函数输入是一些列的ChatMessage输出为结构化数据 from llama_index.core.agent import FunctionAgent from llama_index.llms.deepseek import DeepSeek from pydantic import BaseModel, Field import json from llama_index.core.llms import ChatMessage from typing import List, Dict, Any def multiply(a: float, b: float) - float: Multiply two numbers and returns the product print(execute multiply) return a * b ## define structured output format and tools class MathResult(BaseModel): operation: str Field(descriptionthe performed operation) result: int Field(descriptionthe result of the operation) # 自定义格式化函数 async def structured_output_parsing( messages: List[ChatMessage], ) - Dict[str, Any]: # 内部StructuredLLM # 重要内部实际上是再调用一次模型生产结构化数据 # llama_index.llms.openai.base.OpenAI._stream_chat -》 openai.resources.chat.completions.completions.AsyncCompletions.create struct_llm llm.as_structured_llm(MathResult) messages.append( ChatMessage( roleuser, contentGiven the previous message history, structure the output based on the provided format., ) ) response await struct_llm.achat(messages) return json.loads(response.message.content) llm DeepSeek(modeldeepseek-chat, api_keysk-...) workflow FunctionAgent( tools[multiply], llmllm, system_promptYou are an agent that can perform basic mathematical operations using tools., output_clsMathResult, # 第一种实现方式 # structured_output_fnstructured_output_parsing, # 第二种实现方式 verboseTrue, ) # 执行 async def main(): result await workflow.run(what is 2 multi 3) # print(type(result)) # class llama_index.core.agent.workflow.workflow_events.AgentOutput print(result) # 获取结构化结果 print(result.structured_response) # {operation: 2 * 3, result: 6} print(result.get_pydantic_model(MathResult)) # operation2 * 3 result6 if __name__ __main__: import asyncio asyncio.run(main())示例代码中定义了两种方式方式一使用output_cls指定输出模型Pydantic BaseModel输出为结构化数据。方式二使用structured_output_fn自定义解析函数自定义函数输入是一些列的ChatMessage输出为结构化数据。方式一、使用output_cls内部会结合历史对话自动生成提示词多调用一次LLM输出结构化数据LlamaIndex内部实现如下# LlamaInde定义如下 # llama_index.core.agent.utils.generate_structured_response async def generate_structured_response( messages: List[ChatMessage], llm: LLM, output_cls: Type[BaseModel] ) - Dict[str, Any]: xml_message messages_to_xml_format(messages) structured_response await llm.as_structured_llm( output_cls, ).achat(messagesxml_message) return cast(Dict[str, Any], json.loads(structured_response.message.content))最终发起LLM调用时判断是否支持FunctionCallllama_index.core.llms.function_calling.FunctionCallingLLM.apredict_and_calldebug如下所示方式二、使用structured_output_fn调用的自定义函数函数内采用的仍然是通过自定义提示词调用LLM生成结构化数据也可以是其它方式自定义解析函数如下async def structured_output_parsing( messages: List[ChatMessage], ) - Dict[str, Any]: struct_llm llm.as_structured_llm(MathResult) messages.append( ChatMessage( roleuser, contentGiven the previous message history, structure the output based on the provided format., ) ) response await struct_llm.achat(messages) return json.loads(response.message.content)按示例的方式最终还是会到方式一相同的LLM处理逻辑完成结构化输出llama_index.core.llms.function_calling.FunctionCallingLLM.apredict_and_call。04 总结总体而言LlamaIndex 通过事件驱动的 Workflow 与 Agent 架构成功打通了数据获取、知识处理、模型交互之间的完整链路。其内置的 Agent 体系不仅支持工具调用、多 Agent 协同、HITL人类参与等复杂能力结合事件驱动也提供了足够的开放性与灵活性。与此同时LlamaIndex丰富的数据连接器生态与LlamaHub的便捷检索与集成方式让开发者无需“重复造轮子”即可快速构建业务级 RAG 与智能体应用。最后我在一线科技企业深耕十二载见证过太多因技术卡位而跃迁的案例。那些率先拥抱 AI 的同事早已在效率与薪资上形成代际优势我意识到有很多经验和知识值得分享给大家也可以通过我们的能力和经验解答大家在大模型的学习中的很多困惑。我整理出这套 AI 大模型突围资料包✅AI大模型学习路线图✅Agent行业报告✅100集大模型视频教程✅大模型书籍PDF✅DeepSeek教程✅AI产品经理入门资料完整的大模型学习和面试资料已经上传带到CSDN的官方了有需要的朋友可以扫描下方二维码免费领取【保证100%免费】为什么说现在普通人就业/升职加薪的首选是AI大模型人工智能技术的爆发式增长正以不可逆转之势重塑就业市场版图。从DeepSeek等国产大模型引发的科技圈热议到全国两会关于AI产业发展的政策聚焦再到招聘会上排起的长队AI的热度已从技术领域渗透到就业市场的每一个角落。智联招聘的最新数据给出了最直观的印证2025年2月AI领域求职人数同比增幅突破200%远超其他行业平均水平整个人工智能行业的求职增速达到33.4%位居各行业榜首其中人工智能工程师岗位的求职热度更是飙升69.6%。AI产业的快速扩张也让人才供需矛盾愈发突出。麦肯锡报告明确预测到2030年中国AI专业人才需求将达600万人人才缺口可能高达400万人这一缺口不仅存在于核心技术领域更蔓延至产业应用的各个环节。资料包有什么①从入门到精通的全套视频教程⑤⑥包含提示词工程、RAG、Agent等技术点② AI大模型学习路线图还有视频解说全过程AI大模型学习路线③学习电子书籍和技术文档市面上的大模型书籍确实太多了这些是我精选出来的④各大厂大模型面试题目详解⑤ 这些资料真的有用吗?这份资料由我和鲁为民博士共同整理鲁为民博士先后获得了北京清华大学学士和美国加州理工学院博士学位在包括IEEE Transactions等学术期刊和诸多国际会议上发表了超过50篇学术论文、取得了多项美国和中国发明专利同时还斩获了吴文俊人工智能科学技术奖。目前我正在和鲁博士共同进行人工智能的研究。所有的视频教程由智泊AI老师录制且资料与智泊AI共享相互补充。这份学习大礼包应该算是现在最全面的大模型学习资料了。资料内容涵盖了从入门到进阶的各类视频教程和实战项目无论你是小白还是有些技术基础的这份资料都绝对能帮助你提升薪资待遇转行大模型岗位。智泊AI始终秉持着“让每个人平等享受到优质教育资源”的育人理念通过动态追踪大模型开发、数据标注伦理等前沿技术趋势构建起前沿课程智能实训精准就业的高效培养体系。课堂上不光教理论还带着学员做了十多个真实项目。学员要亲自上手搞数据清洗、模型调优这些硬核操作把课本知识变成真本事如果说你是以下人群中的其中一类都可以来智泊AI学习人工智能找到高薪工作一次小小的“投资”换来的是终身受益应届毕业生无工作经验但想要系统学习AI大模型技术期待通过实战项目掌握核心技术。零基础转型非技术背景但关注AI应用场景计划通过低代码工具实现“AI行业”跨界。业务赋能 突破瓶颈传统开发者Java/前端等学习Transformer架构与LangChain框架向AI全栈工程师转型。获取方式有需要的小伙伴可以保存图片到wx扫描二v码免费领取【保证100%免费】**