2026/4/18 10:57:27
网站建设
项目流程
做网站怎么开后台,西安seo霸屏,vps 建网站 代理,小江高端企业网站建设上一篇介绍了LlamaIndex的工作流#xff08;Workflow#xff09;#xff0c;其通过事件驱动的方式实现了工作流编排#xff0c;其中事件#xff08;Event#xff09;和上下文#xff08;Context#xff09;是两个核心概念与关键要素。
在LlamaIndex中#xff0c;智能体…上一篇介绍了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 岗还在四处搜集零散资料别再浪费时间啦2025 年AI 大模型全套学习资料已整理完毕从学习路线到面试真题从工具教程到行业报告一站式覆盖你的所有需求现在全部免费分享扫码免费领取全部内容一、学习必备100本大模型电子书26 份行业报告 600 套技术PPT帮你看透 AI 趋势想了解大模型的行业动态、商业落地案例大模型电子书这份资料帮你站在 “行业高度” 学 AI1. 100本大模型方向电子书2. 26 份行业研究报告覆盖多领域实践与趋势报告包含阿里、DeepSeek 等权威机构发布的核心内容涵盖职业趋势《AI 职业趋势报告》《中国 AI 人才粮仓模型解析》商业落地《生成式 AI 商业落地白皮书》《AI Agent 应用落地技术白皮书》领域细分《AGI 在金融领域的应用报告》《AI GC 实践案例集》行业监测《2024 年中国大模型季度监测报告》《2025 年中国技术市场发展趋势》。3. 600套技术大会 PPT听行业大咖讲实战PPT 整理自 2024-2025 年热门技术大会包含百度、腾讯、字节等企业的一线实践安全方向《端侧大模型的安全建设》《大模型驱动安全升级腾讯代码安全实践》产品与创新《大模型产品如何创新与创收》《AI 时代的新范式构建 AI 产品》多模态与 Agent《Step-Video 开源模型视频生成进展》《Agentic RAG 的现在与未来》工程落地《从原型到生产AgentOps 加速字节 AI 应用落地》《智能代码助手 CodeFuse 的架构设计》。二、求职必看大厂 AI 岗面试 “弹药库”300 真题 107 道面经直接抱走想冲字节、腾讯、阿里、蔚来等大厂 AI 岗这份面试资料帮你提前 “押题”拒绝临场慌1. 107 道大厂面经覆盖 Prompt、RAG、大模型应用工程师等热门岗位面经整理自 2021-2025 年真实面试场景包含 TPlink、字节、腾讯、蔚来、虾皮、中兴、科大讯飞、京东等企业的高频考题每道题都附带思路解析2. 102 道 AI 大模型真题直击大模型核心考点针对大模型专属考题从概念到实践全面覆盖帮你理清底层逻辑3. 97 道 LLMs 真题聚焦大型语言模型高频问题专门拆解 LLMs 的核心痛点与解决方案比如让很多人头疼的 “复读机问题”三、路线必明 AI 大模型学习路线图1 张图理清核心内容刚接触 AI 大模型不知道该从哪学起这份「AI大模型 学习路线图」直接帮你划重点不用再盲目摸索路线图涵盖 5 大核心板块从基础到进阶层层递进一步步带你从入门到进阶从理论到实战。L1阶段:启航篇丨极速破界AI新时代L1阶段了解大模型的基础知识以及大模型在各个行业的应用和分析学习理解大模型的核心原理、关键技术以及大模型应用场景。L2阶段攻坚篇丨RAG开发实战工坊L2阶段AI大模型RAG应用开发工程主要学习RAG检索增强生成包括Naive RAG、Advanced-RAG以及RAG性能评估还有GraphRAG在内的多个RAG热门项目的分析。L3阶段跃迁篇丨Agent智能体架构设计L3阶段大模型Agent应用架构进阶实现主要学习LangChain、 LIamaIndex框架也会学习到AutoGPT、 MetaGPT等多Agent系统打造Agent智能体。L4阶段精进篇丨模型微调与私有化部署L4阶段大模型的微调和私有化部署更加深入的探讨Transformer架构学习大模型的微调技术利用DeepSpeed、Lamam Factory等工具快速进行模型微调并通过Ollama、vLLM等推理部署框架实现模型的快速部署。L5阶段专题集丨特训篇 【录播课】四、资料领取全套内容免费抱走学 AI 不用再找第二份不管你是 0 基础想入门 AI 大模型还是有基础想冲刺大厂、了解行业趋势这份资料都能满足你现在只需按照提示操作就能免费领取扫码免费领取全部内容2025 年想抓住 AI 大模型的风口别犹豫这份免费资料就是你的 “起跑线”