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 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.