本教程將帶你從零開始,一步步構建一個完整的多 Agent 協作系統。每一步都有詳細的代碼示例和解釋,讓你真正理解 Agno 框架的工作原理。
第一步:創建你的第一個 Agent
讓我們從最簡單的開始 - 創建一個能回答問題的 Agent。
1.1 創建基礎文件
首先創建一個新文件 step1_simple_agent.py
:
from agno import Agent
from agno.models import Qwen# 第一步:配置模型
qwen = Qwen(model="qwen2.5-72b-instruct",api_key="your-api-key-here", # 替換為你的API密鑰base_url="https://dashscope.aliyuncs.com/compatible-mode/v1"
)# 第二步:創建一個簡單的Agent
simple_agent = Agent(name="簡單助手",model=qwen,instructions="你是一個友好的助手,能回答各種問題。"
)# 第三步:測試Agent
if __name__ == "__main__":response = simple_agent.run("你好,請介紹一下自己")print(f"Agent回復: {response.content}")
1.2 運行第一個Agent
運行這個文件:
python step1_simple_agent.py
預期輸出:
Agent回復: 你好!我是一個友好的AI助手,很高興認識你!我可以幫助你回答各種問題...
1.3 代碼解釋
- Qwen模型配置:這是我們使用的大語言模型,需要配置API密鑰和服務地址
- Agent創建:Agent是最基本的智能體,有名字、模型和指令
- run方法:這是與Agent交互的主要方式
第二步:給 Agent 添加工具
現在讓我們給 Agent 添加一些實用的工具,比如搜索功能。
2.1 安裝工具依賴
pip install duckduckgo-search
2.2 創建帶工具的Agent
創建文件 step2_agent_with_tools.py
:
from agno import Agent
from agno.models import Qwen
from agno.tools.duckduckgo import DuckDuckGoTools# 配置模型(和第一步相同)
qwen = Qwen(model="qwen2.5-72b-instruct",api_key="your-api-key-here",base_url="https://dashscope.aliyuncs.com/compatible-mode/v1"
)# 創建帶搜索工具的Agent
search_agent = Agent(name="搜索助手",model=qwen,tools=[DuckDuckGoTools()], # 添加搜索工具instructions="""你是一個專業的搜索助手。當用戶詢問最新信息時,請使用搜索工具獲取準確的信息。搜索后,請整理并總結搜索結果。"""
)# 測試搜索功能
if __name__ == "__main__":# 測試1:普通問答(不需要搜索)print("=== 測試1:普通問答 ===")response1 = search_agent.run("什么是人工智能?")print(f"回復: {response1.content}\n")# 測試2:需要搜索的問題print("=== 測試2:搜索最新信息 ===")response2 = search_agent.run("2024年最新的AI技術發展趨勢是什么?")print(f"回復: {response2.content}")
2.3 運行帶工具的Agent
python step2_agent_with_tools.py
預期輸出:
=== 測試1:普通問答 ===
回復: 人工智能(AI)是計算機科學的一個分支...=== 測試2:搜索最新信息 ===
回復: 根據我搜索到的最新信息,2024年AI技術發展的主要趨勢包括:
1. 大語言模型的持續優化...
2. 多模態AI的突破...
2.4 工具的工作原理
當Agent遇到需要最新信息的問題時,它會:
- 識別需要搜索
- 調用DuckDuckGo搜索工具
- 獲取搜索結果
- 整理并回復用戶
第三步:創建多個專業Agent
現在我們創建多個各有專長的Agent。
3.1 創建專業Agent團隊
創建文件 step3_multiple_agents.py
:
from agno import Agent
from agno.models import Qwen
from agno.tools.duckduckgo import DuckDuckGoTools# 共享的模型配置
qwen = Qwen(model="qwen2.5-72b-instruct",api_key="your-api-key-here",base_url="https://dashscope.aliyuncs.com/compatible-mode/v1"
)# Agent 1: 網絡搜索專家
web_search_agent = Agent(name="網絡搜索專家",model=qwen,tools=[DuckDuckGoTools()],instructions="""你是一個專業的網絡搜索專家。你的任務是:1. 根據用戶需求進行精準搜索2. 篩選和整理搜索結果3. 提供準確、及時的信息請始終使用搜索工具獲取最新信息。"""
)# Agent 2: 新聞分析師
news_agent = Agent(name="新聞分析師",model=qwen,tools=[DuckDuckGoTools()],instructions="""你是一個專業的新聞分析師。你的任務是:1. 搜索和收集相關新聞2. 分析新聞的重要性和影響3. 提供深入的新聞解讀4. 識別新聞趨勢和模式請用專業的新聞分析視角來回答問題。"""
)# Agent 3: 技術顧問
tech_advisor = Agent(name="技術顧問",model=qwen,instructions="""你是一個資深的技術顧問。你的專長包括:1. 軟件開發和架構設計2. 技術選型和最佳實踐3. 問題診斷和解決方案4. 技術趨勢分析請提供專業、實用的技術建議。"""
)# 測試不同的Agent
def test_agents():print("=== 測試網絡搜索專家 ===")search_result = web_search_agent.run("搜索2024年Python最新版本的特性")print(f"搜索專家: {search_result.content}\n")print("=== 測試新聞分析師 ===")news_result = news_agent.run("分析最近AI領域的重要新聞")print(f"新聞分析師: {news_result.content}\n")print("=== 測試技術顧問 ===")tech_result = tech_advisor.run("我想開發一個Web應用,應該選擇什么技術棧?")print(f"技術顧問: {tech_result.content}")if __name__ == "__main__":test_agents()
3.2 運行多Agent測試
python step3_multiple_agents.py
你會看到每個Agent都有自己的專業特色和回答風格。
第四步:組建Team進行協作
現在是最關鍵的部分 - 讓多個Agent協作完成復雜任務!
4.1 創建Agent團隊
創建文件 step4_team_collaboration.py
:
from agno import Agent, Team
from agno.models import Qwen
from agno.tools.duckduckgo import DuckDuckGoTools# 模型配置
qwen = Qwen(model="qwen2.5-72b-instruct",api_key="your-api-key-here",base_url="https://dashscope.aliyuncs.com/compatible-mode/v1"
)# 創建專業Agent(復用第三步的Agent)
web_search_agent = Agent(name="Web Search Agent",model=qwen,tools=[DuckDuckGoTools()],instructions="你是網絡搜索專家,負責搜索和收集信息。"
)news_agent = Agent(name="News Agent",model=qwen,tools=[DuckDuckGoTools()],instructions="你是新聞分析師,負責分析和解讀新聞內容。"
)# 關鍵步驟:創建Team
research_team = Team(name="Research Team",agents=[web_search_agent, news_agent], # 團隊成員instructions="""你們是一個專業的研究團隊。工作流程:1. Web Search Agent 負責搜索相關信息2. News Agent 負責分析和整理信息3. 團隊協作完成深入的研究報告請確保:- 信息準確和及時- 分析深入和專業- 報告結構清晰""",show_chain_of_thought=True # 顯示思考過程
)# 測試團隊協作
def test_team_collaboration():print("=== 團隊協作測試 ===")# 復雜任務:需要搜索+分析task = "研究2024年人工智能在醫療領域的最新應用和發展趨勢"print(f"任務: {task}\n")print("團隊開始協作...\n")# 使用Team處理復雜任務result = research_team.run(task)print("=== 團隊協作結果 ===")print(result.content)if __name__ == "__main__":test_team_collaboration()
4.2 Team協作的工作原理
當你運行這個代碼時,你會看到:
- 任務分配:Team自動將任務分配給合適的Agent
- 協作過程:Agent之間會交換信息和結果
- 結果整合:Team將各Agent的工作整合成最終結果
預期輸出示例:
=== 團隊協作測試 ===
任務: 研究2024年人工智能在醫療領域的最新應用和發展趨勢團隊開始協作...=== 團隊協作結果 ===
# 2024年人工智能在醫療領域研究報告## 最新應用
1. AI輔助診斷系統...
2. 智能藥物發現...
3. 個性化治療方案...## 發展趨勢
1. 多模態AI在醫療影像的應用...
2. 大語言模型在醫療問答的突破...
第五步:完整的實戰項目
現在讓我們基于 ago_multi_agent.py
創建一個完整的項目。
5.1 完整項目代碼
創建文件 step5_complete_project.py
(基于 ago_multi_agent.py
):
from agno import Agent, Team
from agno.models import Qwen
from agno.tools.duckduckgo import DuckDuckGoTools
from agno.tools.reasoning import ReasoningTools# 配置Qwen模型
qwen = Qwen(model="qwen2.5-72b-instruct",api_key="your-api-key-here", # 請替換為你的API密鑰base_url="https://dashscope.aliyuncs.com/compatible-mode/v1"
)# 創建Web搜索Agent
web_search_agent = Agent(name="Web Search Agent",model=qwen,tools=[DuckDuckGoTools()],instructions="""你是一個專業的網絡搜索專家。你的職責是:1. 根據研究需求進行精準的網絡搜索2. 收集相關的、可靠的信息源3. 整理和篩選搜索結果4. 為團隊提供準確的基礎信息請確保搜索的信息是最新的、權威的。"""
)# 創建新聞分析Agent
news_agent = Agent(name="News Agent",model=qwen,tools=[DuckDuckGoTools()],instructions="""你是一個資深的新聞分析師和研究員。你的職責是:1. 深入分析收集到的信息2. 識別重要趨勢和模式3. 提供專業的見解和解讀4. 撰寫結構化的研究報告請用批判性思維分析信息,提供有價值的洞察。"""
)# 創建推理研究團隊
reasoning_research_team = Team(name="Reasoning Research Team",agents=[web_search_agent, news_agent],tools=[ReasoningTools()], # 添加推理工具instructions="""你們是一個專業的推理研究團隊,專門處理復雜的研究任務。## 團隊協作流程:1. **信息收集階段**:Web Search Agent 負責搜索和收集相關信息2. **深度分析階段**:News Agent 負責分析信息,識別關鍵點3. **推理整合階段**:使用推理工具進行邏輯分析和結論推導4. **報告生成階段**:生成結構化的研究報告## 質量標準:- 信息必須準確和最新- 分析必須深入和專業- 推理必須邏輯清晰- 報告必須結構完整## 輸出格式:請按以下格式輸出研究報告:# 研究報告:[主題]## 執行摘要## 關鍵發現## 詳細分析## 趨勢預測## 結論和建議""",show_chain_of_thought=True
)# 主函數:演示完整的研究流程
def main():print("🚀 Agno 多Agent協作系統啟動")print("=" * 50)# 研究任務列表research_tasks = ["分析2024年生成式AI技術的最新發展和商業應用","研究量子計算在未來5年的發展前景和挑戰","調查可持續能源技術的最新突破和投資趨勢"]for i, task in enumerate(research_tasks, 1):print(f"\n📋 任務 {i}: {task}")print("-" * 40)try:# 使用團隊協作完成研究任務result = reasoning_research_team.run(task)print("? 研究完成!")print("📊 研究報告:")print(result.content)except Exception as e:print(f"? 任務執行失敗: {str(e)}")print("\n" + "=" * 50)# 單獨測試各個Agent
def test_individual_agents():print("🧪 測試單個Agent功能")print("=" * 30)# 測試搜索Agentprint("\n🔍 測試Web搜索Agent:")search_result = web_search_agent.run("搜索2024年AI芯片的最新發展")print(f"搜索結果: {search_result.content[:200]}...")# 測試新聞Agentprint("\n📰 測試新聞分析Agent:")news_result = news_agent.run("分析人工智能對就業市場的影響")print(f"分析結果: {news_result.content[:200]}...")# 交互式研究模式
def interactive_research():print("\n🎯 進入交互式研究模式")print("輸入 'quit' 退出")while True:user_query = input("\n請輸入你想研究的問題: ")if user_query.lower() == 'quit':print("👋 再見!")breakif user_query.strip():print("\n🔄 團隊開始研究...")try:result = reasoning_research_team.run(user_query)print("\n📋 研究結果:")print(result.content)except Exception as e:print(f"? 研究失敗: {str(e)}")if __name__ == "__main__":# 選擇運行模式print("請選擇運行模式:")print("1. 預設任務演示")print("2. 單個Agent測試")print("3. 交互式研究")choice = input("請輸入選擇 (1/2/3): ")if choice == "1":main()elif choice == "2":test_individual_agents()elif choice == "3":interactive_research()else:print("無效選擇,運行默認演示")main()
5.2 運行完整項目
python step5_complete_project.py
運行效果:
🚀 Agno 多Agent協作系統啟動
==================================================📋 任務 1: 分析2024年生成式AI技術的最新發展和商業應用
----------------------------------------
? 研究完成!
📊 研究報告:
# 研究報告:2024年生成式AI技術發展分析## 執行摘要
2024年生成式AI技術呈現爆發式增長...## 關鍵發現
1. 大語言模型能力顯著提升
2. 多模態AI成為新趨勢
3. 企業級應用快速普及
...
常見問題和解決方案
Q1: API密鑰配置問題
問題:運行時提示API密鑰錯誤
解決方案:
# 方法1:直接在代碼中配置
qwen = Qwen(model="qwen2.5-72b-instruct",api_key="sk-your-actual-api-key", # 替換為真實密鑰base_url="https://dashscope.aliyuncs.com/compatible-mode/v1"
)# 方法2:使用環境變量(推薦)
import os
qwen = Qwen(model="qwen2.5-72b-instruct",api_key=os.getenv("QWEN_API_KEY"),base_url="https://dashscope.aliyuncs.com/compatible-mode/v1"
)
Q2: 工具導入失敗
問題:ImportError: No module named 'agno.tools.duckduckgo'
解決方案:
# 安裝必要的依賴
pip install agno
pip install duckduckgo-search
Q3: Team協作沒有效果
問題:Team運行時只有一個Agent在工作
解決方案:
# 確保Team的instructions明確指定協作流程
team = Team(name="Research Team",agents=[agent1, agent2],instructions="""明確的協作指令:1. Agent1負責搜索信息2. Agent2負責分析信息3. 兩個Agent必須協作完成任務""",show_chain_of_thought=True # 顯示協作過程
)
Q4: 響應速度慢
問題:Agent響應時間過長
解決方案:
# 優化模型配置
qwen = Qwen(model="qwen2.5-72b-instruct",api_key="your-api-key",base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",timeout=30, # 設置超時時間max_tokens=1000 # 限制輸出長度
)
進階技巧和最佳實踐
1. Agent角色設計
# ? 好的Agent設計
expert_agent = Agent(name="數據分析專家",model=qwen,instructions="""你是一個資深的數據分析專家,具有10年以上的行業經驗。你的專長:- 統計分析和數據挖掘- 商業智能和報表分析- 預測建模和趨勢分析工作風格:- 嚴謹、客觀、基于數據- 提供可操作的建議- 用圖表和數字說話"""
)# ? 不好的Agent設計
bad_agent = Agent(name="助手",model=qwen,instructions="你是一個助手" # 太模糊
)
2. Team協作優化
# 高效的Team設計
optimized_team = Team(name="產品研發團隊",agents=[market_researcher, tech_analyst, product_manager],instructions="""## 協作流程(嚴格按順序執行):### 第一階段:市場調研- Market Researcher: 調研市場需求和競品- 輸出:市場調研報告### 第二階段:技術分析- Tech Analyst: 基于市場報告分析技術可行性- 輸出:技術方案建議### 第三階段:產品規劃- Product Manager: 整合前兩階段結果,制定產品規劃- 輸出:完整的產品規劃文檔## 質量要求:- 每個階段必須有明確的輸出- 后續階段必須基于前面的結果- 最終輸出必須包含所有階段的關鍵信息"""
)
3. 錯誤處理和重試機制
def robust_agent_call(agent, query, max_retries=3):"""帶重試機制的Agent調用"""for attempt in range(max_retries):try:result = agent.run(query)if result and result.content:return resultexcept Exception as e:print(f"嘗試 {attempt + 1} 失敗: {e}")if attempt == max_retries - 1:raisereturn None# 使用示例
try:result = robust_agent_call(my_agent, "復雜的查詢")print(result.content)
except Exception as e:print(f"所有嘗試都失敗了: {e}")
總結
通過這個手把手的教程,你已經學會了:
? 你現在掌握的技能:
- 基礎Agent創建 - 從零開始創建智能Agent
- 工具集成 - 給Agent添加搜索等實用工具
- 多Agent設計 - 創建專業化的Agent團隊
- Team協作 - 實現真正的多Agent協作
- 完整項目 - 構建生產級的多Agent系統
🚀 下一步建議:
-
實踐項目:
- 創建自己的專業Agent(如代碼審查、文檔生成等)
- 構建特定領域的研究團隊
- 開發自動化工作流程
-
深入學習:
- 探索更多工具集成
- 學習自定義工具開發
- 研究高級協作模式
-
生產部署:
- 添加日志和監控
- 實現API接口
- 優化性能和成本
💡 關鍵要點回顧:
- Agent = 模型 + 指令 + 工具
- Team = 多個Agent + 協作指令
- 成功的關鍵在于清晰的角色定義和協作流程
- 從簡單開始,逐步增加復雜性
現在你已經具備了使用Agno框架構建強大多Agent系統的能力!開始創建你自己的AI助手團隊吧! 🎉
多 Agent 協作的優勢
- 任務分工明確:每個 Agent 專注于特定領域,提高專業性
- 并行處理能力:多個 Agent 可以同時處理不同任務
- 容錯性強:單個 Agent 失敗不會影響整個系統
- 可擴展性好:可以輕松添加新的 Agent 來擴展功能
- 協作智能:通過 Team 機制實現智能體間的信息共享和協調
適用場景
- 復雜研究任務(如市場分析、技術調研)
- 多源信息整合(如新聞聚合、數據分析)
- 內容生成與處理(如文檔生成、翻譯)
- 決策支持系統
- 自動化工作流程
環境配置
安裝依賴
# 安裝 Agno 框架
pip install agno# 安裝相關依賴
pip install duckduckgo-search
API 密鑰配置
import os# 配置通義千問 API 密鑰
os.environ["DASHSCOPE_API_KEY"] = "your-api-key-here"# 其他可能需要的 API 密鑰
# os.environ["OPENAI_API_KEY"] = "your-openai-key"
# os.environ["ANTHROPIC_API_KEY"] = "your-anthropic-key"
基礎設置
確保你的環境支持:
- Python 3.8+
- 穩定的網絡連接(用于 API 調用)
- 足夠的內存和計算資源
核心概念
Agent(智能體)
Agent 是 Agno 框架中的基本執行單元,每個 Agent 都有:
- 名稱和角色:定義 Agent 的身份和職責
- 模型:使用的 AI 模型(如 Qwen、GPT 等)
- 工具:Agent 可以使用的外部工具
- 指令:指導 Agent 行為的規則和要求
from agno.agent import Agent
from agno.models.qwen import Qwen
from agno.tools.duckduckgo import DuckDuckGoToolsagent = Agent(name="示例 Agent",role="處理特定任務",model=qwen_model,tools=[DuckDuckGoTools()],instructions="具體的行為指令"
)
Team(團隊)
Team 是多個 Agent 的協作容器,負責:
- 協調 Agent 工作:分配任務和管理執行流程
- 信息共享:在 Agent 之間傳遞信息
- 結果整合:匯總各 Agent 的輸出
- 質量控制:確保最終結果符合要求
from agno.team.team import Teamteam = Team(name="協作團隊",mode="coordinate", # 協作模式members=[agent1, agent2],instructions=["團隊協作指令"]
)
Tools(工具)
工具為 Agent 提供外部能力:
- DuckDuckGoTools:網絡搜索功能
- ReasoningTools:推理和分析工具
- 自定義工具:根據需求開發的專用工具
Model(模型)
模型是 Agent 的"大腦",支持多種 AI 模型:
- Qwen:通義千問模型
- OpenAI GPT:OpenAI 的 GPT 系列
- Claude:Anthropic 的 Claude 模型
代碼詳解
基于 ago_multi_agent.py
的完整代碼分析:
1. 導入必要模塊
import os
from agno.agent import Agent
from agno.models.qwen import Qwen
from agno.team.team import Team
from agno.tools.duckduckgo import DuckDuckGoTools
from agno.tools.reasoning import ReasoningTools
2. 配置模型
# 配置 API 密鑰
os.environ["DASHSCOPE_API_KEY"] = "your-api-key"# 創建 Qwen 模型實例
qwen = Qwen(id="qwen-flash", # 模型標識符base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",top_p=0.7, # 控制生成多樣性temperature=0.95, # 控制隨機性
)
參數說明:
id
:模型標識符,選擇具體的模型版本base_url
:API 服務地址top_p
:核采樣參數,值越小生成越確定temperature
:溫度參數,值越高生成越隨機
3. 創建專門化 Agent
Web 搜索 Agent
web_agent = Agent(name="Web Search Agent",role="處理網絡搜索請求和一般研究",model=qwen,tools=[DuckDuckGoTools()],instructions="始終包含來源",add_datetime_to_instructions=True,debug_mode=True,
)
新聞 Agent
news_agent = Agent(name="News Agent",role="處理新聞請求和時事分析",model=qwen,tools=[DuckDuckGoTools(search=True, news=True)],instructions=["使用表格顯示新聞信息和發現。","明確說明來源和發布日期。","關注提供當前和相關的新聞見解。",],add_datetime_to_instructions=True,debug_mode=True,
)
配置參數詳解:
name
:Agent 的名稱標識role
:Agent 的角色描述model
:使用的 AI 模型tools
:可用工具列表instructions
:行為指令(可以是字符串或列表)add_datetime_to_instructions
:是否添加時間信息debug_mode
:是否啟用調試模式
4. 創建協作團隊
reasoning_research_team = Team(name="Reasoning Research Team",mode="coordinate", # 協作模式model=qwen,members=[web_agent, news_agent],tools=[ReasoningTools(add_instructions=True)],instructions=["協作提供全面的研究和新聞見解","考慮當前事件和熱門話題","使用表格和圖表清晰專業地展示數據","以結構化、易于遵循的格式呈現發現","僅輸出最終的綜合分析,而不是單個代理響應",],markdown=True,show_members_responses=True,enable_agentic_context=True,add_datetime_to_instructions=True,success_criteria="團隊已提供完整的研究分析,包括數據、可視化、趨勢評估和基于當前信息和可靠來源的可操作見解。",debug_mode=True,
)
Team 參數詳解:
mode
:協作模式(coordinate、sequential、parallel 等)members
:團隊成員 Agent 列表tools
:團隊級別的工具markdown
:是否使用 Markdown 格式輸出show_members_responses
:是否顯示各成員的響應enable_agentic_context
:是否啟用智能體上下文success_criteria
:成功標準定義
5. 執行任務
if __name__ == "__main__":reasoning_research_team.print_response("""使用中文輸出,研究并比較可再生能源的最新發展:1. 獲取可再生能源創新的最新消息2. 分析可再生能源領域的最新發展3. 比較不同的可再生能源技術4. 推薦值得關注的未來趨勢""",stream=True,show_full_reasoning=True,stream_intermediate_steps=True,)
執行參數說明:
stream
:是否流式輸出結果show_full_reasoning
:是否顯示完整推理過程stream_intermediate_steps
:是否流式顯示中間步驟
實戰示例
示例 1:創建單個 Agent
from agno.agent import Agent
from agno.models.qwen import Qwen
from agno.tools.duckduckgo import DuckDuckGoTools# 創建模型
model = Qwen(id="qwen-flash")# 創建專門的研究 Agent
research_agent = Agent(name="Research Assistant",role="專業研究助手",model=model,tools=[DuckDuckGoTools()],instructions=["提供準確、詳細的研究信息","引用可靠來源","以結構化方式組織信息"]
)# 使用 Agent
response = research_agent.run("研究人工智能在醫療領域的應用")
print(response.content)
示例 2:組建 Agent 團隊
# 創建多個專門化 Agent
data_agent = Agent(name="Data Analyst",role="數據分析專家",model=model,tools=[DuckDuckGoTools()],instructions="專注于數據收集和統計分析"
)report_agent = Agent(name="Report Writer",role="報告撰寫專家",model=model,instructions="將分析結果整理成專業報告"
)# 創建協作團隊
analysis_team = Team(name="Analysis Team",mode="sequential", # 順序執行模式members=[data_agent, report_agent],instructions=["首先收集和分析數據","然后生成綜合報告","確保報告專業且易懂"]
)# 執行團隊任務
result = analysis_team.run("分析2024年電商市場趨勢")
示例 3:配置不同協作模式
# 并行模式:多個 Agent 同時工作
parallel_team = Team(name="Parallel Research Team",mode="parallel",members=[web_agent, news_agent],instructions="同時進行網絡搜索和新聞分析"
)# 協調模式:智能分配任務
coordinate_team = Team(name="Coordinate Team",mode="coordinate",members=[web_agent, news_agent],instructions="根據任務需求智能分配工作"
)
最佳實踐
Agent 設計原則
-
單一職責原則
# 好的設計:專門化 Agent translation_agent = Agent(name="Translator",role="專業翻譯",instructions="只負責文本翻譯任務" )# 避免:功能過于復雜的 Agent # complex_agent = Agent( # name="Everything Agent", # role="處理所有任務" # 不推薦 # )
-
清晰的角色定義
agent = Agent(name="Market Analyst",role="專注于市場趨勢分析和預測",instructions=["分析市場數據和趨勢","提供基于數據的預測","使用圖表和可視化展示結果"] )
-
合適的工具配置
# 根據 Agent 職責配置相應工具 search_agent = Agent(name="Search Specialist",tools=[DuckDuckGoTools(search=True, news=True)],instructions="專門負責信息搜索和收集" )
Team 協作模式選擇
-
Sequential(順序模式)
- 適用于:有明確先后順序的任務
- 示例:數據收集 → 分析 → 報告生成
-
Parallel(并行模式)
- 適用于:可以同時進行的獨立任務
- 示例:多源信息收集、多角度分析
-
Coordinate(協調模式)
- 適用于:需要智能任務分配的復雜場景
- 示例:綜合研究、多維度分析
錯誤處理
try:result = team.run(task)if result.success:print(f"任務完成:{result.content}")else:print(f"任務失敗:{result.error}")
except Exception as e:print(f"執行錯誤:{e}")# 實施備用方案
性能優化
-
合理設置模型參數
# 平衡性能和質量 model = Qwen(temperature=0.7, # 適中的隨機性top_p=0.9, # 適中的多樣性 )
-
啟用調試模式進行開發
agent = Agent(debug_mode=True, # 開發時啟用# debug_mode=False, # 生產時關閉 )
-
合理使用流式輸出
# 對于長時間任務,使用流式輸出提升用戶體驗 team.print_response(task,stream=True,stream_intermediate_steps=True )
擴展應用
自定義工具
from agno.tools.base import Toolclass CustomAnalysisTool(Tool):def __init__(self):super().__init__(name="Custom Analysis")def analyze_data(self, data):# 自定義分析邏輯return f"分析結果:{data}"# 在 Agent 中使用自定義工具
custom_agent = Agent(name="Custom Agent",tools=[CustomAnalysisTool()],instructions="使用自定義工具進行分析"
)
復雜任務分解
# 將復雜任務分解為多個子任務
def complex_research_workflow(topic):# 第一階段:信息收集collection_team = Team(name="Information Collection",members=[web_agent, news_agent],mode="parallel")raw_data = collection_team.run(f"收集關于{topic}的信息")# 第二階段:數據分析analysis_agent = Agent(name="Data Analyzer",instructions="分析收集到的數據")analysis_result = analysis_agent.run(f"分析數據:{raw_data}")# 第三階段:報告生成report_agent = Agent(name="Report Generator",instructions="生成最終報告")final_report = report_agent.run(f"生成報告:{analysis_result}")return final_report
實際項目應用
新聞聚合系統
news_system = Team(name="News Aggregation System",members=[Agent(name="News Collector", tools=[DuckDuckGoTools(news=True)]),Agent(name="Content Analyzer", instructions="分析新聞內容"),Agent(name="Summary Generator", instructions="生成新聞摘要")],mode="sequential",instructions="收集、分析并總結最新新聞"
)
市場研究系統
market_research_system = Team(name="Market Research System",members=[Agent(name="Data Collector", tools=[DuckDuckGoTools()]),Agent(name="Trend Analyzer", instructions="分析市場趨勢"),Agent(name="Report Writer", instructions="撰寫研究報告")],mode="coordinate",instructions="進行全面的市場研究分析"
)
總結
Agno 多 Agent 協作框架提供了一個強大而靈活的平臺,用于構建智能化的多智能體系統。通過合理的 Agent 設計、Team 協作和工具配置,可以實現復雜任務的自動化處理。
關鍵要點:
- 遵循單一職責原則設計 Agent
- 根據任務特點選擇合適的協作模式
- 合理配置模型參數和工具
- 實施適當的錯誤處理和性能優化
- 根據實際需求擴展和定制功能
通過本教程的學習和實踐,你應該能夠熟練使用 Agno 框架構建自己的多 Agent 協作系統。