ARTICLE DETAIL

资讯详情

深耕网站建设、视觉设计与SEO优化的一线实战洞察。

【收藏必备】Agno框架入门指南:零基础构建高性能多智能体应用

【收藏必备】Agno框架入门指南:零基础构建高性能多智能体应用 01 前言在Github一个开源项目中(awesome-llm-apps)发现有很多Agent应用都是使用的Agno这个框架构建的然后发现Agno在Github上有34k的star提交也比较活跃于是上手体验了一番由此分享。Agno 是一个高性能的多智能体Agents框架。既可构建单一智能体也能将多个智能体组合成一个Team在 Agno 中称为 Team还支持构建稳定输出的工作流。在构建智能体时你可以灵活使用多种组件包括大语言模型LLM、存储会话与状态、记忆模块、知识库以及工具支持 MCP。官方进行了一项与 LangGraph 的性能对比测试在实例化 1000 次带工具的智能体测试任务中测试脚本详见 GithubAgno 在时间和内存使用方面均表现出显著优势。左Agno、右LangGraph除了性能该框架的另一大亮点是其 AgentOS 运行时环境。一方面它可以与 FastApp 结合快速生成 API 接口另一方面Agno 提供了控制面板方便你连接所开发的 AgentOS 进行实时监控、测试与管理。此外AgentOS 还具备隐私数据保护能力确保数据不会通过任何第三方媒介传输这一点与云厂商产品或 SaaS 系统形成鲜明对比。02 单智能体Agent首先看下Agno的基础部分也是核心部分单智能体Agent的构建。Agent可以使用**大语言模型LLM、存储会话与状态、记忆模块、知识库以及工具支持 MCP**等组件。定义一个Agent使用Agno定义并执行一个Agent只需要数行代码即可。from agno.agent import Agent from agno.models.openai import OpenAILike open_ai_like_model OpenAILike(idQwen/Qwen3-Coder-480B-A35B-Instruct, base_urlhttps://api-inference.modelscope.cn/v1, api_keyms-xxx) agent Agent(modelopen_ai_like_model) agent.print_response(自我介绍)示例通过Agent类进行实例化并指定model。使用print_response发起对Agent提问内部使用的是run方法这里也可以直接使用agent.run(“自我介绍”)。如果要流式响应指定stream参数为True。示例中的模型地址是魔塔社区的兼容OpenAI接口URL。模型是千问开源模型魔塔社区模型详情页复制id。上文示例模型定义到一个单独的同层文件中下文示例使用时导入from open_ai_like import open_ai_like_model存储如果需要保存历史****对话消息Session或者对话过程中的状态信息State就需要使用外部数据库进行存储Agno支持Mysql、Pg、Sqlite、Redis等十多种数据库。from agno.agent import Agent from open_ai_like import open_ai_like_model from agno.db.sqlite import SqliteDb from agno.session import AgentSession # set up the database db SqliteDb(db_filetmp/agno_session.db, session_tableagno_session) # Run agent andreturn the response as a variable agent Agent(description你是一个小助手, modelopen_ai_like_model, dbdb, add_history_to_contextTrue, num_history_runs2) # Retrieve the memories about the user agent.print_response(自我介绍, user_id123, session_idss-123, show_messageTrue) # 最后一次运行的消息 output agent.get_last_run_output(session_idss-123) messages output.messages for item in messages: print(f\n{item.role}:{item.content})示例使用SqliteDb进行session会话的存储。add_history_to_context:是否要加入历史消息到提示词上下文中True加入默认False。num_history_runs:加入几轮历史对话消息到上下文中。最后通过get_last_run_output获取输出内容并通过messages打印包括system、user、assistant三种类型的消息。工具支持MCPAgent可以通过使用工具扩展模型的能力边界例如获取当前时间、算数、查询天气、读取文件等等。Agno提供了内置工具调用同时也支持自定义工具以及MCP。1、内置工具Agno内置工具100个位于agno.tools包下。from agno.agent import Agent from open_ai_like import open_ai_like_model from agno.tools.duckduckgo import DuckDuckGoTools agent Agent(modelopen_ai_like_model, tools[DuckDuckGoTools()], markdownTrue) agent.print_response(Whats happening in France?, streamTrue)通过tools指定多个工具。此处使用了duckduckgo工具的web搜索能力实现新闻信息的实时获取。Agent会将工具描述以tools参数的方式发给模型。模型判断如果问题需要查询工具则调用工具并将响应内容返回给模型模型再组织响应内容。如果有必要会进行多轮工具调用。2、自定义工具def web_search(query: str) - str: Use this function to search some News. Args: query(str): query param. return Protests Against Budget Cuts: France is experiencing widespread protests and strikes across more than 240 locations. Organized by the CGT union, emonstrators are urging the government to abandon its planned budget cuts. agent Agent(description你是一个小助手, modelopen_ai_like_model, tools[web_search], markdownTrue) run_out_put agent.run(Whats happening in France?)通过tools指定自定义的web_search方法。可以通过如下方式打印提示词及工具参数run_out_put agent.run(Whats happening in France?) print(frun_out_put.tools:{run_out_put.tools}) messages run_out_put.messages for item in messages: print(f\n{item.role}:{item.content})示例会返回系统提示词如下system:你是一个小助手 additional_information - Use markdown to format your answers. /additional_information也可以通过定义Agent时指定参数debug_modeTrue输出提示词日志。3、MCPMCP即模型上下文协议Model Context ProtocolAgno支持MCP的三种传输协议Stdio、SSE、Streamable HTTP。import asyncio from agno.agent import Agent from open_ai_like import open_ai_like_model from agno.tools.mcp import MCPTools async def run_agent() - None: # Initialize the MCP tools mcp_tools MCPTools(urlhttps://docs.agno.com/mcp, transportstreamable-http) # Connect to the MCP server await mcp_tools.connect() try: agent Agent(modelopen_ai_like_model, tools[mcp_tools], markdownTrue) await agent.aprint_response(What is agno?, streamTrue) finally: # Always close the connection when done await mcp_tools.close() if __name__ __main__: asyncio.run(run_agent())示例使用MCPTools定义MCP工具transport使用的是MCP最新版本传输协议Streamable HTTP并通过connect()进行连接指定的MCP地址。asyncio是Python中一个用于并发编程标准库系统提示词系统提示词在AI应用中至关重要用于发送给模型作上下文并控制模型的输出。Agno框架支持设置系统提示词、用户提示词提问的问题、历史对话消息以及**根据部分参数补充系统提示词。**如上文中有关session的使用属于增加历史对话而markdownTrue会补充系统提示词使用markdown格式输出。1、主动设置系统提示词定义Agent时设置system_message参数可以明确指定系统提示词。设置此参数会失效其它会生成系统提示词的参数如markdownTrue不再补充系统提示词输出markdown格式。2、特定参数生成系统提示词在没有配置system_message参数时有些参数会默认生成系统提示词。from agno.agent import Agent agent Agent( descriptionYou are a famous short story writer asked to write for a magazine, instructions[You are a pilot on a plane flying from Hawaii to Japan.], markdownTrue, debug_modeTrue, # Set to True to view the detailed logs and see the compiled system message ) agent.print_response(Tell me a 2 sentence horror story., streamTrue)生成提示词如下You are a famous short story writer asked to write for a magazine instructions You are a pilot on a plane flying from Hawaii to Japan. /instructions additional_information - Use markdown to format your answers. /additional_information更多生成系统提示词的Agent参数# --- Settings for building the default system message --- # A description of the Agent that is added to the start of the system message. description: Optional[str] None # List of instructions for the agent. instructions: Optional[Union[str, List[str], Callable]] None # Provide the expected output from the Agent. expected_output: Optional[str] None # Additional context added to the end of the system message. additional_context: Optional[str] None # If markdowntrue, add instructions to format the output using markdown markdown: bool False # If True, add the agent name to the instructions add_name_to_context: bool False # If True, add the current datetime to the instructions to give the agent a sense of time # This allows for relative times like tomorrow to be used in the prompt add_datetime_to_context: bool False # If True, add the current location to the instructions to give the agent a sense of place # This allows for location-aware responses and local context add_location_to_context: bool False # Allows for custom timezone for datetime instructions following the TZ Database format (e.g. Etc/UTC) timezone_identifier: Optional[str] None # If True, resolve session_state, dependencies, and metadata in the user and system messages resolve_in_context: bool True03 多智能体Team在Agno中多Agent协作的智能体被定义为Team。“Team 是由多个 Agent或其他子Team组成的集合它们通过协作来完成各项任务。”被执行的Team被称为Team Leader其它Agent或者子Team被称为Team Member。与Agent类似Team支持设置****大语言模型LLM、存储会话、记忆模块、知识库以及工具支持 MCP。设置大模型LLM用于指导Team Leader向Team Member分配任务。其它模块的使用可以类比Agent部分。from agno.agent import Agent from agno.utils.pprint import pprint_run_response from open_ai_like import open_ai_like_model from agno.team import Team, TeamRunOutput def get_weather(city: str) - str: return fThe weather in {city} is sunny and warm. def get_news(topic: str) - str: return fThe latest news about {topic} is HAHAHA agent_1 Agent(modelopen_ai_like_model, roleNews agent, tools[get_news], descriptionget the latest news) agent_2 Agent(modelopen_ai_like_model, roleWeather agent, tools[get_weather], descriptionget the weather for the next 3 days) # 通过模型来判断要用的agent team Team(modelopen_ai_like_model, nameNews and Weather Team, members[agent_1, agent_2]) # Synchronous execution 非流式 result: TeamRunOutput team.run(inputWhat is the weather in Hangzhou?, debug_modeTrue) pprint_run_response(result) # Synchronous execution 流式 #for chunk in team.run(What is the weather in Tokyo?, streamTrue, stream_intermediate_stepsTrue): # print(chunk.content, end, flushTrue)示例定义的Team指定了两个Agent成员分别是新闻Agent和天气Agent两个Agent分别绑定了各自的工具列表。最后使用team.run进行提问。如下是Team生成的系统提示词You are the leader of a team and sub-teams of AI Agents. Your task is to coordinate the team to complete the users request. Here are the members in your team: team_members - Agent 1: - ID: f2b3e3a2-a15e-432a-a465-8cf4de227561 - Role: News agent - Member tools: - get_news - Agent 2: - ID: be6eaf34-9808-4305-ba24-38960d27d8c7 - Role: Weather agent - Member tools: - get_weather /team_members how_to_respond - Your role is to delegate tasks to members in your team with the highest likelihood of completing the users request. - Carefully analyze the tools available to the members and their roles before delegating tasks. - You cannot use a member tool directly. You can only delegate tasks to members. - When you delegate a task to another member, make sure to include: - member_id (str): The ID of the member to delegate the task to. Use only the ID of the member, not the ID of the team followed by the ID of the member. - task_description (str): A clear description of the task. - expected_output (str): The expected output. - You can delegate tasks to multiple members at once. - You must always analyze the responses from members before responding to the user. - After analyzing the responses from the members, if you feel the task has been completed, you can stop and respond to the user. - If you are not satisfied with the responses from the members, you should re-assign the task. - For simple greetings, thanks, or questions about the team itself, you should respond directly. - For all work requests, tasks, or questions requiring expertise, route to appropriate team members. /how_to_respond任务会被指派给第二个查询天气的Agent其系统提示词和用户提示词如下 system get the weather for the next 3 days your_role Weather agent /your_role user You are a member of a team of agents. Your goal is to complete the following task: task Get the current weather information for Hangzhou, China /task expected_output Current weather conditions including temperature, humidity, wind speed, and general weather description for Hangzhou /expected_output04 最后整体而言利用 Agno 构建智能体Agent能够显著降低开发成本与门槛。其有完整详尽的 API 文档大大降低了上手难度性能则是该框架的另一大亮点。Agno能力还不止于此还支持如Human in the loop以及多模态等等篇幅原因可以直接借鉴官方文档学习。最后为什么要学AI大模型当下⼈⼯智能市场迎来了爆发期并逐渐进⼊以⼈⼯通⽤智能AGI为主导的新时代。企业纷纷官宣“ AI ”战略为新兴技术⼈才创造丰富的就业机会⼈才缺⼝将达 400 万DeepSeek问世以来生成式AI和大模型技术爆发式增长让很多岗位重新成了炙手可热的新星岗位薪资远超很多后端岗位在程序员中稳居前列。与此同时AI与各行各业深度融合飞速发展成为炙手可热的新风口企业非常需要了解AI、懂AI、会用AI的员工纷纷开出高薪招聘AI大模型相关岗位。最近很多程序员朋友都已经学习或者准备学习 AI 大模型后台也经常会有小伙伴咨询学习路线和学习资料我特别拜托北京清华大学学士和美国加州理工学院博士学位的鲁为民老师给大家这里给大家准备了一份涵盖了AI大模型入门学习思维导图、精品AI大模型学习书籍手册、视频教程、实战学习等录播视频全系列的学习资料这些学习资料不仅深入浅出而且非常实用让大家系统而高效地掌握AI大模型的各个知识点。这份完整版的大模型 AI 学习资料已经上传CSDN朋友们如果需要可以微信扫描下方CSDN官方认证二维码免费领取【保证100%免费】AI大模型系统学习路线在面对AI大模型开发领域的复杂与深入精准学习显得尤为重要。一份系统的技术路线图不仅能够帮助开发者清晰地了解从入门到精通所需掌握的知识点还能提供一条高效、有序的学习路径。但知道是一回事做又是另一回事初学者最常遇到的问题主要是理论知识缺乏、资源和工具的限制、模型理解和调试的复杂性在这基础上找到高质量的学习资源不浪费时间、不走弯路又是重中之重。AI大模型入门到实战的视频教程项目包看视频学习是一种高效、直观、灵活且富有吸引力的学习方式可以更直观地展示过程能有效提升学习兴趣和理解力是现在获取知识的重要途径光学理论是没用的要学会跟着一起敲要动手实操才能将自己的所学运用到实际当中去这时候可以搞点实战案例来学习。海量AI大模型必读的经典书籍PDF阅读AI大模型经典书籍可以帮助读者提高技术水平开拓视野掌握核心技术提高解决问题的能力同时也可以借鉴他人的经验。对于想要深入学习AI大模型开发的读者来说阅读经典书籍是非常有必要的。600AI大模型报告实时更新这套包含640份报告的合集涵盖了AI大模型的理论研究、技术实现、行业应用等多个方面。无论您是科研人员、工程师还是对AI大模型感兴趣的爱好者这套报告合集都将为您提供宝贵的信息和启示。AI大模型面试真题答案解析我们学习AI大模型必然是想找到高薪的工作下面这些面试题都是总结当前最新、最热、最高频的面试题并且每道题都有详细的答案面试前刷完这套面试题资料小小offer不在话下这份完整版的大模型 AI 学习资料已经上传CSDN朋友们如果需要可以微信扫描下方CSDN官方认证二维码免费领取【保证100%免费】
返回列表