• Meta 推出的 Llama as a System 将 Llama 3.1 模型转变为一个能够自主完成任务的智能代理,通过多步推理、工具使用和系统级安全机制,为构建更智能、更安全的 AI 应用开辟了新的可能性。
• Llama-Agentic-System 具备强大的功能,包括多步推理、工具使用(内置和零样本学习)以及系统级安全保障,能够处理更复杂的任务,并增强安全性。
•本文将深入探讨 Llama as a System 的概念、架构、功能和应用场景,并提供详细的代码示例和使用指南。
•多步推理:将复杂任务分解成多个步骤,并按照逻辑顺序执行。例如,要预订航班,模型需要先搜索航班信息,然后选择合适的航班,最后填写乘客信息并完成支付。
•工具使用:能够调用各种工具来完成任务,包括:
•内置工具:如搜索引擎、代码解释器等。这些工具预先集成到系统中,模型可以直接调用。
•零样本学习工具:可以通过上下文信息学习使用新的工具。这意味着即使模型之前没有见过某个工具,只要提供工具的使用说明,它就可以学会使用。
•系统级安全:将安全评估从模型级别提升到整个系统级别,通过 Llama Guard 等安全机制,确保系统在各种场景下的安全性。这包括对用户输入、模型输出以及工具调用进行安全检查和过滤,防止恶意攻击和不当内容的产生。
•User(用户): 与 Llama Agentic System 进行交互的用户,发起任务指令并接收最终结果。
•Executor(执行器): Llama Agentic System 的核心控制单元,负责接收用户输入,调用安全机制,并将任务分发给 LLM 或工具,最终将结果返回给用户。
•LLM(大型语言模型): Llama 模型,负责理解任务、生成文本、选择合适的工具来执行任务,是系统的智能核心。
•Tools(工具): 外部工具,如搜索引擎、代码解释器等,用于扩展 LLM 的功能,执行 LLM 无法直接完成的任务。
•Shields(安全机制): 负责对用户输入、模型输出以及工具调用进行安全检查和过滤,确保系统安全可靠地运行。
1. 用户将任务指令和相关信息发送给 Executor。
2. Executor 调用安全机制对用户输入进行检查,确保输入内容安全无害。
3. Executor 将任务指令发送给 LLM,LLM 分析指令并选择合适的工具(如果需要)。
4. LLM 根据任务指令选择合适的工具,并将调用请求发送给 Executor。
5. Executor 调用安全机制对工具调用进行检查,防止潜在的安全风险。
6. Executor 调用相应的工具,并将工具返回的结果发送给 LLM,LLM 继续处理任务。
7. LLM 整合工具返回的结果,生成最终的回复,并发送给 Executor。
8. Executor 调用安全机制对模型输出进行检查,确保输出内容安全可靠。
9. Executor 将最终的回复发送给用户,完成任务。
Llama Agentic System 的核心代码位于llama_agentic_system/agentic_system.py文件中。以下是一些关键代码片段和解释:
classAgentInstance(ShieldRunnerMixin):
def__init__(
self,
system_id:int,
instance_config:AgenticSystemInstanceConfig,
model:InstructModel,
inference_api:Inference,
builtin_tools
ist[SingleMessageBuiltinTool],
custom_tool_definitions
ist[ToolDefinition],
input_shields
ist[ShieldBase],
output_shields
ist[ShieldBase],
max_infer_iters:int=10,
prefix_messages:Optional[List[Message]]=None,
):
#...初始化代码...
#初始化内置工具字典
self.tools_dict={t.get_name():tfortinbuiltin_tools}
#初始化会话字典
self.sessions={}
#初始化安全机制
ShieldRunnerMixin.__init__(
self,
input_shields=input_shields,
output_shields=output_shields,
)
defcreate_session(self,name:str)->Session:
#...创建会话代码...AgentInstance类表示一个 Llama Agentic System 实例,负责管理会话、执行推理、调用工具和安全机制等。它是 Llama Agentic System 的核心控制单元,协调各个组件协同工作。
•它维护一个tools_dict字典,存储所有可用的内置工具,键为工具名,值为工具实例。
•它维护一个sessions字典,存储所有会话,键为会话 ID,值为会话实例。
•它使用ShieldRunnerMixin来管理输入和输出安全机制。
asyncdefcreate_and_execute_turn(
self,request:AgenticSystemTurnCreateRequest
)->AsyncGenerator:
#...获取会话,构建历史消息...
#...创建轮次ID,初始化参数...
#发送轮次开始事件
yieldAgenticSystemTurnResponseStreamChunk(
event=AgenticSystemTurnResponseEvent(
payload=AgenticSystemTurnResponseTurnStartPayload(
turn_id=turn_id,
)
)
)
steps=[]
output_message=None
asyncforchunkinself.run(
turn_id=turn_id,
input_messages=messages,
temperature=params.temperature,
top_p=params.top_p,
stream=request.stream,
max_gen_len=params.max_tokens,
):
#处理推理过程中的事件流
#...
#...断言output_message不为空...
#创建轮次实例
turn=Turn(
turn_id=turn_id,
session_id=request.session_id,
input_messages=request.messages,
output_message=output_message,
started_at=start_time,
completed_at=datetime.now(),
steps=steps,
)
#将轮次添加到会话中
session.turns.append(turn)
#发送轮次结束事件
yieldAgenticSystemTurnResponseStreamChunk(
event=AgenticSystemTurnResponseEvent(
payload=AgenticSystemTurnResponseTurnCompletePayload(
turn=turn,
)
)
)该方法负责创建一个新的会话轮次,并执行用户请求。它会根据用户输入调用 LLM 进行推理,并根据 LLM 的回复调用相应的工具。这个方法实现了 Llama Agentic System 的交互逻辑,处理用户输入并生成相应的输出。
•它首先获取对应的会话,并构建包含历史消息的消息列表。
•然后,它调用self.run()方法执行推理,并处理推理过程中产生的事件流。
•最后,它创建Turn实例表示当前轮次,并发送轮次结束事件。
asyncdefrun(
self,
turn_id:str,
input_messages
ist[Message],
temperature:float,
top_p:float,
stream:bool=False,
max_gen_len:Optional[int]=None,
)->AsyncGenerator:
#对用户输入调用安全机制
asyncforresinself.run_shields_wrapper(
turn_id,input_messages,self.input_shields,"user-input"
):
ifisinstance(res,bool):
return
else:
yieldres
#调用_run方法执行推理
asyncforresinself._run(
turn_id,input_messages,temperature,top_p,stream,max_gen_len
):
ifisinstance(res,bool):
return
elifisinstance(res,CompletionMessage):
final_response=res
break
else:
yieldres
#...断言final_response不为空...
#对模型输出调用安全机制
messages=input_messages+[final_response]
asyncforresinself.run_shields_wrapper(
turn_id,messages,self.output_shields,"assistant-output"
):
ifisinstance(res,bool):
return
else:
yieldres
yieldfinal_responserun方法是create_and_execute_turn方法的核心,它实现了 Llama Agentic System 的推理逻辑,包括调用 LLM、执行工具、处理安全机制等。该方法是 Llama Agentic System 智能的核心,实现了多步推理、工具使用和安全保障等关键功能。
•它首先对用户输入调用run_shields_wrapper方法进行安全检查。
•然后,它调用_run方法执行实际的推理过程,并处理推理过程中产生的事件流。
•最后,它对模型输出再次调用run_shields_wrapper方法进行安全检查。
asyncdef_run(
self,
turn_id:str,
input_messages
ist[Message],
temperature:float,
top_p:float,
stream:bool=False,
max_gen_len:Optional[int]=None,
)->AsyncGenerator:
#预处理消息,添加系统提示信息
input_messages=preprocess_dialog(input_messages,self.prefix_messages)
attachments=[]
n_iter=0
whileTrue:
#...获取最后一条消息,打印消息内容...
step_id=str(uuid.uuid4())
#发送推理步骤开始事件
yieldAgenticSystemTurnResponseStreamChunk(
event=AgenticSystemTurnResponseEvent(
payload=AgenticSystemTurnResponseStepStartPayload(
step_type=StepType.inference.value,
step_id=step_id,
)
)
)
#构建推理请求
req=ChatCompletionRequest(
model=self.model,
messages=input_messages,
available_tools=self.instance_config.available_tools,
stream=True,
sampling_params=SamplingParams(
temperature=temperature,
top_p=top_p,
max_tokens=max_gen_len,
),
)
tool_calls=[]
content=""
stop_reason=None
#调用推理接口,处理推理结果
asyncforchunkinself.inference_api.chat_completion(req):
#...处理推理结果...
#...处理推理结束原因...
#创建CompletionMessage实例
message=CompletionMessage(
content=content,
stop_reason=stop_reason,
tool_calls=tool_calls,
)
#发送推理步骤结束事件
yieldAgenticSystemTurnResponseStreamChunk(
event=AgenticSystemTurnResponseEvent(
payload=AgenticSystemTurnResponseStepCompletePayload(
step_type=StepType.inference.value,
step_id=step_id,
step_details=InferenceStep(
step_id=step_id,turn_id=turn_id,model_response=message
),
)
)
)
#...处理推理结束条件...
#...处理模型调用工具...
n_iter+=1_run方法是run方法的核心,它实现了 Llama Agentic System 的推理逻辑,包括调用 LLM、执行工具、处理安全机制等。
•它首先预处理消息,添加系统提示信息。
•然后,它进入一个循环,每次循环执行一次推理步骤,直到满足结束条件。
•在每个推理步骤中,它首先构建推理请求,然后调用self.inference_api.chat_completion()方法执行推理,并处理推理结果。
•如果模型需要调用工具,它会调用相应的工具,并将工具返回的结果添加到消息列表中。
Llama Agentic System 提供了一些 Demo 示例,展示了如何使用它来完成实际任务。以下是一些示例:
•代码路径:examples/scripts/inflation.py
•功能描述: 该示例展示了如何使用 Llama Agentic System 来分析通货膨胀数据。它首先加载一个 CSV 文件,然后使用 LLM 来回答有关通货膨胀的问题,例如“哪一年以最高的通货膨胀结束?”、“是什么宏观经济形势导致了该时期如此高的通货膨胀?”等等。这个示例展示了 Llama Agentic System 如何处理结构化数据,并利用工具进行数据分析。
importasyncio
importfire
fromllama_models.llama3_1.api.datatypesimport*#noqa:F403
fromcustom_tools.ticker_dataimportTickerDataTool
frommulti_turnimportprompt_to_message,run_main
#定义主函数
defmain(host:str,port:int,disable_safety:bool=False):
#使用asyncio运行异步主函数
asyncio.run(
run_main(
[
UserMessage(
content=[
"Hereisacsv,canyoudescribeit?",
Attachment(
url=URL(uri="file://examples/resources/inflation.csv"),
mime_type="text/csv",
),
],
),
prompt_to_message("Whichyearendedwiththehighestinflation?"),
prompt_to_message(
"Whatmacroeconomicsituationsthatledtosuchhighinflationinthatperiod?"
),
prompt_to_message("Plotaverageyearlyinflationasatimeseries"),
prompt_to_message(
"Usingprovidedfunctions,gettickerdataforMETAforthepast10years?plotpercentageyearoveryeargrowth"
),
prompt_to_message(
"CanyoutakeMeta'syearoveryeargrowthdataandputitinthesameinflationtimeseriesasabove?"
),
],
host=host,
port=port,
disable_safety=disable_safety,
custom_tools=[TickerDataTool()],
)
)
if__name__=="__main__":
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函数绑定到命令行接口,方便用户使用命令行参数运行程序。
•代码路径:examples/scripts/vacation.py
•功能描述: 该示例展示了如何使用 Llama Agentic System 来计划旅行。用户可以向系统提供一些旅行信息,例如目的地、时间等,系统会根据这些信息生成详细的旅行计划,包括景点推荐、路线规划、住宿建议等。这个示例展示了 Llama Agentic System 如何与用户进行多轮对话,并调用外部工具获取信息,最终完成复杂的任务。
importasyncio
importfire
frommulti_turnimportprompt_to_message,run_main
#定义主函数
defmain(host:str,port:int,disable_safety:bool=False):
asyncio.run(
run_main(
[
prompt_to_message(
"IamplanningatriptoSwitzerland,whatarethetop3placestovisit?"
),
prompt_to_message("Whatissospecialabout#1?"),
prompt_to_message("WhatothercountriesshouldIconsidertoclub?"),
prompt_to_message("HowmanydaysshouldIplanforineachcountry?"),
],
host=host,
port=port,
disable_safety=disable_safety,
)
)
#当脚本作为主程序运行时,使用fire库执行main函数
if__name__=="__main__":
fire.Fire(main)代码解读:
•导入必要的库,包括asyncio用于异步操作,fire用于命令行参数解析,以及multi_turn用于多轮对话。
•定义main函数,它是程序的入口点。
•它使用asyncio.run运行异步函数run_main。
•run_main函数接收一系列用户消息和参数,包括主机地址、端口号以及是否禁用安全机制。
•用户消息使用prompt_to_message函数将文本提示转换为用户消息。
•使用fire.Fire(main)将main函数绑定到命令行接口,方便用户使用命令行参数运行程序。
如果您对 Llama as a System 感兴趣,并想尝试使用它,可以按照以下步骤进行安装和配置:
#创建并激活虚拟环境
ENV=agentic_env
with-proxycondacreate-n$ENVpython=3.10
cd<path-to-llama-agentic-system-repo>
condaactivate$ENV
#安装所需包
pipinstall-rrequirements.txt
pipinstallllama-agentic-system
#安装bubblewrap
#...根据您的操作系统安装bubblewrap...
#测试安装
llama--help
#下载模型检查点
llamadownloadmeta-llama/Meta-Llama-3.1-8B-Instruct
llamadownloadmeta-llama/Meta-Llama-3.1-70B-Instruct
llamadownloadmeta-llama/Prompt-Guard-86M--ignore-patternsoriginal
llamadownloadmeta-llama/Llama-Guard-3-8B--ignore-patternsoriginal
#配置推理服务器
llamainferenceconfigure
#运行推理服务器
llamainferencestart
#配置AgenticSystem
llamaagentic_systemconfigure
#运行应用程序
mesopapp/main.py
#脚本交互
cd<path-to-llama-agentic-system>
condaactivate$ENV
llamainferencestart
pythonexamples/scripts/vacation.pylocalhost5000Llama as a System 为构建更智能、更安全的 AI 应用提供了强大的工具。通过将 Llama 模型与工具、安全机制相结合,我们可以构建能够解决更复杂问题的 AI 代理,并将其应用于更广泛的领域。
| 欢迎光临 链载Ai (https://www.lianzai.com/) | Powered by Discuz! X3.5 |