使用Llama 4和AutoGen構(gòu)建一個(gè)AI智能體 原創(chuàng)
Meta的Llama 4 系列模型目前正主導(dǎo)不斷發(fā)展的AI世界。這些模型憑借原生的多模態(tài)功能,正在徹底改變我們構(gòu)建智能系統(tǒng)的方式。當(dāng)Llama 4與AutoGen結(jié)合使用時(shí),它將充分發(fā)掘構(gòu)建動(dòng)態(tài)、響應(yīng)迅速且強(qiáng)大的AI智能體的潛力。如果充分利用Llama 4與AutoGen之間的集成,開(kāi)發(fā)者可以創(chuàng)建能夠高效推理、協(xié)作和適應(yīng)的創(chuàng)新型AI智能體。我們?cè)诒疚闹袑W(xué)習(xí)如何使用 Llama 4和AutoGen為特定應(yīng)用場(chǎng)景構(gòu)建AI智能體。
為什么我們應(yīng)該考慮使用Llama 4?
Llama 4系列模型(包括 Scout和Maverick變體)是開(kāi)源AI技術(shù)的重大飛躍。這些模型有以下幾大優(yōu)勢(shì):
- 多模態(tài)智能:Llama 4具有原生多模態(tài)功能,可以將不同類型的輸入集成到統(tǒng)一的架構(gòu)中。因而可以跨不同類型的媒體進(jìn)行更復(fù)雜的推理。
- 大上下文長(zhǎng)度:它支持高達(dá)1000萬(wàn)個(gè) token,超越了Llama 3的12.8萬(wàn)個(gè)限制。它能夠處理超長(zhǎng)上下文,這使得支持高級(jí)應(yīng)用成為可能,比如全面的多文檔分析、基于用戶歷史記錄的廣泛個(gè)性化以及大型代碼庫(kù)的導(dǎo)航。
- 高效性能:Llama 4 采用混合專家架構(gòu),針對(duì)處理的每個(gè)token僅激活模型的特定部分。這種方法大大提高了模型的效率。比如說(shuō),Llama 4 Maverick在運(yùn)行過(guò)程中僅使用其總共 4000 億個(gè)參數(shù)中的170億個(gè),這使得它在單單一個(gè)H100 DGX主機(jī)上就能夠運(yùn)行。
- 卓越的性能和功能:基準(zhǔn)測(cè)試表明,Llama 4 Maverick在編程、推理、多語(yǔ)言能力和圖像理解方面均優(yōu)于GPT-4o 和 Gemini 2.0等同類模型。
- 開(kāi)源、易于訪問(wèn):Meta現(xiàn)在允許人們下載使用其模型。這鼓勵(lì)開(kāi)放式創(chuàng)新,使開(kāi)發(fā)者能夠跨各種應(yīng)用程序和平臺(tái)定制和部署該技術(shù)。
Llama 4 基準(zhǔn)測(cè)試性能
為了了解該模型到底有多好,下面比較Llama 4 與其他頭部模型在各項(xiàng)標(biāo)準(zhǔn)基準(zhǔn)測(cè)試中的表現(xiàn)。
圖1. Llama 4 基準(zhǔn)測(cè)試性能
使用Llama 4構(gòu)建AI智能體
我在本節(jié)中將逐步介紹使用Llama 4和AutoGen構(gòu)建針對(duì)特定任務(wù)的智能體的過(guò)程。我們將創(chuàng)建一個(gè)多智能體系統(tǒng),該系統(tǒng)可分析客戶的工作需求,根據(jù)自由職業(yè)者的經(jīng)驗(yàn)和詳細(xì)信息尋找適合某項(xiàng)工作的自由職業(yè)者,然后生成自定義的工作提案供用戶發(fā)送。
步驟 0:設(shè)置環(huán)境
在構(gòu)建智能體之前,我們先介紹必要的先決條件并設(shè)置環(huán)境。
先決條件
- 熟悉終端或命令提示。
- 能夠在系統(tǒng)上設(shè)置環(huán)境變量。
- 能夠使用終端或命令提示來(lái)運(yùn)行程序。
- 必須安裝 Python:??https://www.python.org/downloads/???
- 對(duì)AutoGen有一番基本的了解:??https://docs.ag2.ai/latest/???
訪問(wèn)API
我們將在此處使用Together API來(lái)訪問(wèn)Llama 4模型。在Together AI上創(chuàng)建一個(gè)帳戶,并訪問(wèn)該頁(yè)面以創(chuàng)建密鑰:??https://api.together.xyz/??。
步驟 1:設(shè)置用于指導(dǎo)AI智能體的庫(kù)和工具
首先,我們將在此處導(dǎo)入所有必要的庫(kù)和工具。
import os
import autogen
from IPython.display import display, Markdown
步驟 2:調(diào)用API
若要使用Llama 4,我們必須加載Together API。下面的代碼塊將幫助我們加載API,并根據(jù)環(huán)境來(lái)配置它們。
with open("together_ai_api.txt") as file:
LLAMA_API_KEY = file.read().strip()
os.environ["LLAMA_API_KEY"] = LLAMA_API_KEY
步驟 3:創(chuàng)建智能體并定義任務(wù)
現(xiàn)在不妨創(chuàng)建所需的智能體并定義它們的任務(wù),即它們要執(zhí)行的操作。
1.客戶輸入智能體
客戶輸入智能體充當(dāng)人類用戶和智能體系統(tǒng)之間的主要接口。它從用戶那里收集項(xiàng)目的詳細(xì)信息,比如客戶需求、時(shí)間表和預(yù)算,并將它們傳遞給范圍架構(gòu)師。它還會(huì)傳遞后續(xù)問(wèn)題和答案,并在最終提案被接受時(shí)發(fā)出終止信號(hào)。
預(yù)期輸出:
- 清晰地傳達(dá)用戶的項(xiàng)目描述和自由職業(yè)者的個(gè)人資料(技能、經(jīng)驗(yàn)和預(yù)計(jì)時(shí)間)。
- 一旦提交了令人滿意的提案,就結(jié)束會(huì)話,或者用戶明確結(jié)束會(huì)話。
# 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. 范圍架構(gòu)師智能體
范圍架構(gòu)師智能體負(fù)責(zé)從客戶輸入智能體那里獲取初始項(xiàng)目詳細(xì)信息。之后,它會(huì)提出具體問(wèn)題,以收集自由職業(yè)者的技能、工具、過(guò)去的項(xiàng)目經(jīng)驗(yàn)以及完成工作的預(yù)計(jì)時(shí)間。它本身不會(huì)生成提案,但確保在提交給下一個(gè)智能體之前收集所有必要的上下文。
預(yù)期輸出:
- 結(jié)構(gòu)清晰的摘要結(jié)合客戶的項(xiàng)目需求和自由職業(yè)者的能力。
- 一旦收集并匯總了所有必需數(shù)據(jù),就觸發(fā)“費(fèi)率推薦智能體”。
# 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.費(fèi)率推薦智能體
費(fèi)率推薦智能體使用收集到的信息生成詳細(xì)的項(xiàng)目提案。它等待范圍架構(gòu)師智能體提供的完整摘要,然后分析項(xiàng)目范圍和自由職業(yè)者的詳細(xì)信息,以生成一份專業(yè)的提案文檔。這份文檔包含自定義簡(jiǎn)介、時(shí)間表、多個(gè)定價(jià)層級(jí)以及明確的行動(dòng)號(hào)召。
預(yù)期輸出:
- 格式專業(yè)的項(xiàng)目提案文檔,附有范圍、定價(jià)和后續(xù)步驟。
- 最終輸出已準(zhǔn)備好交付給客戶審批或進(jìn)一步討論。
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. 用戶代理智能體
該智能體充當(dāng)啟動(dòng)交互的入口點(diǎn)或助手。雖然它在該流程中并不扮演核心角色(根據(jù)提供的代碼),但可用于發(fā)起或協(xié)助完成面向用戶的任務(wù)。
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:創(chuàng)建群組管理器
這一步創(chuàng)建中央?yún)f(xié)調(diào)器,以管理所有專業(yè)智能體之間的溝通和團(tuán)隊(duì)協(xié)作。
1. 設(shè)置群聊
群聊為三個(gè)專業(yè)智能體構(gòu)建了一個(gè)結(jié)構(gòu)化的對(duì)話環(huán)境。這些是客戶智能體、范圍架構(gòu)師智能體和費(fèi)率推薦智能體。它通過(guò)輪次限制和有序的發(fā)言者選擇來(lái)管理對(duì)話流程。
要點(diǎn):
容納三個(gè)專業(yè)智能體共同創(chuàng)建提案
- 最多四輪次,以保持專注
- “循環(huán)”發(fā)言模式確保有序參與
- 創(chuàng)建一個(gè)受控的信息收集環(huán)境
# --- 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. 創(chuàng)建群聊管理器
群聊管理器負(fù)責(zé)協(xié)調(diào)整個(gè)對(duì)話,引導(dǎo)交互完成從項(xiàng)目細(xì)節(jié)到提案生成的邏輯過(guò)程。其系統(tǒng)消息提供智能體交互的逐步說(shuō)明,并定義明確的終止條件。
要點(diǎn):
- 引導(dǎo)所有智能體之間的對(duì)話流程
- 鏈接到群聊對(duì)象
- 保持一致的LLM 配置
- 包含詳細(xì)的流程說(shuō)明
- 在提案完成或使用TERMINATE命令時(shí)終止
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:發(fā)起聊天
現(xiàn)在智能體已到位,不妨啟動(dòng)智能體之間的協(xié)作工作流程。為此,我們將從user_proxy 智能體向GroupChatManager(群聊管理器)發(fā)送清晰的指令提示。
要點(diǎn):
- 使用user_proxy.initiate_chat()觸發(fā)對(duì)話,該函數(shù)啟動(dòng)群聊,并將消息發(fā)送到 GroupChatManager。
- 將控制權(quán)委托給GroupChatManager,然后GroupChatManager使用循環(huán)方法及其內(nèi)部系統(tǒng)消息指令,按照逐步流程協(xié)調(diào)智能體。
# --- 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) 格式呈現(xiàn)輸出。
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.")
示例輸出:
結(jié)語(yǔ)
我們?cè)诒疚闹惺褂肔lama 4和AutoGen構(gòu)建了一個(gè)項(xiàng)目提案智能體。該智能體有效地收集了客戶需求,明確了提案結(jié)構(gòu),并提交了一份包含清晰定價(jià)和時(shí)間表安排的專業(yè)文檔。AutoGen負(fù)責(zé)處理對(duì)話流程,而Llama 4確保了全程自然且基于上下文的響應(yīng)。這種協(xié)作簡(jiǎn)化了智能體溝通,為自由職業(yè)者和顧問(wèn)提供了精簡(jiǎn)的解決方案,使其能夠以最少的手動(dòng)輸入自動(dòng)生成提案。
Llama 4通過(guò)改進(jìn)的指令遵循能力、更佳的上下文保留能力和高效的小樣本學(xué)習(xí),提升了智能體的性能。它能夠在多輪對(duì)話中保持一致性,使提案生成過(guò)程更加智能化、響應(yīng)更迅速。此外,該模型的快速推理和低成本使其非常適合實(shí)時(shí)應(yīng)用場(chǎng)景。Llama 4和AutoGen共同實(shí)現(xiàn)了強(qiáng)大的智能體工作流程,從而在處理面向客戶的任務(wù)時(shí)提升了生產(chǎn)力和專業(yè)性。
原文標(biāo)題:??Building an AI Agent with Llama 4 and AutoGen??,作者:Vipin Vashisth
