Meta开源的Llama官方Agent:Llama-Agentic-System深度解析

打印 上一主题 下一主题

主题 1772|帖子 1772|积分 5316

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x

TLDR



  • • Meta 推出的 Llama as a System 将 Llama 3.1 模型转变为一个可以或许自主完成使命的智能代理,通过多步推理、工具使用和系统级安全机制,为构建更智能、更安全的 AI 应用开辟了新的可能性。
  • • Llama-Agentic-System 具备强大的功能,包括多步推理、工具使用(内置和零样本学习)以及系统级安全保障,可以或许处理惩罚更复杂的使命,并加强安全性。
  • • 本文将深入探讨 Llama as a System 的概念、架构、功能和应用场景,并提供具体的代码示例和使用指南。
引言

大型语言模型(LLM)的迅猛发展为人工智能领域带来了革命性的变革。从最初的文本生成工具,LLM 渐渐展现出理解复杂指令、执行多步使命的潜力。然而,如何将 LLM 安全、高效地应用于实际使命仍然是一个挑衅。Meta 推出的 Llama 3.1 为解决这个问题提供了新的思路:将 Llama 作为一个系统,使其可以或许完成更复杂的使命,并加强其安全性。本文将具体先容 Llama as a System 的概念、功能以及如何使用它构建 AI 应用。
Llama Agentic System 的核心功能

Llama Agentic System 的核心在于将 Llama 模型从一个简朴的文本生成工具转变为一个可以或许自主完成使命的智能代理。它具备以下关键能力:


  • • 多步推理: 将复杂使命分解成多个步调,并按照逻辑顺序执行。例如,要预订航班,模型必要先搜索航班信息,然后选择符合的航班,最后填写乘客信息并完成支付。
  • • 工具使用: 可以或许调用各种工具来完成使命,包括:

    • • 内置工具:如搜索引擎、代码解释器等。这些工具预先集成到系统中,模型可以直接调用。
    • • 零样本学习工具:可以通过上下文信息学习使用新的工具。这意味着即使模型之前没有见过某个工具,只要提供工具的使用阐明,它就可以学会使用。

  • • 系统级安全: 将安全评估从模型级别提拔到整个系统级别,通过 Llama Guard 等安全机制,确保系统在各种场景下的安全性。这包括对用户输入、模型输出以及工具调用举行安全查抄和过滤,防止恶意攻击和不当内容的产生。
Llama Agentic System 架构解析

为了更好地理解 Llama Agentic System 的工作原理,让我们深入相识其架构。下图展示了 Llama Agentic System 的核心组件及其交互方式:
  1. [/code] [b]组件阐明:[/b]
  2. [list]
  3. [*] • [b]User(用户)[/b]: 与 Llama Agentic System 举行交互的用户,发起使命指令并接收终极效果。
  4. [*] • [b]Executor(执行器)[/b]: Llama Agentic System 的核心控制单元,负责接收用户输入,调用安全机制,并将使命分发给 LLM 或工具,终极将效果返回给用户。
  5. [*] • [b]LLM(大型语言模型)[/b]: Llama 模型,负责理解使命、生成文本、选择符合的工具来执利用命,是系统的智能核心。
  6. [*] • [b]Tools(工具)[/b]: 外部工具,如搜索引擎、代码解释器等,用于扩展 LLM 的功能,执行 LLM 无法直接完成的使命。
  7. [*] • [b]Shields(安全机制)[/b]: 负责对用户输入、模型输出以及工具调用举行安全查抄和过滤,确保系统安全可靠地运行。
  8. [/list] [b]工作流程:[/b]
  9. [list=1]
  10. [*] 1. 用户将使命指令和相关信息发送给 Executor。
  11. [*] 2. Executor 调用安全机制对用户输入举行查抄,确保输入内容安全无害。
  12. [*] 3. Executor 将使命指令发送给 LLM,LLM 分析指令并选择符合的工具(如果必要)。
  13. [*] 4. LLM 根据使命指令选择符合的工具,并将调用请求发送给 Executor。
  14. [*] 5. Executor 调用安全机制对工具调用举行查抄,防止潜在的安全风险。
  15. [*] 6. Executor 调用相应的工具,并将工具返回的效果发送给 LLM,LLM 继续处理惩罚使命。
  16. [*] 7. LLM 整合工具返回的效果,生成终极的回复,并发送给 Executor。
  17. [*] 8. Executor 调用安全机制对模型输出举行查抄,确保输出内容安全可靠。
  18. [*] 9. Executor 将终极的回复发送给用户,完成使命。
  19. [/list] [size=4]Llama Agentic System 代码实现细节[/size]
  20. Llama Agentic System 的核心代码位于 llama_agentic_system/agentic_system.py 文件中。以下是一些关键代码片段和解释:
  21. [size=3]1. AgentInstance 类[/size]
  22. [code]class AgentInstance(ShieldRunnerMixin):
  23. def__init__(
  24.         self,
  25.         system_id:int,
  26.         instance_config:AgenticSystemInstanceConfig,
  27.         model:InstructModel,
  28.         inference_api:Inference,
  29.         builtin_tools:List[SingleMessageBuiltinTool],
  30.         custom_tool_definitions:List[ToolDefinition],
  31.         input_shields:List[ShieldBase],
  32.         output_shields:List[ShieldBase],
  33.         max_infer_iters:int=10,
  34.         prefix_messages:Optional[List[Message]]=None,
  35.     ):
  36. # ... 初始化代码 ...
  37. # 初始化内置工具字典
  38.         self.tools_dict ={t.get_name(): t for t in builtin_tools}
  39. # 初始化会话字典
  40.         self.sessions ={}
  41. # 初始化安全机制
  42. ShieldRunnerMixin.__init__(
  43.             self,
  44.             input_shields=input_shields,
  45.             output_shields=output_shields,
  46. )
  47. defcreate_session(self, name: str)->Session:
  48.         # ... 创建会话代码 ...
