smolagents 文档

智能体

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

智能体

Smolagents 是一个实验性 API,可能随时更改。由于 API 或底层模型容易发生变化,智能体返回的结果可能有所不同。

要了解更多关于智能体和工具的信息,请务必阅读入门指南。本页面包含底层类的 API 文档。

智能体

我们的智能体继承自 MultiStepAgent,这意味着它们可以分多步执行,每一步包括一个思考、一个工具调用和执行。更多信息请阅读本概念指南

我们提供两种类型的智能体,基于主要的 `Agent` 类。

  • CodeAgent 用 Python 代码编写其工具调用(这是默认设置)。
  • ToolCallingAgent 用 JSON 编写其工具调用。

两者在初始化时都需要 `model` 参数和工具列表 `tools`。

智能体类别

smolagents.MultiStepAgent

< >

( tools: list model: Model prompt_templates: smolagents.agents.PromptTemplates | None = None instructions: str | None = None max_steps: int = 20 add_base_tools: bool = False verbosity_level: LogLevel = <LogLevel.INFO: 1> managed_agents: list | None = None step_callbacks: list[collections.abc.Callable] | dict[typing.Type[smolagents.memory.MemoryStep], collections.abc.Callable | list[collections.abc.Callable]] | None = None planning_interval: int | None = None name: str | None = None description: str | None = None provide_run_summary: bool = False final_answer_checks: list[collections.abc.Callable] | None = None return_full_result: bool = False logger: smolagents.monitoring.AgentLogger | None = None )

参数

  • tools (list[Tool]) — 智能体可使用的工具
  • model (Callable[[list[dict[str, str]]], ChatMessage]) — 将生成智能体动作的模型。
  • prompt_templates (PromptTemplates, 可选) — 提示模板。
  • instructions (str, 可选) — 智能体的自定义指令,将插入到系统提示中。
  • max_steps (int, 默认值 20) — 智能体解决任务的最大步骤数。
  • add_base_tools (bool, 默认值 False) — 是否将基础工具添加到智能体的工具中。
  • verbosity_level (LogLevel, 默认值 LogLevel.INFO) — 智能体日志的详细程度。
  • managed_agents (list, 可选) — 智能体可以调用的托管智能体。
  • step_callbacks (list[Callable] | dict[Type[MemoryStep], Callable | list[Callable]], 可选) — 每一步将调用的回调。
  • planning_interval (int, 可选) — 智能体运行规划步骤的间隔。
  • name (str, 可选) — 仅对于托管智能体来说是必要的——该智能体可以被调用的名称。
  • description (str, 可选) — 仅对于托管智能体来说是必要的——该智能体的描述。
  • provide_run_summary (bool, 可选) — 当作为托管智能体调用时,是否提供运行摘要。
  • final_answer_checks (list[Callable], 可选) — 接受最终答案前要运行的验证函数列表。每个函数都应:
    • 将最终答案和智能体的内存作为参数。
    • 返回一个布尔值,指示最终答案是否有效。

智能体类,使用 ReAct 框架逐步解决给定任务:当目标未达成时,智能体将执行一个动作(由 LLM 提供)和观察(从环境中获取)的循环。

extract_action

< >

( model_output: str split_token: str )

参数

  • model_output (str) — LLM 的输出
  • split_token (str) — 动作的分隔符。应与系统提示中的示例匹配。

从 LLM 输出中解析动作

from_dict

< >

( agent_dict: dict **kwargs ) MultiStepAgent

参数

  • agent_dict (dict[str, Any]) — 智能体的字典表示。
  • **kwargs — 将覆盖 `agent_dict` 值的额外关键字参数。

返回

多步骤智能体

智能体类的实例。

从字典表示创建智能体。

from_folder

< >

( folder: str | pathlib.Path **kwargs )

参数

  • folder (strPath) — 智能体保存的文件夹。
  • **kwargs — 将传递给智能体 init 的额外关键字参数。

从本地文件夹加载智能体。

from_hub

< >

( repo_id: str token: str | None = None trust_remote_code: bool = False **kwargs )

参数

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

从 Hub 加载已定义的智能体。

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

initialize_system_prompt

< >

( )

将在子类中实现

interrupt

< >

( )

中断智能体执行。

provide_final_answer

< >

( task: str images: list['PIL.Image.Image'] | None = None ) str

参数

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

返回

字符串

