譯者 | 布加迪
審校 | 重樓
Meta的Llama 4 系列模型目前正主導不斷發展的AI世界。這些模型憑借原生的多模態功能,正在徹底改變我們構建智能系統的方式。當Llama 4與AutoGen結合使用時,它將充分發掘構建動態、響應迅速且強大的AI智能體的潛力。如果充分利用Llama 4與AutoGen之間的集成,開發者可以創建能夠高效推理、協作和適應的創新型AI智能體。我們在本文中將學習如何使用 Llama 4和AutoGen為特定應用場景構建AI智能體。
為什么我們應該考慮使用Llama 4?
Llama 4系列模型(包括 Scout和Maverick變體)是開源AI技術的重大飛躍。這些模型有以下幾大優勢:
- 多模態智能:Llama 4具有原生多模態功能,可以將不同類型的輸入集成到統一的架構中。因而可以跨不同類型的媒體進行更復雜的推理。
- 大上下文長度:它支持高達1000萬個 token,超越了Llama 3的12.8萬個限制。它能夠處理超長上下文,這使得支持高級應用成為可能,比如全面的多文檔分析、基于用戶歷史記錄的廣泛個性化以及大型代碼庫的導航。
- 高效性能:Llama 4 采用混合專家架構,針對處理的每個token僅激活模型的特定部分。這種方法大大提高了模型的效率。比如說,Llama 4 Maverick在運行過程中僅使用其總共 4000 億個參數中的170億個,這使得它在單單一個H100 DGX主機上就能夠運行。
- 卓越的性能和功能:基準測試表明,Llama 4 Maverick在編程、推理、多語言能力和圖像理解方面均優于GPT-4o 和 Gemini 2.0等同類模型。
- 開源、易于訪問:Meta現在允許人們下載使用其模型。這鼓勵開放式創新,使開發者能夠跨各種應用程序和平臺定制和部署該技術。
Llama 4 基準測試性能
為了了解該模型到底有多好,下面比較Llama 4 與其他頭部模型在各項標準基準測試中的表現。
圖1. Llama 4 基準測試性能
使用Llama 4構建AI智能體
我在本節中將逐步介紹使用Llama 4和AutoGen構建針對特定任務的智能體的過程。我們將創建一個多智能體系統,該系統可分析客戶的工作需求,根據自由職業者的經驗和詳細信息尋找適合某項工作的自由職業者,然后生成自定義的工作提案供用戶發送。
步驟 0:設置環境
在構建智能體之前,我們先介紹必要的先決條件并設置環境。
先決條件
- 熟悉終端或命令提示。
- 能夠在系統上設置環境變量。
- 能夠使用終端或命令提示來運行程序。
- 必須安裝 Python:https://www.python.org/downloads/
- 對AutoGen有一番基本的了解:https://docs.ag2.ai/latest/
訪問API
我們將在此處使用Together API來訪問Llama 4模型。在Together AI上創建一個帳戶,并訪問該頁面以創建密鑰:https://api.together.xyz/。
步驟 1:設置用于指導AI智能體的庫和工具
首先,我們將在此處導入所有必要的庫和工具。
import os
import autogen
from IPython.display import display, Markdown
步驟 2:調用API
若要使用Llama 4,我們必須加載Together API。下面的代碼塊將幫助我們加載API,并根據環境來配置它們。
with open("together_ai_api.txt") as file:
LLAMA_API_KEY = file.read().strip()
os.environ["LLAMA_API_KEY"] = LLAMA_API_KEY
步驟 3:創建智能體并定義任務
現在不妨創建所需的智能體并定義它們的任務,即它們要執行的操作。
1.客戶輸入智能體
客戶輸入智能體充當人類用戶和智能體系統之間的主要接口。它從用戶那里收集項目的詳細信息,比如客戶需求、時間表和預算,并將它們傳遞給范圍架構師。它還會傳遞后續問題和答案,并在最終提案被接受時發出終止信號。
預期輸出:
- 清晰地傳達用戶的項目描述和自由職業者的個人資料(技能、經驗和預計時間)。
- 一旦提交了令人滿意的提案,就結束會話,或者用戶明確結束會話。
# Agent 1: Handles Human Input for Client Requirements
client_agent = autogen.UserProxyAgent(
name="Client_Input_Agent",
human_input_mode="ALWAYS", # asks the human for input
max_consecutive_auto_reply=1, # Only reply once
is_termination_msg=lambda x: x.get("content", "").rstrip().endswith("TERMINATE"),
system_message="""You are the primary point of contact for the user.
Your first task is to provide the initial project details received from the human user (client requirements, product details, timeline, budget) to the group chat.
After the Scope Architect asks questions, relay the human user's answers about their skills, experience, tools, and time estimate back to the chat.
Reply TERMINATE when the final proposal is generated and satisfactory, or if the user wishes to stop. Otherwise, relay the user's input.
""",
)
2. 范圍架構師智能體
范圍架構師智能體負責從客戶輸入智能體那里獲取初始項目詳細信息。之后,它會提出具體問題,以收集自由職業者的技能、工具、過去的項目經驗以及完成工作的預計時間。它本身不會生成提案,但確保在提交給下一個智能體之前收集所有必要的上下文。
預期輸出:
- 結構清晰的摘要結合客戶的項目需求和自由職業者的能力。
- 一旦收集并匯總了所有必需數據,就觸發“費率推薦智能體”。
# Agent 2: Gathers User's Profile and Estimates
scope_architect_agent = autogen.AssistantAgent(
name="Scope_Architect",
llm_cnotallow=llm_config,
human_input_mode="ALWAYS",
max_consecutive_auto_reply=1, # Only reply once
is_termination_msg=lambda x: x.get("content", "").rstrip().endswith("TERMINATE"),
system_message="""You are a Scope Architect. Your role is to understand the project requirements provided initially and then gather necessary details *from the Client_Input_Agent (representing the user/freelancer)*.
1. Wait for the initial project details from Client_Input_Agent.
2. Once you have the project details, formulate clear questions for the Client_Input_Agent to ask the human user about their:
- Relevant past work/projects and collaborations.
- Key skills and tools applicable to this project.
- Their estimated time to complete the defined work.
3. Do NOT proceed to proposal generation. Wait for the Client_Input_Agent to provide the user's answers.
4. Once you have both the client requirements AND the user's details (skills, experience, time estimate), summarize this information clearly for the Rate Recommender. Signal that you have all necessary info.
""",
)
3.費率推薦智能體
費率推薦智能體使用收集到的信息生成詳細的項目提案。它等待范圍架構師智能體提供的完整摘要,然后分析項目范圍和自由職業者的詳細信息,以生成一份專業的提案文檔。這份文檔包含自定義簡介、時間表、多個定價層級以及明確的行動號召。
預期輸出:
- 格式專業的項目提案文檔,附有范圍、定價和后續步驟。
- 最終輸出已準備好交付給客戶審批或進一步討論。
rate_recommender_agent = autogen.AssistantAgent(
name="Rate_Recommender",
llm_cnotallow=llm_config,
max_consecutive_auto_reply=1, # Only reply once
system_message=f"""
You are a Proposal Generator and Rate Recommender. Your task is to create a structured project proposal.
Wait until the Scope_Architect shares a summary containing BOTH the client's project requirements AND the user's profile (skills, experience, time estimate, past work if available).
Analyze all received data: client needs, user expertise, estimated time, and any prior rate insights.
Generate a well-structured proposal addressed to the client, including the following sections:
Custom Introduction: Professionally introduce the user's services and reference the client's company and project.
Project Scope & Timeline: Clearly outline the deliverables with estimated timelines based on user input.
Suggested Pricing Tiers: Provide 1–3 pricing options (hourly, fixed fee, retainer) with justifications based on scope, user experience, or complexity.
Next Steps (CTA): Recommend scheduling a brief kickoff call to finalize and clarify details.
Present ONLY the final formatted proposal. Do not include additional commentary unless clarification is requested.""",)
4. 用戶代理智能體
該智能體充當啟動交互的入口點或助手。雖然它在該流程中并不扮演核心角色(根據提供的代碼),但可用于發起或協助完成面向用戶的任務。
user_proxy = autogen.UserProxyAgent(
name="user_proxy",
max_consecutive_auto_reply=1,
# is_termination_msg=lambda x: x.get("content", "").rstrip().endswith("TERMINATE"),
llm_cnotallow=llm_config,
system_message="""you are an helpful assistant and initate the conversation"""
)
步驟 4:創建群組管理器
這一步創建中央協調器,以管理所有專業智能體之間的溝通和團隊協作。
1. 設置群聊
群聊為三個專業智能體構建了一個結構化的對話環境。這些是客戶智能體、范圍架構師智能體和費率推薦智能體。它通過輪次限制和有序的發言者選擇來管理對話流程。
要點:
容納三個專業智能體共同創建提案
- 最多四輪次,以保持專注
- “循環”發言模式確保有序參與
- 創建一個受控的信息收集環境
# --- Group Chat Setup ---
groupchat = autogen.GroupChat(
agents=[client_agent, scope_architect_agent, rate_recommender_agent],
messages=[],
max_round=4,
speaker_selection_method="round_robin",
)
2. 創建群聊管理器
群聊管理器負責協調整個對話,引導交互完成從項目細節到提案生成的邏輯過程。其系統消息提供智能體交互的逐步說明,并定義明確的終止條件。
要點:
- 引導所有智能體之間的對話流程
- 鏈接到群聊對象
- 保持一致的LLM 配置
- 包含詳細的流程說明
- 在提案完成或使用TERMINATE命令時終止
manager = autogen.GroupChatManager(
groupchat=groupchat,
llm_cnotallow=llm_config,
# System message for the manager guiding the overall flow
system_message="""Manage the conversation flow between the agents.
1. Start with the Client_Input_Agent providing project details.
2. Ensure the Scope_Architect asks the necessary questions about the user's background.
3. Ensure the Client_Input_Agent relays the user's answers.
4. Ensure the Rate_Recommender waits for all info before generating the final proposal in the specified format.
The conversation finishes when the final proposal is generated or the Client_Input_Agent says TERMINATE."""
)
步驟 5:發起聊天
現在智能體已到位,不妨啟動智能體之間的協作工作流程。為此,我們將從user_proxy 智能體向GroupChatManager(群聊管理器)發送清晰的指令提示。
要點:
- 使用user_proxy.initiate_chat()觸發對話,該函數啟動群聊,并將消息發送到 GroupChatManager。
- 將控制權委托給GroupChatManager,然后GroupChatManager使用循環方法及其內部系統消息指令,按照逐步流程協調智能體。
# --- Initiate Chat ---
print("Starting the proposal generation process...")
print("Please provide the initial client and project details when prompted.")
initial_prompt_message = """
Start the process. First, I need the client/project details from the user (via Client_Input_Agent).
Then, Scope_Architect should ask the user (via Client_Input_Agent) about their background.
Finally, Rate_Recommender should generate the proposal.
"""
user_proxy.initiate_chat(
manager,
message=initial_prompt_message
)
步驟 6:格式化輸出
該代碼將幫助我們以markdown(.md) 格式呈現輸出。
chat_history = manager.chat_messages[client_agent] # Or potentially just manager.chat_messages if structure differs slightly
# Find the last message from the Rate_Recommender agent
final_proposal_message = None
for msg in reversed(chat_history):
if msg.get("role") == "assistant" and msg.get("name") == rate_recommender_agent.name:
if "Custom Introduction:" in msg.get("content", ""):
final_proposal_message = msg
break
if final_proposal_message:
final_proposal_string = final_proposal_message.get("content", "Proposal content not found.")
try:
display(Markdown(final_proposal_string))
except NameError:
print("\n(Displaying raw Markdown text as rich output is unavailable)\n")
print(final_proposal_string)
else:
print("\nCould not automatically extract the final proposal from the chat history.")
print("You may need to review the full chat history above.")
示例輸出:
結語
我們在本文中使用Llama 4和AutoGen構建了一個項目提案智能體。該智能體有效地收集了客戶需求,明確了提案結構,并提交了一份包含清晰定價和時間表安排的專業文檔。AutoGen負責處理對話流程,而Llama 4確保了全程自然且基于上下文的響應。這種協作簡化了智能體溝通,為自由職業者和顧問提供了精簡的解決方案,使其能夠以最少的手動輸入自動生成提案。
Llama 4通過改進的指令遵循能力、更佳的上下文保留能力和高效的小樣本學習,提升了智能體的性能。它能夠在多輪對話中保持一致性,使提案生成過程更加智能化、響應更迅速。此外,該模型的快速推理和低成本使其非常適合實時應用場景。Llama 4和AutoGen共同實現了強大的智能體工作流程,從而在處理面向客戶的任務時提升了生產力和專業性。
原文標題:Building an AI Agent with Llama 4 and AutoGen,作者:Vipin Vashisth