复制代码
AgentInstance 类表示一个 Llama Agentic System 实例,负责管分析话、执行推理、调用工具和安全机制等。它是 Llama Agentic System 的核心控制单元,和谐各个组件协同工作。


  • • 它维护一个 tools_dict 字典,存储所有可用的内置工具,键为工具名,值为工具实例。
  • • 它维护一个 sessions 字典,存储所有会话,键为会话 ID,值为会话实例。
  • • 它使用 ShieldRunnerMixin 来管理输入和输出安全机制。
2. create_and_execute_turn 方法

  1.     async defcreate_and_execute_turn(
  2.         self, request: AgenticSystemTurnCreateRequest
  3.     )->AsyncGenerator:
  4. # ... 获取会话,构建历史消息 ...
  5. # ... 创建轮次 ID,初始化参数 ...
  6. # 发送轮次开始事件
  7. yieldAgenticSystemTurnResponseStreamChunk(
  8.             event=AgenticSystemTurnResponseEvent(
  9.                 payload=AgenticSystemTurnResponseTurnStartPayload(
  10.                     turn_id=turn_id,
  11. )
  12. )
  13. )
  14.         steps =[]
  15.         output_message =None
  16. asyncfor chunk in self.run(
  17.             turn_id=turn_id,
  18.             input_messages=messages,
  19.             temperature=params.temperature,
  20.             top_p=params.top_p,
  21.             stream=request.stream,
  22.             max_gen_len=params.max_tokens,
  23. ):
  24. # 处理推理过程中的事件流
  25. # ...
  26. # ... 断言 output_message 不为空 ...
  27. # 创建轮次实例
  28.         turn =Turn(
  29.             turn_id=turn_id,
  30.             session_id=request.session_id,
  31.             input_messages=request.messages,
  32.             output_message=output_message,
  33.             started_at=start_time,
  34.             completed_at=datetime.now(),
  35.             steps=steps,
  36. )
  37. # 将轮次添加到会话中
  38.         session.turns.append(turn)
  39. # 发送轮次结束事件
  40. yieldAgenticSystemTurnResponseStreamChunk(
  41.             event=AgenticSystemTurnResponseEvent(
  42.                 payload=AgenticSystemTurnResponseTurnCompletePayload(
  43.                     turn=turn,
  44. )
  45. )
  46.         )
