AI在线 AI在线

使用Llama 4和AutoGen构建一个AI智能体

译者 | 布加迪审校 | 重楼Meta的Llama 4 系列模型目前正主导不断发展的AI世界。 这些模型凭借原生的多模态功能,正在彻底改变我们构建智能系统的方式。 当Llama 4与AutoGen结合使用时,它将充分发掘构建动态、响应迅速且强大的AI智能体的潜力。

使用Llama 4和AutoGen构建一个AI智能体

译者 | 布加迪

审校 | 重楼

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 与其他头部模型在各项标准基准测试中的表现。

使用Llama 4和AutoGen构建一个AI智能体

图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/。

使用Llama 4和AutoGen构建一个AI智能体

步骤 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构建一个AI智能体

使用Llama 4和AutoGen构建一个AI智能体

结语

我们在本文中使用Llama 4和AutoGen构建了一个项目提案智能体。该智能体有效地收集了客户需求,明确了提案结构,并提交了一份包含清晰定价和时间表安排的专业文档。AutoGen负责处理对话流程,而Llama 4确保了全程自然且基于上下文的响应。这种协作简化了智能体沟通,为自由职业者和顾问提供了精简的解决方案,使其能够以最少的手动输入自动生成提案。

Llama 4通过改进的指令遵循能力、更佳的上下文保留能力和高效的小样本学习,提升了智能体的性能。它能够在多轮对话中保持一致性,使提案生成过程更加智能化、响应更迅速。此外,该模型的快速推理和低成本使其非常适合实时应用场景。Llama 4和AutoGen共同实现了强大的智能体工作流程,从而在处理面向客户的任务时提升了生产力和专业性。

原文标题:Building an AI Agent with Llama 4 and AutoGen,作者:Vipin Vashisth

相关资讯

早半年发arXiv,却被质疑抄袭:活在微软AutoGen阴影里的CAMEL

arXiv 不是同行评审期刊,所以发在 arXiv 上的论文不必被引用,这合理吗?  如果你对 AI 智能体感兴趣,那你一定知道微软的 AutoGen。它是一个用于构建 AI 智能体的开源编程框架,允许多个智能体通过聊天来解决任务。其间,LLM 智能体可以扮演多种角色,如程序员、设计师,或者各种角色的组合。在 GitHub 上,这个项目已经收获了 28k 的 star 量,论文还在 ICLR 2024  LLM Agent Workshop 上获得了最佳论文奖。不过,这篇论文的背后其实是存在争议的。2023 年 1
7/17/2024 3:18:00 PM
机器之心

如何使用AutoGen AI技术实现多代理对话

译者 | 李睿审校 | 重楼本文将介绍一个实验,展示多个人工智能代理如何通过群聊方式进行互动,并根据具体的业务需求协同工作,共同生成解决方案的架构。 本文介绍如何使用Databricks Community Edition (CE)(一个免费的基于云的平台)运行一些基本的人工智能Python代码。 因为只处理开源库,所以这个实验可以很容易地在任何Python/PySpark环境中复现。
12/5/2024 8:15:00 AM
李睿

真·ChatGPT平替:无需显卡,MacBook、树莓派就能运行LLaMA

Meta 在上个月末发布了一系列开源大模型 ——LLaMA(Large Language Model Meta AI),参数量从 70 亿到 650 亿不等。由于模型参数量较少,只需单张显卡即可运行,LLaMA 因此被称为 ChatGPT 的平替。发布以来,已有多位开发者尝试在自己的设备上运行 LLaMA 模型,并分享经验。
3/14/2023 2:16:00 PM
机器之心
  • 1