smolagents 文档 (smolagents documentation)

智能体 (Agents)

Hugging Face's logo
加入 Hugging Face 社区 (Join the Hugging Face community)

并获得增强的文档体验 (and get access to the augmented documentation experience)

开始使用 (to get started)

智能体 (Agents)

Smolagents 是一个实验性的 API,随时可能更改。由于 API 或底层模型容易发生变化,智能体返回的结果可能会有所不同。(Smolagents is an experimental API which is subject to change at any time. Results returned by the agents can vary as the APIs or underlying models are prone to change.)

要了解有关智能体和工具的更多信息,请务必阅读入门指南。此页面包含底层类的 API 文档。(To learn more about agents and tools make sure to read the introductory guide. This page contains the API docs for the underlying classes.)

智能体 (Agents)

我们的智能体继承自 MultiStepAgent,这意味着它们可以分多个步骤执行操作,每个步骤都包含一个思考,然后是一个工具调用和执行。在本概念指南中阅读更多内容。(Our agents inherit from MultiStepAgent, which means they can act in multiple steps, each step consisting of one thought, then one tool call and execution. Read more in this conceptual guide.)

我们提供两种类型的智能体,基于主要的 Agent 类。(We provide two types of agents, based on the main Agent class.)

  • CodeAgent 是默认智能体,它用 Python 代码编写其工具调用。(CodeAgent is the default agent, it writes its tool calls in Python code.)
  • ToolCallingAgent 以 JSON 格式编写其工具调用。(ToolCallingAgent writes its tool calls in JSON.)

两者都需要在初始化时提供参数 model 和工具列表 tools。(Both require arguments model and list of tools tools at initialization.)

智能体类别 (Classes of agents)

class smolagents.MultiStepAgent

< >

( tools: typing.List[smolagents.tools.Tool] model: typing.Callable[[typing.List[typing.Dict[str, str]]], smolagents.models.ChatMessage] prompt_templates: typing.Optional[smolagents.agents.PromptTemplates] = None max_steps: int = 20 add_base_tools: bool = False verbosity_level: LogLevel = <LogLevel.INFO: 1> grammar: typing.Optional[typing.Dict[str, str]] = None managed_agents: typing.Optional[typing.List] = None step_callbacks: typing.Optional[typing.List[typing.Callable]] = None planning_interval: typing.Optional[int] = None name: typing.Optional[str] = None description: typing.Optional[str] = None provide_run_summary: bool = False final_answer_checks: typing.Optional[typing.List[typing.Callable]] = None )

参数 (Parameters)

  • tools (list[Tool]) — 智能体可以使用的 工具 (Tool)
  • model (Callable[[list[dict[str, str]]], ChatMessage]) — 将生成智能体操作的模型 (Model that will generate the agent’s actions.)。
  • prompt_templates (PromptTemplates, 可选 (optional)) — Prompt 模板 (Prompt templates)。
  • max_steps (int, 默认 20) — 智能体解决任务可以采取的最大步骤数 (Maximum number of steps the agent can take to solve the task.)。
  • tool_parser (Callable, 可选 (optional)) — 用于解析来自 LLM 输出的工具调用的函数 (Function used to parse the tool calls from the LLM output.)。
  • add_base_tools (bool, 默认 False) — 是否将基本工具添加到智能体的工具中 (Whether to add the base tools to the agent’s tools.)。
  • verbosity_level (LogLevel, 默认 LogLevel.INFO) — 智能体日志的详细程度级别 (Level of verbosity of the agent’s logs.)。
  • grammar (dict[str, str], 可选 (optional)) — 用于解析 LLM 输出的语法 (Grammar used to parse the LLM output.)。
  • managed_agents (list, 可选 (optional)) — 智能体可以调用的受管智能体 (Managed agents that the agent can call.)。
  • step_callbacks (list[Callable], 可选 (optional)) — 将在每个步骤调用的回调函数 (Callbacks that will be called at each step.)。
  • planning_interval (int, 可选 (optional)) — 智能体运行规划步骤的间隔 (Interval at which the agent will run a planning step.)。
  • name (str, 可选 (optional)) — 仅当为受管智能体时才需要 - 此智能体可以被调用的名称 (Necessary for a managed agent only - the name by which this agent can be called.)。
  • description (str, 可选 (optional)) — 仅当为受管智能体时才需要 - 此智能体的描述 (Necessary for a managed agent only - the description of this agent.)。
  • provide_run_summary (bool, 可选 (optional)) — 当作为受管智能体调用时是否提供运行摘要 (Whether to provide a run summary when called as a managed agent.)。
  • final_answer_checks (list, 可选 (optional)) — 在返回最终答案以检查有效性之前要运行的 Callable 列表 (List of Callables to run before returning a final answer for checking validity.)。

