尧图网站设计 尧图网站设计YAOTU DESIGN
ARTICLE DETAIL

资讯详情

深耕网站设计与一线实操的经验洞察。

agno 团队依赖注入实战指南:Team Dependencies 的三种注入方式与源码级原理解析

agno 团队依赖注入实战指南:Team Dependencies 的三种注入方式与源码级原理解析 agno 团队依赖注入实战指南Team Dependencies 的三种注入方式与源码级原理解析【免费下载链接】agnoBuild, run, and manage agent platforms.项目地址: https://gitcode.com/GitHub_Trending/ag/agno导读在 agno 的团队Team编程模型中dependencies依赖注入允许开发者把用户画像、业务指标、当前上下文等运行时数据以结构化方式注入到团队指令、团队成员工具乃至成员智能体的上下文中从而实现真正的个性化与数据驱动协同。本文以 cookbook/03_teams/17_dependencies/README.md 为主线结合仓库内三个完整示例与 agno 团队核心源码系统讲解依赖注入的三种模式In Context、In Tools、To Members及其底层解析机制读完即可在你的多智能体团队中落地使用。一、理解 Team Dependencies 是什么1.1 解决的问题多智能体团队在真实业务中通常需要两类运行时信息静态但变化的数据如用户画像偏好、职级、所在地、业务指标团队绩效、营收动态上下文如当前时间、时区、星期几。如果把这些信息写死在指令instructions里团队无法复用如果让每个成员各自去查又会产生重复与不一致。agno 的dependencies机制正是为此设计它是一组Dict[str, Any]形式的键值对值可以是普通对象也可以是可调用函数callable——后者会在每次运行时被解析求值得到最新的结果后再注入。1.2 源码中的定义在 libs/agno/agno/team/team.py#L218-L222 中Team 类定义了依赖注入相关的两个核心字段# --- User provided dependencies --- # User provided dependencies dependencies: Optional[Dict[str, Any]] None # If True, add the dependencies to the user prompt add_dependencies_to_context: bool Falsedependencies用户提供的依赖字典可在构造 Team 时声明也可在run()/print_response()时传入后者会覆盖前者add_dependencies_to_context布尔开关置为True时依赖内容会被解析后写入用户提示词user prompt供模型直接看到。此外 libs/agno/agno/run/base.py#L17-L25 中的RunContext也持有dependencies: Optional[Dict[str, Any]]字段它是依赖在单次运行run生命周期内流转的载体——这为在工具中读取依赖提供了基础。二、环境前置条件按 cookbook/03_teams/17_dependencies/README.md 的说明运行本目录示例前需要加载环境变量例如OPENAI_API_KEY仓库示例采用 direnv 方案在项目根目录执行direnv allow使用推荐解释器使用.venvs/demo/bin/python运行 cookbook 示例关注额外服务依赖部分示例需要 PostgreSQL、LanceDB、Infinity 等外部服务具体以各示例文件 docstring 中的说明为准。本目录的三个示例仅依赖 OpenAI API无额外服务要求。三个示例文件及主题对应关系如下文件主题dependencies_in_context.py在指令与成员上下文中使用依赖dependencies_in_tools.py运行时传入依赖并在团队工具内读取dependencies_to_members.py运行时传入依赖并传播给成员智能体三、模式一In Context —— 在指令与上下文中使用依赖3.1 示例目标dependencies_in_context.py 演示的是在 Team 构造阶段声明依赖并把依赖以模板变量的形式写进团队指令让模型在生成回复时自然引用用户画像与当前上下文实现个性化推荐。3.2 关键实现拆解首先定义两个依赖提供函数这是整个目录示例共用的数据源模式def get_user_profile(user_id: str john_doe) - dict: 获取用户画像信息可在回复中引用 profiles { john_doe: { name: John Doe, preferences: { communication_style: professional, topics_of_interest: [AI/ML, Software Engineering, Finance], experience_level: senior, }, location: San Francisco, CA, role: Senior Software Engineer, } } return profiles.get(user_id, {name: Unknown User}) def get_current_context() - dict: 获取当前上下文信息时间、时区、星期等 return { current_time: datetime.now().strftime(%Y-%m-%d %H:%M:%S), timezone: PST, day_of_week: datetime.now().strftime(%A), }随后创建两个成员智能体ProfileAnalyst 负责画像分析、ContextAnalyst 负责时序分析再创建团队并声明依赖team Team( namePersonalizationTeam, modelOpenAIResponses(idgpt-5.2), members[profile_agent, context_agent], dependencies{ user_profile: get_user_profile, current_context: get_current_context, }, add_dependencies_to_contextTrue, instructions[ You are a personalization team that provides personalized recommendations based on the users profile and context., Here is the user profile: {user_profile}, Here is the current context: {current_context}, ], markdownTrue, )3.3 两个关键设计点依赖值传入的是函数而非结果dependencies字典的值是get_user_profile、get_current_context这两个函数对象。在运行开始时 agno 会调用它们得到最新结果——这意味着时间、上下文类数据永远是当下的而不是构造时刻的陈旧快照。{user_profile}与{current_context}的模板替换指令中直接引用依赖的键名。当add_dependencies_to_contextTrue时解析后的依赖内容会进入用户提示词与{user_profile}等占位符协同确保模型拿到的是已求值的真实数据。执行cd cookbook/03_teams/17_dependencies .venvs/demo/bin/python dependencies_in_context.py团队便会基于约翰·杜的画像资深软件工程师、关注 AI/ML 与金融、偏好专业沟通风格结合当前时间给出今日优先事项的个性化摘要。四、模式二In Tools —— 在团队工具中读取依赖4.1 与模式一的本质区别dependencies_in_tools.py 的核心差异在于依赖不再是给模型看的提示词而是运行时传入、供团队工具函数通过RunContext编程式访问的数据源。这适用于工具需要结构化数据做计算而不是让模型读文本的场景例如绩效分析工具需要读取team_metrics字典做分数判定。4.2 在工具签名中声明 RunContext工具函数的第二个参数是 agno 的RunContextfrom agno.run import RunContext def analyze_team_performance(team_id: str, run_context: RunContext) - str: 使用运行上下文中可用的依赖分析团队绩效 dependencies run_context.dependencies if not dependencies: return No data sources available for analysis. print(f-- Team tool received data sources: {list(dependencies.keys())}) results [f TEAM PERFORMANCE ANALYSIS FOR {team_id.upper()} ] if team_metrics in dependencies: metrics_data dependencies[team_metrics] results.append(fTeam Metrics: {metrics_data}) score metrics_data.get(productivity_score) if score is not None: if score 8: results.append(fPerformance Analysis: Excellent performance with {score}/10 productivity score) elif score 6: results.append(fPerformance Analysis: Good performance with {score}/10 productivity score) else: results.append(fPerformance Analysis: Needs improvement with {score}/10 productivity score) if current_context in dependencies: context_data dependencies[current_context] results.append(fCurrent Context: {context_data}) results.append( fTime-based Analysis: Team analysis performed on {context_data[day_of_week]} at {context_data[current_time]} ) print(f-- Team tool returned results: {results}) return \n\n.join(results)要点只要工具函数签名中带有run_context: RunContext参数agno 就会在调用时自动注入当前运行的RunContext工具内通过run_context.dependencies即可按键读取依赖。4.3 运行时传入依赖示例中团队本身不声明依赖而是在run()时通过dependencies参数临时注入response performance_team.run( inputPlease analyze the engineering_team performance and provide comprehensive insights about their productivity and recommendations for improvement., dependencies{ team_metrics: { team_name: Engineering Team Alpha, team_size: 8, productivity_score: 7.5, sprint_velocity: 85, bug_resolution_rate: 92, code_review_turnaround: 2.3 days, areas: [Backend Development, Frontend Development, DevOps], }, current_context: get_current_context, }, session_idtest_team_tool_dependencies, )这里展示了依赖注入的灵活形态值既可以是普通数据结构team_metrics字典也可以是函数get_current_context两者在运行开始阶段都会被统一处理函数被求值普通对象原样保留随后工具通过RunContext读取。示例同时演示了session_id参数的使用——依赖与具体会话绑定便于与 cookbook/03_teams/07_session 中的会话管理配合。五、模式三To Members —— 运行时依赖传播给成员5.1 场景与示例目标dependencies_to_members.py 演示了最贴近实际协作的场景Team 构造时不声明任何依赖在print_response()运行时传入依赖agno 自动将依赖传播给团队成员智能体members使 ProfileAnalyst、ContextAnalyst 在各自的子上下文中也能使用同一份数据。5.2 关键实现team Team( namePersonalizationTeam, modelOpenAIResponses(idgpt-5.2), members[profile_agent, context_agent], markdownTrue, show_members_responsesTrue, ) team.print_response( Please provide me with a personalized summary of todays priorities based on my profile and interests., dependencies{ user_profile: get_user_profile, current_context: get_current_context, }, add_dependencies_to_contextTrue, )与模式一的对比对比维度In Context模式一To Members模式三依赖声明位置Team 构造时运行调用时print_response/run是否配置成员有成员依赖进团队指令有成员依赖传播到成员输出方式run()后打印response.contentprint_response()直接打印且show_members_responsesTrue可见成员中间响应复用性团队级依赖构造即绑定每次运行可传不同依赖同一团队服务多类请求模式三尤其适合一个团队、多次调用、每次携带不同参数的服务化场景——例如同一推荐团队根据每次请求传入的不同user_id画像产出不同结果。六、源码级原理依赖是如何被解析与注入的6.1 依赖解析函数依赖的核心解析逻辑位于 libs/agno/agno/team/_run.py#L5334-L5398同步与异步版本分别名为_resolve_run_dependencies与_aresolve_run_dependencies。其工作流程可以概括为类型校验若run_context.dependencies不是dict直接告警返回遍历键值对对每个依赖项判断值是否可调用callable非 callable 原样保留普通数据结构直接写入run_context.dependencies[key]不做任何转换callable 按签名注入参数并求值使用inspect.signature检查函数签名若函数声明了agent、team或run_context形参则分别注入当前 Team 对象与RunContext然后执行函数得到最终值并写回依赖字典异常兜底解析失败仅记录告警日志不会中断整个团队运行。关键代码同步版节选for key, value in run_context.dependencies.items(): if not callable(value): run_context.dependencies[key] value continue try: sig signature(value) kwargs: Dict[str, Any] {} if agent in sig.parameters: kwargs[agent] team if team in sig.parameters: kwargs[team] team if run_context in sig.parameters: kwargs[run_context] run_context resolved_value value(**kwargs) if kwargs else value() run_context.dependencies[key] resolved_value except Exception as e: log_warning(fFailed to resolve dependencies for {key}: {str(e)})异步版本_aresolve_run_dependencies额外支持协程依赖若函数返回coroutine会await后写入——这意味着依赖提供函数也支持 async 写法例如从数据库或远程 API 异步拉取数据。6.2 解析时机从 libs/agno/agno/team/_run.py#L228-L230 与 libs/agno/agno/team/_run.py#L2050-L2052 可以看到依赖在会话session建立、状态从数据库加载之后被解析且在重试循环retry loop前完成一次解析。这一顺序保证了依赖求值时可利用会话中已恢复的状态同一轮运行内依赖只解析一次避免重试时重复执行副作用函数。6.3 传播机制依赖随RunContext在团队的任务分发成员 agent 的 run中流转团队级run()接收dependencies与add_dependencies_to_context参数后写入运行选项run options与RunContext成员在各自的子运行中继承同一份上下文因此To Members模式下成员无需感知依赖来源即可直接使用。若成员本身是远程智能体libs/agno/agno/team/remote.py 中同样存在add_dependencies_to_context与dependencies的参数透传入口说明该机制对远程成员同样适用可从源码结构推断。七、三种模式选型建议场景推荐模式原因依赖相对固定如全局用户画像In Context构造时声明指令模板直接引用配置最集中工具需要结构化数据做逻辑计算In Tools通过RunContext编程式访问数据类型安全、可做条件分支同一团队服务多变请求依赖随请求变化To Members运行时可传参依赖自动传播给所有成员依赖来自数据库/远程 API异步获取任意模式 async 函数_aresolve_run_dependencies支持协程求值实践注意点不要传未求值的重计算函数依赖会在每次运行时被调用若提供函数本身昂贵如查库可结合缓存或仅在需要时使用 callable键名与指令占位符保持一致指令中的{user_profile}必须与依赖字典键user_profile对应否则模板无法替换add_dependencies_to_context的语义它控制依赖是否进入用户提示词在 Tools 模式下工具通过RunContext取数不依赖该开关但在 In Context 模式下需要置True错误静默依赖解析失败只会记录告警团队仍会运行请在关键依赖场景中自行校验run_context.dependencies的完整性示例工具中if not dependencies:的兜底写法值得借鉴。结语agno 的 Team Dependencies 为多智能体团队提供了一套统一、灵活的运行时数据注入方案从构造期声明、指令模板引用到运行时传参、工具内编程式读取再到向成员智能体自动传播配合可调用依赖的自动求值与异步支持覆盖了个性化推荐、绩效分析、动态上下文感知等典型团队协作场景。深入阅读 libs/agno/agno/team/_run.py 的依赖解析实现能帮助你在设计复杂多智能体系统时准确预判数据流与执行时机把依赖注入从会用提升到用对。【免费下载链接】agnoBuild, run, and manage agent platforms.项目地址: https://gitcode.com/GitHub_Trending/ag/agno创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表