smolagents 文档
智能体
并获得增强的文档体验
开始使用
智能体
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 )
从 LLM 输出中解析动作
from_dict
< 来源 >( agent_dict: dict **kwargs ) → MultiStepAgent
从字典表示创建智能体。
from_folder
< 来源 >( folder: str | pathlib.Path **kwargs )
从本地文件夹加载智能体。
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 安装软件包时一样。
将在子类中实现
中断智能体执行。
provide_final_answer
< 来源 >( task: str images: list['PIL.Image.Image'] | None = None ) → str
根据智能体交互日志提供任务的最终答案。
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 (
bool
或str
, 可选) — 用作远程文件 HTTP 承载授权的令牌。如果未设置,将使用运行 `huggingface-cli login` 时生成的令牌(存储在 `~/.huggingface` 中)。 - create_pr (
bool
, 可选, 默认为False
) — 是创建 PR 上传文件还是直接提交。
将智能体上传到 Hub。
replay
< 来源 >( detailed: bool = 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
, 可选) — 智能体解决任务的最大步骤数。如果未提供,将使用智能体的默认值。
运行智能体执行给定任务。
save
< 来源 >( output_dir: str | pathlib.Path relative_path: str | None = None )
保存代理的相关代码文件。这会将代理的代码复制到 output_dir
中,并自动生成
- 一个
tools
文件夹,其中包含tools/{tool_name}.py
下每个工具的逻辑。 - 一个
managed_agents
文件夹,其中包含每个受管代理的逻辑。 - 一个
agent.json
文件,其中包含表示代理的字典。 - 一个
prompt.yaml
文件,其中包含代理使用的提示模板。 - 一个
app.py
文件,当代理使用agent.push_to_hub()
导出到 Space 时,提供代理的 UI。 - 一个
requirements.txt
文件,其中包含代理工具使用的模块名称(在检查其代码时检测到)
在 ReAct 框架中执行一步:代理思考、行动并观察结果。如果步骤不是最终步骤,则返回 None,否则返回最终答案。
将代理转换为字典表示。
创建代理结构的丰富树状可视化。
从内存中读取过去的 llm_outputs、actions 和 observations 或 errors,将其转换为一系列可作为 LLM 输入的消息。添加了一些关键字(如 PLAN、error 等)来帮助 LLM。
类 smolagents.CodeAgent
< source >( 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
< source >( agent_dict: dict **kwargs ) → CodeAgent
从字典表示创建 CodeAgent。
类 smolagents.ToolCallingAgent
< source >( 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 引擎的工具调用功能。
执行工具调用
< source >( tool_name: str arguments: dict[str, str] | str )
使用提供的参数执行工具或受管代理。
如果参数引用状态变量,则将其替换为状态中的实际值。
处理工具调用
< source >( chat_message: ChatMessage memory_step: ActionStep ) → ToolCall | ToolOutput
处理来自模型输出的工具调用并更新代理内存。
stream_to_gradio
smolagents.stream_to_gradio
< source >( 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
< source >( 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()
启动
< source >( share: bool = True **kwargs )
启动带有代理界面的 Gradio 应用程序。
上传文件
< source >( file file_uploads_log allowed_file_types = None )
上传文件并将其添加到会话状态中的上传文件列表。
文件保存到 self.file_upload_folder
文件夹。如果文件类型不被允许,则返回一条消息指示不允许的文件类型。
提示
类 smolagents.PromptTemplates
< source >( )
参数
- system_prompt (
str
) — 系统提示。 - planning (PlanningPromptTemplate) — 规划提示模板。
- managed_agent (ManagedAgentPromptTemplate) — 托管代理提示模板。
- final_answer (FinalAnswerPromptTemplate) — 最终答案提示模板。
代理的提示模板。
class smolagents.PlanningPromptTemplate
< source 来源 >( )
规划步骤的提示模板。
class smolagents.ManagedAgentPromptTemplate
< source >( )
托管代理的提示模板。
class smolagents.FinalAnswerPromptTemplate
< source >( )
最终答案的提示模板。
记忆
Smolagents 使用记忆来在多个步骤中存储信息。
class smolagents.AgentMemory
< source >( system_prompt: str )
代理的记忆,包含系统提示和代理采取的所有步骤。
此类用于存储代理的步骤,包括任务、动作和规划步骤。它允许重置记忆、检索简洁或完整的步骤信息,以及重放代理的步骤。
属性:
- system_prompt (
SystemPromptStep
) — 代理的系统提示步骤。 - steps (
list[TaskStep | ActionStep | PlanningStep]
) — 代理采取的步骤列表,可以包括任务、动作和规划步骤。
返回代理步骤的完整表示,包括模型输入消息。
返回代理步骤的简洁表示,不包括模型输入消息。
replay
< source >( logger: AgentLogger detailed: bool = False )
打印智能体步骤的漂亮回放。
重置代理的记忆,清除所有步骤并保留系统提示。
返回代理步骤中的所有代码操作,连接成一个脚本。
Python 代码执行器
本地 Python 执行器
class smolagents.LocalPythonExecutor
< source >( additional_authorized_imports: list max_print_outputs_length: int | None = None additional_functions: dict[str, collections.abc.Callable] | None = None )
本地环境中 Python 代码的执行器。
此执行器评估 Python 代码,并限制对导入和内置函数的访问,使其适用于运行不受信任的代码。它在执行之间维护状态,允许自定义工具和函数可用于代码,并将打印输出与返回值分开捕获。
远程 Python 执行器
class smolagents.remote_executors.RemotePythonExecutor
< source >( additional_imports: list logger )
执行代码,返回结果和输出,并确定结果是否为最终答案。
使用 pickle 将变量发送到内核命名空间。
E2BExecutor
class smolagents.E2BExecutor
< source >( additional_imports: list logger **kwargs )
使用 E2B 执行 Python 代码。
清理 E2B 沙盒和资源。
DockerExecutor
class smolagents.DockerExecutor
< source >( 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
< source >( additional_imports: list logger deno_path: str = 'deno' deno_permissions: list[str] | None = None timeout: int = 60 )
在沙盒 WebAssembly 环境中运行的远程 Python 代码执行器,由 Pyodide 和 Deno 提供支持。
此执行器结合了 Deno 的安全运行时和 Pyodide 编译的 WebAssembly Python 解释器,以提供强大的隔离保证,同时实现完整的 Python 执行。
清理执行器使用的资源。
确保删除时进行清理。
安装包
< source >( additional_imports: list ) → list[str]
在 Pyodide 环境中安装额外的 Python 包。
run_code_raise_errors
< source >( code: str ) → CodeOutput
在 Pyodide 环境中执行 Python 代码并返回结果。