任务的最终答案。

根据智能体交互日志提供任务的最终答案。

push_to_hub

< >

( repo_id: str commit_message: str = 'Upload agent' private: bool | None = None token: bool | str | None = None create_pr: bool = False )

参数

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

将智能体上传到 Hub。

replay

< >

( detailed: bool = False )

参数

  • detailed (布尔值, 可选) — 如果为 True,则还显示每一步的内存。默认为 False。注意:将指数级增加日志长度。仅用于调试。

打印智能体步骤的漂亮回放。

run

< >

( task: str stream: bool = False reset: bool = True images: list['PIL.Image.Image'] | None = None additional_args: dict | None = None max_steps: int | None = None )

参数

  • task (str) — 要执行的任务。
  • stream (bool) — 是否以流模式运行。如果为 `True`,则返回一个生成器,该生成器在执行每个步骤时生成该步骤。您必须遍历此生成器才能处理单个步骤(例如,使用 for 循环或 `next()`)。如果为 `False`,则在内部执行所有步骤,并在完成后仅返回最终答案。
  • 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: str | None = None )

参数

  • 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 文件,其中包含代理工具使用的模块名称(在检查其代码时检测到)

步骤

< >

( memory_step: ActionStep )

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

to_dict

< >

( ) dict

返回

字典

代理的字典表示。

将代理转换为字典表示。

可视化

< >

( )

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

将内存写入消息

< >

( summary_mode: bool = False )

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

smolagents.CodeAgent

< >

( tools: list model: Model prompt_templates: smolagents.agents.PromptTemplates | None = None additional_authorized_imports: list[str] | None = None planning_interval: int | None = None executor_type: typing.Literal['local', 'e2b', 'docker', 'wasm'] = 'local' executor_kwargs: dict[str, typing.Any] | None = None max_print_outputs_length: int | None = None stream_outputs: bool = False use_structured_outputs_internally: bool = False code_block_tags: str | tuple[str, str] | None = None **kwargs )

参数

  • tools (list[Tool]) — 代理可使用的 工具
  • model (Model) — 将生成代理动作的模型。
  • prompt_templates (PromptTemplates, 可选) — 提示模板。
  • additional_authorized_imports (list[str], 可选) — 代理的其他授权导入。
  • planning_interval (int, 可选) — 代理运行规划步骤的间隔。
  • executor_type (Literal["local", "e2b", "docker", "wasm"], 默认 "local") — 代码执行器的类型。
  • executor_kwargs (dict, 可选) — 传递给初始化执行器的附加参数。
  • max_print_outputs_length (int, 可选) — 打印输出的最大长度。
  • stream_outputs (bool, 可选, 默认 False) — 执行期间是否流式输出。
  • use_structured_outputs_internally (bool, 默认 False) — 是否在每个操作步骤中使用结构化生成:这可以提高许多模型的性能。

    添加于 1.17.0 版本

  • code_block_tags (tuple[str, str] | Literal["markdown"], 可选) — 代码块的开始和结束标签(正则表达式字符串)。可以传递自定义元组,或者传递“markdown”以使用(“(?:python|py)", "\n”),留空则使用(“”, ””)。
  • **kwargs — 额外的关键字参数。

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

清理

< >

( )

清理代理使用的资源,例如远程 Python 执行器。

from_dict

< >

( agent_dict: dict **kwargs ) CodeAgent

参数

  • agent_dict (dict[str, Any]) — 代理的字典表示。
  • **kwargs — 额外的关键字参数,将覆盖 agent_dict 中的值。

返回

代码代理

CodeAgent 类的实例。

从字典表示创建 CodeAgent。

smolagents.ToolCallingAgent

< >

( tools: list model: Model prompt_templates: smolagents.agents.PromptTemplates | None = None planning_interval: int | None = None stream_outputs: bool = False max_tool_threads: int | None = None **kwargs )

参数

  • tools (list[Tool]) — 代理可使用的 工具
  • model (Model) — 将生成代理动作的模型。
  • prompt_templates (PromptTemplates, 可选) — 提示模板。
  • planning_interval (int, 可选) — 代理运行规划步骤的间隔。
  • stream_outputs (bool, 可选, 默认 False) — 执行期间是否流式输出。
  • max_tool_threads (int, 可选) — 并行工具调用的最大线程数。值越高,并发性越高,但资源使用也越高。默认为 ThreadPoolExecutor 的默认值。
  • **kwargs — 额外的关键字参数。

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