复制代码
该方法负责创建一个新的会话轮次,并执行用户请求。它会根据用户输入调用 LLM 举行推理,并根据 LLM 的回复调用相应的工具。这个方法实现了 Llama Agentic System 的交互逻辑,处理惩罚用户输入并生成相应的输出。


  • • 它首先获取对应的会话,并构建包罗历史消息的消息列表。
  • • 然后,它调用 self.run() 方法执行推理,并处理惩罚推理过程中产生的事件流。
  • • 最后,它创建 Turn 实例表示当前轮次,并发送轮次结束事件。
3. run 方法

  1.     async defrun(
  2.         self,
  3.         turn_id:str,
  4.         input_messages:List[Message],
  5.         temperature:float,
  6.         top_p:float,
  7.         stream:bool=False,
  8.         max_gen_len:Optional[int]=None,
  9.     )->AsyncGenerator:
  10. # 对用户输入调用安全机制
  11. asyncfor res in self.run_shields_wrapper(
  12.             turn_id, input_messages, self.input_shields,"user-input"
  13. ):
  14. ifisinstance(res,bool):
  15. return
  16. else:
  17. yield res
  18. # 调用 _run 方法执行推理
  19. asyncfor res in self._run(
  20.             turn_id, input_messages, temperature, top_p, stream, max_gen_len
  21. ):
  22. ifisinstance(res,bool):
  23. return
  24. elifisinstance(res,CompletionMessage):
  25.                 final_response = res
  26. break
  27. else:
  28. yield res
  29. # ... 断言 final_response 不为空 ...
  30. # 对模型输出调用安全机制
  31.         messages = input_messages +[final_response]
  32. asyncfor res in self.run_shields_wrapper(
  33.             turn_id, messages, self.output_shields,"assistant-output"
  34. ):
  35. ifisinstance(res,bool):
  36. return
  37. else:
  38. yield res
  39. yield final_response
复制代码
run 方法是 create_and_execute_turn 方法的核心,它实现了 Llama Agentic System 的推理逻辑,包括调用 LLM、执行工具、处理惩罚安全机制等。该方法是 Llama Agentic System 智能的核心,实现了多步推理、工具使用和安全保障等关键功能。


  • • 它首先对用户输入调用 run_shields_wrapper 方法举行安全查抄。
  • • 然后,它调用 _run 方法执行实际的推理过程,并处理惩罚推理过程中产生的事件流。
  • • 最后,它对模型输出再次调用 run_shields_wrapper 方法举行安全查抄。
4. _run 方法

  1.     async def_run(
  2.         self,
  3.         turn_id:str,
  4.         input_messages:List[Message],
  5.         temperature:float,
  6.         top_p:float,
  7.         stream:bool=False,
  8.         max_gen_len:Optional[int]=None,
  9.     )->AsyncGenerator:
  10. # 预处理消息,添加系统提示信息
  11.         input_messages = preprocess_dialog(input_messages, self.prefix_messages)
  12.         attachments =[]
  13.         n_iter =0
  14. whileTrue:
  15. # ... 获取最后一条消息,打印消息内容 ...
  16.             step_id =str(uuid.uuid4())
  17. # 发送推理步骤开始事件
  18. yieldAgenticSystemTurnResponseStreamChunk(
  19.                 event=AgenticSystemTurnResponseEvent(
  20.                     payload=AgenticSystemTurnResponseStepStartPayload(
  21.                         step_type=StepType.inference.value,
  22.                         step_id=step_id,
  23. )
  24. )
  25. )
  26. # 构建推理请求
  27.             req =ChatCompletionRequest(
  28.                 model=self.model,
  29.                 messages=input_messages,
  30.                 available_tools=self.instance_config.available_tools,
  31.                 stream=True,
  32.                 sampling_params=SamplingParams(
  33.                     temperature=temperature,
  34.                     top_p=top_p,
  35.                     max_tokens=max_gen_len,
  36. ),
  37. )
  38.             tool_calls =[]
  39.             content =""
  40.             stop_reason =None
  41. # 调用推理接口,处理推理结果
  42. asyncfor chunk in self.inference_api.chat_completion(req):
  43. # ... 处理推理结果 ...
  44. # ... 处理推理结束原因 ...
  45. # 创建 CompletionMessage 实例
  46.             message =CompletionMessage(
  47.                 content=content,
  48.                 stop_reason=stop_reason,
  49.                 tool_calls=tool_calls,
  50. )
  51. # 发送推理步骤结束事件
  52. yieldAgenticSystemTurnResponseStreamChunk(
  53.                 event=AgenticSystemTurnResponseEvent(
  54.                     payload=AgenticSystemTurnResponseStepCompletePayload(
  55.                         step_type=StepType.inference.value,
  56.                         step_id=step_id,
  57.                         step_details=InferenceStep(
  58.                             step_id=step_id, turn_id=turn_id, model_response=message
  59. ),
  60. )
  61. )
  62. )
  63. # ... 处理推理结束条件 ...
  64. # ... 处理模型调用工具 ...
  65.             n_iter += 1