智能体类,它使用 ReAct 框架逐步解决给定的任务:在未达到目标之前,智能体将执行一个操作循环(由 LLM 给出)和观察(从环境中获得)。(Agent class that solves the given task step by step, using the ReAct framework: While the objective is not reached, the agent will perform a cycle of action (given by the LLM) and observation (obtained from the environment).)

extract_action

< >

( model_output: str split_token: str )

参数 (Parameters)

  • model_output (str) — LLM 的输出 (Output of the LLM)
  • split_token (str) — 操作的分隔符 (Separator for the action)。应与系统提示中的示例匹配 (Should match the example in the system prompt.)。

从 LLM 输出中解析操作 (Parse action from the LLM output)

from_folder

< >

( folder: typing.Union[str, pathlib.Path] **kwargs )

参数 (Parameters)

  • folder (strPath) — 保存智能体的文件夹 (The folder where the agent is saved.)。
  • **kwargs — 将传递给智能体 init 的其他关键字参数 (Additional keyword arguments that will be passed to the agent’s init.)。

从本地文件夹加载智能体。(Loads an agent from a local folder.)

from_hub

< >

( repo_id: str token: typing.Optional[str] = None trust_remote_code: bool = False **kwargs )

参数 (Parameters)

  • repo_id (str) — Hub 上仓库的名称,您的工具定义于此仓库中。
  • token (str, 可选) — 用于在 hf.co 上标识您的令牌。如果未设置,将使用运行 huggingface-cli login 时生成的令牌(存储在 ~/.huggingface 中)。
  • trust_remote_code(bool, 可选,默认为 False) — 此标志表示您理解运行远程代码的风险,并且您信任此工具。如果不将其设置为 True,则从 Hub 加载工具将失败。
  • kwargs (附加关键字参数,可选) — 将拆分为两部分的附加关键字参数:所有与 Hub 相关的参数(例如 cache_dirrevisionsubfolder)将在下载代理文件时使用,其他参数将传递给其 init 方法。

加载 Hub 上定义的代理。

从 Hub 加载工具意味着您将下载该工具并在本地执行它。 始终在运行时加载工具之前检查您要下载的工具,就像您在使用 pip/npm/apt 安装软件包时一样。

initialize_system_prompt

< >

( )

将在子类中实现

interrupt

< >

( )

中断代理执行。

provide_final_answer

< >

( task: str images: typing.Optional[list['PIL.Image.Image']] ) str

参数 (Parameters)

  • task (str) — 要执行的任务。
  • images (list[PIL.Image.Image], 可选) — 图像对象。

返回值

str

任务的最终答案。

根据代理交互的日志,提供任务的最终答案。

push_to_hub

< >

( repo_id: str commit_message: str = 'Upload agent' private: typing.Optional[bool] = None token: typing.Union[bool, str, NoneType] = None create_pr: bool = False )

参数 (Parameters)

  • repo_id (str) — 您要推送到的仓库的名称。当推送到给定的组织时,它应该包含您的组织名称。
  • commit_message (str, 可选,默认为 "Upload agent") — 推送时提交的消息。
  • private (bool, 可选,默认为 None) — 是否将仓库设为私有。如果为 None,则仓库将是公开的,除非组织的默认设置为私有。如果仓库已存在,则忽略此值。
  • token (boolstr, 可选) — 用作远程文件的 HTTP Bearer 授权的令牌。如果未设置,将使用运行 huggingface-cli login 时生成的令牌(存储在 ~/.huggingface 中)。
  • create_pr (bool, 可选,默认为 False) — 是否创建包含上传文件的 PR 或直接提交。