执行工具调用

< >

( tool_name: str arguments: dict[str, str] | str )

参数

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

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

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

处理工具调用

< >

( chat_message: ChatMessage memory_step: ActionStep ) ToolCall | ToolOutput

参数

  • chat_message (ChatMessage) — 包含模型工具调用的聊天消息。
  • memory_step (ActionStep) — 要用结果更新的内存 ActionStep。

产生

工具调用 | 工具输出

处理来自模型输出的工具调用并更新代理内存。

stream_to_gradio

smolagents.stream_to_gradio

< >

( agent task: str task_images: list | None = None reset_agent_memory: bool = False additional_args: dict | None = None )

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

GradioUI

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

smolagents.GradioUI

< >

( agent: MultiStepAgent file_upload_folder: str | None = None reset_agent_memory: bool = False )

参数

  • agent (MultiStepAgent) — 交互的代理。
  • file_upload_folder (str, 可选) — 上传文件将保存到的文件夹。如果未提供,文件上传将被禁用。
  • reset_agent_memory (bool, 可选, 默认为 False) — 是否在每次交互开始时重置代理的内存。如果为 True,代理将不会记住之前的交互。

引发

ModuleNotFoundError

  • ModuleNotFoundError — 如果未安装 gradio 扩展。

用于与 MultiStepAgent 交互的 Gradio 接口。

此类提供了一个 Web 界面,用于与代理进行实时交互,允许用户提交提示、上传文件,并以聊天式格式接收响应。如果需要,它可以在每次交互开始时重置代理的内存。它支持文件上传,文件将保存到指定的文件夹。它使用 gradio.Chatbot 组件显示对话历史记录。此类需要安装 gradio 扩展:smolagents[gradio]

示例

from smolagents import CodeAgent, GradioUI, InferenceClientModel

model = InferenceClientModel(model_id="meta-llama/Meta-Llama-3.1-8B-Instruct")
agent = CodeAgent(tools=[], model=model)
gradio_ui = GradioUI(agent, file_upload_folder="uploads", reset_agent_memory=True)
gradio_ui.launch()

启动

< >

( share: bool = True **kwargs )

参数

  • share (bool, 默认为 True) — 是否公开共享应用程序。
  • **kwargs — 传递给 Gradio 启动方法的额外关键字参数。

启动带有代理界面的 Gradio 应用程序。

上传文件

< >

( file file_uploads_log allowed_file_types = None )

参数

  • file (gradio.File) — 上传的文件。
  • file_uploads_log (list) — 用于记录上传文件的列表。
  • allowed_file_types (list, 可选) — 允许的文件扩展名列表。默认为 [“.pdf”, “.docx”, “.txt”]。

上传文件并将其添加到会话状态中的上传文件列表。

文件保存到 self.file_upload_folder 文件夹。如果文件类型不被允许,则返回一条消息指示不允许的文件类型。

提示

smolagents.PromptTemplates

< >

( )

参数

代理的提示模板。

class smolagents.PlanningPromptTemplate

< 来源 >

( )

参数

  • plan (str) — 初始计划提示。
  • update_plan_pre_messages (str) — 更新计划预消息提示。
  • update_plan_post_messages (str) — 更新计划后消息提示。

规划步骤的提示模板。

class smolagents.ManagedAgentPromptTemplate

< >

( )

参数

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

托管代理的提示模板。

class smolagents.FinalAnswerPromptTemplate

< >

( )

参数

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

最终答案的提示模板。

记忆

Smolagents 使用记忆来在多个步骤中存储信息。

class smolagents.AgentMemory

< >

( system_prompt: str )

参数

  • system_prompt (str) — 代理的系统提示,设置代理行为的上下文和指令。

代理的记忆,包含系统提示和代理采取的所有步骤。

此类用于存储代理的步骤,包括任务、动作和规划步骤。它允许重置记忆、检索简洁或完整的步骤信息,以及重放代理的步骤。

属性:

  • system_prompt (SystemPromptStep) — 代理的系统提示步骤。
  • steps (list[TaskStep | ActionStep | PlanningStep]) — 代理采取的步骤列表,可以包括任务、动作和规划步骤。

get_full_steps

< >

( )

返回代理步骤的完整表示,包括模型输入消息。

get_succinct_steps