复制代码
_run 方法是 run 方法的核心,它实现了 Llama Agentic System 的推理逻辑,包括调用 LLM、执行工具、处理惩罚安全机制等。


  • • 它首先预处理惩罚消息,添加系统提示信息。
  • • 然后,它进入一个循环,每次循环执行一次推理步调,直到满意结束条件。
  • • 在每个推理步调中,它首先构建推理请求,然后调用 self.inference_api.chat_completion() 方法执行推理,并处理惩罚推理效果。
  • • 如果模型必要调用工具,它会调用相应的工具,并将工具返回的效果添加到消息列表中。
Llama Agentic System Demo 示例

Llama Agentic System 提供了一些 Demo 示例,展示了如何使用它来完成实际使命。以下是一些示例:
1. 通货膨胀分析



  • • 代码路径: examples/scripts/inflation.py
  • • 功能描述: 该示例展示了如何使用 Llama Agentic System 来分析通货膨胀数据。它首先加载一个 CSV 文件,然后使用 LLM 往返答有关通货膨胀的问题,例如“哪一年以最高的通货膨胀结束?”、“是什么宏观经济形势导致了该时期如此高的通货膨胀?”等等。这个示例展示了 Llama Agentic System 如何处理惩罚结构化数据,并使用工具举行数据分析。
  1. import asyncio
  2. import fire
  3. from llama_models.llama3_1.api.datatypes import*# noqa: F403
  4. from custom_tools.ticker_data importTickerDataTool
  5. from multi_turn import prompt_to_message, run_main
  6. # 定义主函数
  7. defmain(host: str, port: int, disable_safety: bool = False):
  8. # 使用 asyncio 运行异步主函数
  9.     asyncio.run(
  10.         run_main(
  11. [
  12. UserMessage(
  13.                     content=[
  14. "Here is a csv, can you describe it ?",
  15. Attachment(
  16.                             url=URL(uri="file://examples/resources/inflation.csv"),
  17.                             mime_type="text/csv",
  18. ),
  19. ],
  20. ),
  21.                 prompt_to_message("Which year ended with the highest inflation ?"),
  22.                 prompt_to_message(
  23. "What macro economic situations that led to such high inflation in that period?"
  24. ),
  25.                 prompt_to_message("Plot average yearly inflation as a time series"),
  26.                 prompt_to_message(
  27. "Using provided functions, get ticker data for META for the past 10 years ? plot percentage year over year growth"
  28. ),
  29.                 prompt_to_message(
  30. "Can you take Meta's year over year growth data and put it in the same inflation timeseries as above ?"
  31. ),
  32. ],
  33.             host=host,
  34.             port=port,
  35.             disable_safety=disable_safety,
  36.             custom_tools=[TickerDataTool()],
  37. )
  38. )
  39. if __name__ =="__main__":
  40.     fire.Fire(main)
复制代码
代码解读:


  • • 导入须要的库,包括 asyncio 用于异步利用,fire 用于下令行参数解析,llama_models 用于 Llama 模型相关功能,custom_tools 用于自定义工具,以及 multi_turn 用于多轮对话。
  • • 定义 main 函数,它是步伐的入口点。

    • • 它使用 asyncio.run 运行异步函数 run_main。
    • • run_main 函数接收一系列用户消息和参数,包括主机地址、端口号、是否禁用安全机制以及自定义工具列表。
    • • 用户消息使用 UserMessage 类表示,可以包罗文本、附件等内容。
    • • prompt_to_message 函数用于将文本提示转换为用户消息。
    • • TickerDataTool 是一个自定义工具,用于获取股票数据。

  • • 使用 fire.Fire(main) 将 main 函数绑定到下令行接口,方便用户使用下令行参数运行步伐。