将代理上传到 Hub。

replay

< >

( detailed: bool = False )

参数 (Parameters)

  • detailed (bool, 可选) — 如果为 True,还会在每个步骤显示内存。默认为 False。注意:将成倍增加日志长度。仅用于调试。

打印代理步骤的美观回放。

run

< >

( task: str stream: bool = False reset: bool = True images: typing.Optional[typing.List[ForwardRef('PIL.Image.Image')]] = None additional_args: typing.Optional[typing.Dict] = None max_steps: typing.Optional[int] = None )

参数 (Parameters)

  • task (str) — 要执行的任务。
  • stream (bool) — 是否以流式方式运行。
  • reset (bool) — 是否重置对话或从上次运行继续。
  • images (list[PIL.Image.Image], 可选) — 图像对象。
  • additional_args (dict, 可选) — 您想要传递给代理运行的任何其他变量,例如图像或数据帧。给它们清晰的名称!
  • max_steps (int, 可选) — 代理可以为解决任务而采取的最大步骤数。如果未提供,将使用代理的默认值。

运行代理以执行给定的任务。

示例

from smolagents import CodeAgent
agent = CodeAgent(tools=[])
agent.run("What is the result of 2 power 3.7384?")

save

< >

( output_dir: str | pathlib.Path relative_path: typing.Optional[str] = None )

参数 (Parameters)

  • output_dir (strPath) — 您想要在其中保存代理的文件夹。

保存代理的相关代码文件。这会将代理的代码复制到 output_dir 中,并自动生成

  • 一个 tools 文件夹,其中包含 tools/{tool_name}.py 下每个工具的逻辑。
  • 一个 managed_agents 文件夹,其中包含每个托管代理的逻辑。
  • 一个 agent.json 文件,其中包含表示您的代理的字典。
  • 一个 prompt.yaml 文件,其中包含您的代理使用的提示模板。
  • 一个 app.py 文件,当您的代理使用 agent.push_to_hub() 导出到 Space 时,为其提供 UI。
  • 一个 requirements.txt,其中包含您的工具使用的模块名称(在检查其代码时检测到)。

step

< >

( memory_step: ActionStep )

将在子类中实现。如果步骤不是最终步骤,则应返回 None。

to_dict

< >

( ) dict

返回值

dict

代理的字典表示形式。

将代理转换为字典表示形式。

visualize

< >

( )

创建代理结构的富树形可视化。

write_memory_to_messages

< >

( summary_mode: typing.Optional[bool] = False )

从内存中读取过去的 llm_outputs、actions 和 observations 或 errors,并将其转换为一系列消息,这些消息可以用作 LLM 的输入。添加一些关键词(例如 PLAN、error 等)以帮助 LLM。

class smolagents.CodeAgent

< >

( tools: typing.List[smolagents.tools.Tool] model: typing.Callable[[typing.List[typing.Dict[str, str]]], smolagents.models.ChatMessage] prompt_templates: typing.Optional[smolagents.agents.PromptTemplates] = None grammar: typing.Optional[typing.Dict[str, str]] = None additional_authorized_imports: typing.Optional[typing.List[str]] = None planning_interval: typing.Optional[int] = None executor_type: str | None = 'local' executor_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None max_print_outputs_length: typing.Optional[int] = None **kwargs )