< >

( )

返回代理步骤的简洁表示,不包括模型输入消息。

replay

< >

( logger: AgentLogger detailed: bool = False )

参数

  • logger (AgentLogger) — 用于打印回放日志的日志记录器。
  • detailed (bool, 默认值 False) — 如果为 True,则还会在每个步骤显示内存。默认为 False。注意:这将使日志长度呈指数级增长。仅用于调试。

打印智能体步骤的漂亮回放。

重置

< >

( )

重置代理的记忆,清除所有步骤并保留系统提示。

return_full_code

< >

( )

返回代理步骤中的所有代码操作,连接成一个脚本。

Python 代码执行器

class smolagents.PythonExecutor

< >

( )

本地 Python 执行器

class smolagents.LocalPythonExecutor

< >

( additional_authorized_imports: list max_print_outputs_length: int | None = None additional_functions: dict[str, collections.abc.Callable] | None = None )

参数

  • additional_authorized_imports (list[str]) — 执行器的额外授权导入。
  • max_print_outputs_length (int, 默认为 DEFAULT_MAX_LEN_OUTPUT=50_000) — 打印输出的最大长度。
  • additional_functions (dict[str, Callable], 可选) — 要添加到执行器的额外 Python 函数。

本地环境中 Python 代码的执行器。

此执行器评估 Python 代码,并限制对导入和内置函数的访问,使其适用于运行不受信任的代码。它在执行之间维护状态,允许自定义工具和函数可用于代码,并将打印输出与返回值分开捕获。

远程 Python 执行器

class smolagents.remote_executors.RemotePythonExecutor

< >

( additional_imports: list logger )

run_code_raise_errors

< >

( code: str )

执行代码,返回结果和输出,并确定结果是否为最终答案。

send_variables

< >

( variables: dict )

使用 pickle 将变量发送到内核命名空间。

E2BExecutor

class smolagents.E2BExecutor

< >

( additional_imports: list logger **kwargs )

参数

  • additional_imports (list[str]) — 要安装的额外导入。
  • logger (Logger) — 要使用的日志记录器。
  • **kwargs — 传递给 E2B 沙盒的额外参数。

使用 E2B 执行 Python 代码。

清理

< >

( )

清理 E2B 沙盒和资源。

DockerExecutor

class smolagents.DockerExecutor

< >

( additional_imports: list logger host: str = '127.0.0.1' port: int = 8888 image_name: str = 'jupyter-kernel' build_new_image: bool = True container_run_kwargs: dict[str, typing.Any] | None = None )

使用 Docker 容器中的 Jupyter Kernel Gateway 执行 Python 代码。

清理

< >

( )

清理 Docker 容器和资源。

删除

< >

( )

确保删除时进行清理。

WasmExecutor

class smolagents.WasmExecutor

< >

( additional_imports: list logger deno_path: str = 'deno' deno_permissions: list[str] | None = None timeout: int = 60 )

参数

  • additional_imports (list[str]) — 要在 Pyodide 环境中安装的额外 Python 包。
  • logger (Logger) — 用于输出和错误的日志记录器。
  • deno_path (str, 可选) — Deno 可执行文件的路径。如果未提供,将使用 PATH 中的“deno”。
  • deno_permissions (list[str], 可选) — 授予 Deno 运行时的权限列表。默认是执行所需的最小权限。
  • timeout (int, 可选) — 代码执行的超时时间(秒)。默认是 60 秒。

在沙盒 WebAssembly 环境中运行的远程 Python 代码执行器,由 Pyodide 和 Deno 提供支持。

此执行器结合了 Deno 的安全运行时和 Pyodide 编译的 WebAssembly Python 解释器,以提供强大的隔离保证,同时实现完整的 Python 执行。

清理

< >

( )

清理执行器使用的资源。

删除

< >

( )

确保删除时进行清理。

安装包

< >

( additional_imports: list ) list[str]

参数

  • additional_imports (list[str]) — 要安装的包名称。

返回

list[str]

已安装的包。

在 Pyodide 环境中安装额外的 Python 包。

run_code_raise_errors

< >

( code: str ) CodeOutput

参数

  • code (str) — 要执行的 Python 代码。

返回

代码输出

包含结果、日志以及是否为最终答案的代码输出。

在 Pyodide 环境中执行 Python 代码并返回结果。

< > 在 GitHub 上更新