2. 旅行筹划



  • • 代码路径: examples/scripts/vacation.py
  • • 功能描述: 该示例展示了如何使用 Llama Agentic System 来筹划旅行。用户可以向系统提供一些旅行信息,例如目标地、时间等,系统会根据这些信息生成具体的旅行筹划,包括景点推荐、路线规划、留宿发起等。这个示例展示了 Llama Agentic System 如何与用户举行多轮对话,并调用外部工具获取信息,终极完成复杂的使命。
  1. import asyncio
  2. import fire
  3. from multi_turn import prompt_to_message, run_main
  4. # 定义主函数
  5. defmain(host: str, port: int, disable_safety: bool = False):
  6.     asyncio.run(
  7.         run_main(
  8. [
  9.                 prompt_to_message(
  10. "I am planning a trip to Switzerland, what are the top 3 places to visit?"
  11. ),
  12.                 prompt_to_message("What is so special about #1?"),
  13.                 prompt_to_message("What other countries should I consider to club?"),
  14.                 prompt_to_message("How many days should I plan for in each country?"),
  15. ],
  16.             host=host,
  17.             port=port,
  18.             disable_safety=disable_safety,
  19. )
  20. )
  21. # 当脚本作为主程序运行时,使用 fire 库执行 main 函数
  22. if __name__ =="__main__":
  23.     fire.Fire(main)
复制代码
代码解读:


  • • 导入须要的库,包括 asyncio 用于异步利用,fire 用于下令行参数解析,以及 multi_turn 用于多轮对话。
  • • 定义 main 函数,它是步伐的入口点。

    • • 它使用 asyncio.run 运行异步函数 run_main。
    • • run_main 函数接收一系列用户消息和参数,包括主机地址、端口号以及是否禁用安全机制。
    • • 用户消息使用 prompt_to_message 函数将文本提示转换为用户消息。

  • • 使用 fire.Fire(main) 将 main 函数绑定到下令行接口,方便用户使用下令行参数运行步伐。
Llama Agentic System 安装与配置

如果您对 Llama as a System 感兴趣,并想尝试使用它,可以按照以下步调举行安装和配置:
  1. # 创建并激活虚拟环境
  2. ENV=agentic_env
  3. with-proxy conda create -n $ENV python=3.10
  4. cd<path-to-llama-agentic-system-repo>
  5. conda activate $ENV
  6. # 安装所需包
  7. pip install -r requirements.txt
  8. pip install llama-agentic-system
  9. # 安装 bubblewrap 
  10. # ... 根据您的操作系统安装 bubblewrap ...
  11. # 测试安装
  12. llama --help
  13. # 下载模型检查点
  14. llama download meta-llama/Meta-Llama-3.1-8B-Instruct
  15. llama download meta-llama/Meta-Llama-3.1-70B-Instruct
  16. llama download meta-llama/Prompt-Guard-86M--ignore-patterns original
  17. llama download meta-llama/Llama-Guard-3-8B--ignore-patterns original
  18. # 配置推理服务器
  19. llama inference configure
  20. # 运行推理服务器
  21. llama inference start
  22. # 配置 Agentic System
  23. llama agentic_system configure
  24. # 运行应用程序
  25. mesop app/main.py
  26. # 脚本交互
  27. cd<path-to-llama-agentic-system>
  28. conda activate $ENV
  29. llama inference start
  30. python examples/scripts/vacation.py localhost 5000
复制代码
结论

Llama as a System 为构建更智能、更安全的 AI 应用提供了强大的工具。通过将 Llama 模型与工具、安全机制相结合,我们可以构建可以或许解决更复杂问题的 AI 代理,并将其应用于更广泛的领域。


相关链接



  • • Llama 官方网站: https://ai.meta.com/llama/
  • • Llama Agentic System GitHub 仓库: https://github.com/facebookresearch/llama-agentic-system
  • 来源 | 子非AI

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

万有斥力

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表