参数 (Parameters)

  • tools (list[Tool]) — 代理可以使用的工具列表。
  • model (Callable[[list[dict[str, str]]], ChatMessage]) — 将生成代理行为的模型。
  • prompt_templates (PromptTemplates, optional) — Prompt 模板。
  • grammar (dict[str, str], optional) — 用于解析 LLM 输出的语法。
  • additional_authorized_imports (list[str], optional) — 代理的其他授权导入。
  • planning_interval (int, optional) — 代理运行规划步骤的间隔。
  • executor_type (str, default "local") — 使用哪种执行器类型,选项包括 "local""e2b""docker"
  • executor_kwargs (dict, optional) — 传递给初始化执行器的其他参数。
  • max_print_outputs_length (int, optional) — 打印输出的最大长度。
  • **kwargs — 附加的关键字参数。

在此代理中,工具调用将由 LLM 以代码格式制定,然后进行解析和执行。

step

< >

( memory_step: ActionStep )

在 ReAct 框架中执行一个步骤:代理思考、行动并观察结果。如果步骤不是最终步骤,则返回 None。

class smolagents.ToolCallingAgent

< >

( tools: typing.List[smolagents.tools.Tool] model: typing.Callable[[typing.List[typing.Dict[str, str]]], smolagents.models.ChatMessage] prompt_templates: typing.Optional[smolagents.agents.PromptTemplates] = None planning_interval: typing.Optional[int] = None **kwargs )

参数 (Parameters)

  • tools (list[Tool]) — 代理可以使用的工具列表。
  • model (Callable[[list[dict[str, str]]], ChatMessage]) — 将生成代理行为的模型。
  • prompt_templates (PromptTemplates, optional) — Prompt 模板。
  • planning_interval (int, optional) — 代理运行规划步骤的间隔。
  • **kwargs — 附加的关键字参数。

此代理使用类似 JSON 的工具调用,使用方法 model.get_tool_call 来利用 LLM 引擎的工具调用功能。

execute_tool_call

< >

( tool_name: str arguments: typing.Union[typing.Dict[str, str], str] )

参数 (Parameters)

  • tool_name (str) — 要执行的工具或托管代理的名称。
  • arguments (dict[str, str] | str) — 传递给工具调用的参数。

使用提供的参数执行工具或托管代理。

如果参数引用状态变量,则这些参数将被状态中的实际值替换。

step

< >

( memory_step: ActionStep )

在 ReAct 框架中执行一个步骤:代理思考、行动并观察结果。如果步骤不是最终步骤,则返回 None。

ManagedAgent

此类已自 1.8.0 版本起弃用:现在您只需将属性 namedescription 传递给普通代理,即可使其可由管理器代理调用。

stream_to_gradio

smolagents.stream_to_gradio

< >

( agent task: str reset_agent_memory: bool = False additional_args: typing.Optional[dict] = None )

使用给定的任务运行代理,并将来自代理的消息作为 gradio ChatMessages 流式传输。

GradioUI

您必须安装 gradio 才能使用 UI。如果尚未安装,请运行 pip install smolagents[gradio]

class smolagents.GradioUI

< >

( agent: MultiStepAgent file_upload_folder: str | None = None )

在 Gradio 中启动代理的单行界面

upload_file

< >

( file file_uploads_log allowed_file_types = None )

处理文件上传,默认允许的文件类型为 .pdf、.docx 和 .txt

提示词

class smolagents.PromptTemplates

< >

( )

参数 (Parameters)

代理的提示模板。

class smolagents.PlanningPromptTemplate

< >

( )

参数 (Parameters)

  • initial_facts (str) — 初始事实提示。
  • initial_plan (str) — 初始计划提示。
  • update_facts_pre_messages (str) — 更新事实前消息提示。
  • update_facts_post_messages (str) — 更新事实后消息提示。
  • update_plan_pre_messages (str) — 更新计划前消息提示。
  • update_plan_post_messages (str) — 更新计划后消息提示。

规划步骤的提示模板。

class smolagents.ManagedAgentPromptTemplate

< >

( )

参数 (Parameters)

  • task (str) — 任务提示。
  • report (str) — 报告提示。

受管代理的提示模板。

class smolagents.FinalAnswerPromptTemplate

< >

( )

参数 (Parameters)

  • pre_messages (str) — 前消息提示。
  • post_messages (str) — 后消息提示。

最终答案的提示模板。

< > 在 GitHub 上更新