smolagents 文件

模型

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

模型

Smolagents 是一個實驗性 API,可能隨時更改。由於 API 或底層模型容易發生變化,智慧體返回的結果可能有所不同。

要了解更多關於智慧體和工具的資訊,請務必閱讀入門指南。本頁面包含底層類的 API 文件。

模型

您的自定義模型

您可以自由建立和使用自己的模型來驅動您的 Agent。

您可以對基類 Model 進行子類化,為您的 Agent 建立一個模型。主要標準是對 generate 方法進行子類化,並滿足以下兩個標準:

  1. 其輸入 messages 遵循 訊息格式List[Dict[str, str]]),並且它返回一個帶有 .content 屬性的物件。
  2. 它會在 stop_sequences 引數中傳遞的序列處停止生成輸出。

為了定義您的 LLM,您可以建立一個繼承自基類 ModelCustomModel 類。它應該有一個 `generate` 方法,該方法接收一個 訊息 列表,並返回一個包含文字的帶有 `.content` 屬性的物件。generate 方法還需要接受一個 stop_sequences 引數,以指示何時停止生成。

from huggingface_hub import login, InferenceClient

login("<YOUR_HUGGINGFACEHUB_API_TOKEN>")

model_id = "meta-llama/Llama-3.3-70B-Instruct"

client = InferenceClient(model=model_id)

class CustomModel(Model):
    def generate(messages, stop_sequences=["Task"]):
        response = client.chat_completion(messages, stop=stop_sequences, max_tokens=1024)
        answer = response.choices[0].message
        return answer

custom_model = CustomModel()

此外,generate 還可以接受一個 grammar 引數,以允許受約束的生成,從而強制輸出格式正確的 Agent 輸出。

TransformersModel

為方便起見,我們添加了一個 TransformersModel,它透過為初始化時給定的 model_id 構建一個本地 transformers 流水線來實現上述幾點。

from smolagents import TransformersModel

model = TransformersModel(model_id="HuggingFaceTB/SmolLM-135M-Instruct")

print(model([{"role": "user", "content": [{"type": "text", "text": "Ok!"}]}], stop_sequences=["great"]))
>>> What a

您必須在您的機器上安裝 transformerstorch。如果尚未安裝,請執行 pip install smolagents[transformers]

class smolagents.TransformersModel

< >

( model_id: str | None = None device_map: str | None = None torch_dtype: str | None = None trust_remote_code: bool = False model_kwargs: dict[str, typing.Any] | None = None **kwargs )

引數

  • model_id (str) — 用於推理的 Hugging Face 模型 ID。這可以是 Hugging Face 模型中心的一個路徑或模型識別符號。例如,"Qwen/Qwen2.5-Coder-32B-Instruct"
  • device_map (str, 可選) — 用於初始化模型的 device_map。
  • torch_dtype (str, 可選) — 用於初始化模型的 torch_dtype。
  • trust_remote_code (bool, 預設 False) — Hub 上的某些模型需要執行遠端程式碼:對於這些模型,您必須將此標誌設定為 True。
  • model_kwargs (dict[str, Any], 可選) — 傳遞給 AutoModel.from_pretrained 的額外關鍵字引數(如 revision, model_args, config 等)。
  • **kwargs — 傳遞給 model.generate() 的額外關鍵字引數,例如 max_new_tokensdevice

引發

ValueError

  • ValueError — 如果未提供模型名稱。

一個使用 Hugging Face 的 Transformers 庫進行語言模型互動的類。

此模型允許您使用 Transformers 庫在本地載入和使用 Hugging Face 的模型。它支援停止序列和語法定製等功能。

您必須在您的機器上安裝 transformerstorch。如果尚未安裝,請執行 pip install smolagents[transformers]

示例

>>> engine = TransformersModel(
...     model_id="Qwen/Qwen2.5-Coder-32B-Instruct",
...     device="cuda",
...     max_new_tokens=5000,
... )
>>> messages = [{"role": "user", "content": "Explain quantum mechanics in simple terms."}]
>>> response = engine(messages, stop_sequences=["END"])
>>> print(response)
"Quantum mechanics is the branch of physics that studies..."

InferenceClientModel

InferenceClientModel 封裝了 huggingface_hub 的 InferenceClient,用於執行 LLM。它支援 Hub 上所有可用的推理提供商:Cerebras、Cohere、Fal、Fireworks、HF-Inference、Hyperbolic、Nebius、Novita、Replicate、SambaNova、Together 等等。

您還可以使用 requests_per_minute 引數設定每分鐘的請求速率限制。

from smolagents import InferenceClientModel

messages = [
  {"role": "user", "content": [{"type": "text", "text": "Hello, how are you?"}]}
]

model = InferenceClientModel(provider="novita", requests_per_minute=60)
print(model(messages))
>>> Of course! If you change your mind, feel free to reach out. Take care!

class smolagents.InferenceClientModel

< >

( model_id: str = 'Qwen/Qwen2.5-Coder-32B-Instruct' provider: str | None = None token: str | None = None timeout: int = 120 client_kwargs: dict[str, typing.Any] | None = None custom_role_conversions: dict[str, str] | None = None api_key: str | None = None bill_to: str | None = None base_url: str | None = None **kwargs )

引數

  • model_id (str, 可選, 預設 "Qwen/Qwen2.5-Coder-32B-Instruct") — 用於推理的 Hugging Face 模型 ID。這可以是 Hugging Face 模型中心的模型識別符號,也可以是部署的推理端點的 URL。目前預設為 "Qwen/Qwen2.5-Coder-32B-Instruct",但將來可能會更改。
  • provider (str, 可選) — 用於推理的提供商名稱。支援的提供商列表可以在推理提供商文件中找到。預設為“auto”,即模型可用的提供商中的第一個,按使用者在此處的順序排序。如果傳遞了 base_url,則不使用 provider
  • token (str, 可選) — 用於 Hugging Face API 身份驗證的令牌。此令牌需要被授權“對無伺服器推理提供商進行呼叫”。如果模型是受限的(如 Llama-3 模型),令牌還需要“讀取您可訪問的所有公開受限倉庫內容的許可權”。如果未提供,該類將嘗試使用環境變數“HF_TOKEN”,否則使用儲存在 Hugging Face CLI 配置中的令牌。
  • timeout (int, 可選, 預設為 120) — API 請求的超時時間,單位為秒。
  • client_kwargs (dict[str, Any], 可選) — 傳遞給 Hugging Face InferenceClient 的額外關鍵字引數。
  • custom_role_conversions (dict[str, str], 可選) — 自定義角色轉換對映,用於將訊息角色轉換為其他角色。對於不支援特定訊息角色(如“system”)的特定模型很有用。
  • api_key (str, 可選) — 用於身份驗證的令牌。這是 token 的重複引數,旨在使 InferenceClientModel 遵循與 openai.OpenAI 客戶端相同的模式。如果設定了 token,則不能使用。預設為 None。
  • bill_to (str, 可選) — 用於請求的計費賬戶。預設情況下,請求計費到使用者的賬戶。請求只能計費到使用者所屬的、並且已訂閱企業版 Hub 的組織。
  • base_url (str, 可選) — 執行推理的基礎 URL。這是 model 的重複引數,旨在使 InferenceClientModel 遵循與 openai.OpenAI 客戶端相同的模式。如果設定了 model,則不能使用。預設為 None。
  • **kwargs — 傳遞給 Hugging Face InferenceClient 的額外關鍵字引數。

引發

ValueError

  • ValueError — 如果未提供模型名稱。

一個用於與 Hugging Face 推理提供商進行語言模型互動的類。

此模型允許您使用推理提供商與 Hugging Face 的模型進行通訊。它可以在無伺服器模式下使用,也可以使用專用端點,甚至可以使用本地 URL,支援停止序列和語法定製等功能。

提供商包括 Cerebras、Cohere、Fal、Fireworks、HF-Inference、Hyperbolic、Nebius、Novita、Replicate、SambaNova、Together 等等。

示例

>>> engine = InferenceClientModel(
...     model_id="Qwen/Qwen2.5-Coder-32B-Instruct",
...     provider="nebius",
...     token="your_hf_token_here",
...     max_tokens=5000,
... )
>>> messages = [{"role": "user", "content": "Explain quantum mechanics in simple terms."}]
>>> response = engine(messages, stop_sequences=["END"])
>>> print(response)
"Quantum mechanics is the branch of physics that studies..."

create_client

< >

( )

建立 Hugging Face 客戶端。

LiteLLMModel

LiteLLMModel 利用 LiteLLM 來支援來自各種提供商的 100 多個 LLM。您可以在模型初始化時傳遞 kwargs,這些 kwargs 將在每次使用模型時使用,例如下面我們傳遞 temperature。您還可以使用 requests_per_minute 引數設定每分鐘的請求速率限制。

from smolagents import LiteLLMModel

messages = [
  {"role": "user", "content": [{"type": "text", "text": "Hello, how are you?"}]}
]

model = LiteLLMModel(model_id="anthropic/claude-3-5-sonnet-latest", temperature=0.2, max_tokens=10, requests_per_minute=60)
print(model(messages))

class smolagents.LiteLLMModel

< >

( model_id: str | None = None api_base: str | None = None api_key: str | None = None custom_role_conversions: dict[str, str] | None = None flatten_messages_as_text: bool | None = None **kwargs )

引數

  • model_id (str) — 要在伺服器上使用的模型識別符號(例如 “gpt-3.5-turbo”)。
  • api_base (str, 可選) — 呼叫模型的提供商 API 的基礎 URL。
  • api_key (str, 可選) — 用於身份驗證的 API 金鑰。
  • custom_role_conversions (dict[str, str], 可選) — 自定義角色轉換對映,用於將訊息角色轉換為其他角色。對於不支援特定訊息角色(如“system”)的特定模型很有用。
  • flatten_messages_as_text (bool, 可選) — 是否將訊息展平為文字。對於以“ollama”、“groq”、“cerebras”開頭的模型,預設為 True
  • **kwargs — 傳遞給 OpenAI API 的額外關鍵字引數。

使用 LiteLLM Python SDK 訪問數百個 LLM 的模型。

create_client

< >

( )

建立 LiteLLM 客戶端。

LiteLLMRouterModel

LiteLLMRouterModelLiteLLM 路由器 的一個包裝器,它利用了先進的路由策略:跨多個部署的負載均衡、透過排隊優先處理關鍵請求,以及實施基本的可靠性措施,如冷卻、回退和指數退避重試。

from smolagents import LiteLLMRouterModel

messages = [
  {"role": "user", "content": [{"type": "text", "text": "Hello, how are you?"}]}
]

model = LiteLLMRouterModel(
    model_id="llama-3.3-70b",
    model_list=[
        {
            "model_name": "llama-3.3-70b",
            "litellm_params": {"model": "groq/llama-3.3-70b", "api_key": os.getenv("GROQ_API_KEY")},
        },
        {
            "model_name": "llama-3.3-70b",
            "litellm_params": {"model": "cerebras/llama-3.3-70b", "api_key": os.getenv("CEREBRAS_API_KEY")},
        },
    ],
    client_kwargs={
        "routing_strategy": "simple-shuffle",
    },
)
print(model(messages))

class smolagents.LiteLLMRouterModel

< >

( model_id: str model_list: list client_kwargs: dict[str, typing.Any] | None = None custom_role_conversions: dict[str, str] | None = None flatten_messages_as_text: bool | None = None **kwargs )

引數

  • model_id (str) — 模型列表中的模型組識別符號(例如,“model-group-1”)。
  • model_list (list[dict[str, Any]]) — 用於路由的模型配置。每個配置應包括模型組名稱和任何必要的引數。有關更多詳細資訊,請參閱 LiteLLM 路由 文件。
  • client_kwargs (dict[str, Any], 可選) — 路由器客戶端的附加配置引數。有關更多詳細資訊,請參閱 LiteLLM 路由配置
  • custom_role_conversions (dict[str, str], 可選) — 自定義角色轉換對映,用於將訊息角色轉換為其他角色。對於不支援特定訊息角色(如“system”)的特定模型很有用。
  • flatten_messages_as_text (bool, 可選) — 是否將訊息展平為文字。對於以“ollama”、“groq”、“cerebras”開頭的模型,預設為 True
  • **kwargs — 傳遞給 LiteLLM Router 完成方法的額外關鍵字引數。

用於與 LiteLLM Python SDK 路由器 互動的基於路由器的客戶端。

該類提供了一個高階介面,用於使用 LiteLLM SDK 的路由功能在多個語言模型之間分發請求。它負責初始化和配置路由器客戶端、應用自定義角色轉換以及管理訊息格式,以確保與各種 LLM 的無縫整合。

示例

>>> import os
>>> from smolagents import CodeAgent, WebSearchTool, LiteLLMRouterModel
>>> os.environ["OPENAI_API_KEY"] = ""
>>> os.environ["AWS_ACCESS_KEY_ID"] = ""
>>> os.environ["AWS_SECRET_ACCESS_KEY"] = ""
>>> os.environ["AWS_REGION"] = ""
>>> llm_loadbalancer_model_list = [
...     {
...         "model_name": "model-group-1",
...         "litellm_params": {
...             "model": "gpt-4o-mini",
...             "api_key": os.getenv("OPENAI_API_KEY"),
...         },
...     },
...     {
...         "model_name": "model-group-1",
...         "litellm_params": {
...             "model": "bedrock/anthropic.claude-3-sonnet-20240229-v1:0",
...             "aws_access_key_id": os.getenv("AWS_ACCESS_KEY_ID"),
...             "aws_secret_access_key": os.getenv("AWS_SECRET_ACCESS_KEY"),
...             "aws_region_name": os.getenv("AWS_REGION"),
...         },
...     },
>>> ]
>>> model = LiteLLMRouterModel(
...    model_id="model-group-1",
...    model_list=llm_loadbalancer_model_list,
...    client_kwargs={
...        "routing_strategy":"simple-shuffle"
...    }
>>> )
>>> agent = CodeAgent(tools=[WebSearchTool()], model=model)
>>> agent.run("How many seconds would it take for a leopard at full speed to run through Pont des Arts?")

OpenAIServerModel

該類允許您呼叫任何與 OpenAIServer 相容的模型。以下是設定方法(您可以自定義 api_base url 以指向其他伺服器)

import os
from smolagents import OpenAIServerModel

model = OpenAIServerModel(
    model_id="gpt-4o",
    api_base="https://api.openai.com/v1",
    api_key=os.environ["OPENAI_API_KEY"],
)

class smolagents.OpenAIServerModel

< >

( model_id: str api_base: str | None = None api_key: str | None = None organization: str | None = None project: str | None = None client_kwargs: dict[str, typing.Any] | None = None custom_role_conversions: dict[str, str] | None = None flatten_messages_as_text: bool = False **kwargs )

引數

  • model_id (str) — 要在伺服器上使用的模型識別符號(例如 “gpt-3.5-turbo”)。
  • api_base (str, 可選) — 相容 OpenAI 的 API 伺服器的基礎 URL。
  • api_key (str, 可選) — 用於身份驗證的 API 金鑰。
  • organization (str, 可選) — 用於 API 請求的組織。
  • project (str, 可選) — 用於 API 請求的專案。
  • client_kwargs (dict[str, Any], 可選) — 傳遞給 OpenAI 客戶端的額外關鍵字引數(如 organization、project、max_retries 等)。
  • custom_role_conversions (dict[str, str], 可選) — 自定義角色轉換對映,用於將訊息角色轉換為其他角色。對於不支援特定訊息角色(如“system”)的特定模型非常有用。
  • flatten_messages_as_text (bool, 預設為 False) — 是否將訊息展平為文字。
  • **kwargs — 傳遞給 OpenAI API 的額外關鍵字引數。

該模型連線到一個相容 OpenAI 的 API 伺服器。

AzureOpenAIServerModel

AzureOpenAIServerModel 允許您連線到任何 Azure OpenAI 部署。

下面是一個設定示例,請注意,您可以省略 azure_endpointapi_keyapi_version 引數,前提是您已經設定了相應的環境變數 — AZURE_OPENAI_ENDPOINTAZURE_OPENAI_API_KEYOPENAI_API_VERSION

請注意 OPENAI_API_VERSION 沒有 AZURE_ 字首,這是由於底層 openai 包的設計方式所致。

import os

from smolagents import AzureOpenAIServerModel

model = AzureOpenAIServerModel(
    model_id = os.environ.get("AZURE_OPENAI_MODEL"),
    azure_endpoint=os.environ.get("AZURE_OPENAI_ENDPOINT"),
    api_key=os.environ.get("AZURE_OPENAI_API_KEY"),
    api_version=os.environ.get("OPENAI_API_VERSION")    
)

class smolagents.AzureOpenAIServerModel

< >

( model_id: str azure_endpoint: str | None = None api_key: str | None = None api_version: str | None = None client_kwargs: dict[str, typing.Any] | None = None custom_role_conversions: dict[str, str] | None = None **kwargs )

引數

  • model_id (str) — 連線時使用的模型部署名稱(例如,“gpt-4o-mini”)。
  • azure_endpoint (str, 可選) — Azure 端點,包括資源,例如 https://example-resource.azure.openai.com/。如果未提供,將從 AZURE_OPENAI_ENDPOINT 環境變數推斷。
  • api_key (str, 可選) — 用於身份驗證的 API 金鑰。如果未提供,將從 AZURE_OPENAI_API_KEY 環境變數推斷。
  • api_version (str, 可選) — 要使用的 API 版本。如果未提供,將從 OPENAI_API_VERSION 環境變數推斷。
  • client_kwargs (dict[str, Any], 可選) — 傳遞給 AzureOpenAI 客戶端的額外關鍵字引數(如 organization、project、max_retries 等)。
  • custom_role_conversions (dict[str, str], 可選) — 自定義角色轉換對映,用於將訊息角色轉換為其他角色。對於不支援特定訊息角色(如“system”)的特定模型非常有用。
  • **kwargs — 傳遞給 Azure OpenAI API 的額外關鍵字引數。

該模型連線到一個 Azure OpenAI 部署。

AmazonBedrockServerModel

AmazonBedrockServerModel 幫助您連線到 Amazon Bedrock 並使用任何可用模型執行您的智慧體。

下面是一個設定示例。該類還提供了額外的自定義選項。

import os

from smolagents import AmazonBedrockServerModel

model = AmazonBedrockServerModel(
    model_id = os.environ.get("AMAZON_BEDROCK_MODEL_ID"),
)

class smolagents.AmazonBedrockServerModel

< >

( model_id: str client = None client_kwargs: dict[str, typing.Any] | None = None custom_role_conversions: dict[str, str] | None = None **kwargs )

引數

  • model_id (str) — 在 Bedrock 上使用的模型識別符號(例如,“us.amazon.nova-pro-v1:0”)。
  • client (boto3.client, 可選) — 用於 AWS 互動的自定義 boto3 客戶端。如果未提供,將建立一個預設客戶端。
  • client_kwargs (dict[str, Any], 可選) — 如果需要在內部建立 boto3 客戶端,則用於配置該客戶端的關鍵字引數。例如 region_nameconfigendpoint_url
  • custom_role_conversions (dict[str, str], 可選) — 自定義角色轉換對映,用於將訊息角色轉換為其他角色。對於不支援特定訊息角色(如“system”)的特定模型非常有用。預設為將所有角色轉換為“user”角色,以啟用所有 Bedrock 模型。
  • flatten_messages_as_text (bool, 預設為 False) — 是否將訊息展平為文字。
  • **kwargs — 直接傳遞給底層 API 呼叫的額外關鍵字引數。

一個用於透過 Bedrock API 與 Amazon Bedrock Server 模型互動的模型類。

該類提供了一個與各種 Bedrock 語言模型互動的介面,允許自定義模型推理、護欄配置、訊息處理以及 boto3 API 允許的其他引數。

身份驗證

Amazon Bedrock 支援多種身份驗證方法

  • 預設 AWS 憑證:使用預設的 AWS 憑證鏈(例如,IAM 角色、IAM 使用者)。
  • API 金鑰身份驗證(需要 boto3 >= 1.39.0):使用 AWS_BEARER_TOKEN_BEDROCK 環境變數設定 API 金鑰。

API 金鑰支援需要 boto3 >= 1.39.0。對於不依賴 API 金鑰身份驗證的使用者,支援的最低版本是 boto3 >= 1.36.18

示例

使用預設設定建立模型例項

>>> bedrock_model = AmazonBedrockServerModel(
...     model_id='us.amazon.nova-pro-v1:0'
... )

使用自定義 boto3 客戶端建立模型例項

>>> import boto3
>>> client = boto3.client('bedrock-runtime', region_name='us-west-2')
>>> bedrock_model = AmazonBedrockServerModel(
...     model_id='us.amazon.nova-pro-v1:0',
...     client=client
... )

使用 client_kwargs 建立模型例項以進行內部客戶端建立

>>> bedrock_model = AmazonBedrockServerModel(
...     model_id='us.amazon.nova-pro-v1:0',
...     client_kwargs={'region_name': 'us-west-2', 'endpoint_url': 'https://custom-endpoint.com'}
... )

使用推理和護欄配置建立模型例項

>>> additional_api_config = {
...     "inferenceConfig": {
...         "maxTokens": 3000
...     },
...     "guardrailConfig": {
...         "guardrailIdentifier": "identify1",
...         "guardrailVersion": 'v1'
...     },
... }
>>> bedrock_model = AmazonBedrockServerModel(
...     model_id='anthropic.claude-3-haiku-20240307-v1:0',
...     **additional_api_config
... )

MLXModel

from smolagents import MLXModel

model = MLXModel(model_id="HuggingFaceTB/SmolLM-135M-Instruct")

print(model([{"role": "user", "content": "Ok!"}], stop_sequences=["great"]))
>>> What a

您的機器上必須安裝 mlx-lm。如果尚未安裝,請執行 pip install smolagents[mlx-lm]

class smolagents.MLXModel

< >

( model_id: str trust_remote_code: bool = False load_kwargs: dict[str, typing.Any] | None = None apply_chat_template_kwargs: dict[str, typing.Any] | None = None **kwargs )

引數

  • model_id (str) — 用於推理的 Hugging Face 模型 ID。這可以是來自 Hugging Face 模型中心的路徑或模型識別符號。
  • tool_name_key (str) — 用於檢索工具名稱的鍵,通常可以在模型的聊天模板中找到。
  • tool_arguments_key (str) — 用於檢索工具引數的鍵,通常可以在模型的聊天模板中找到。
  • trust_remote_code (bool, 預設為 False) — Hub 上的某些模型需要執行遠端程式碼:對於此模型,您需要將此標誌設定為 True。
  • load_kwargs (dict[str, Any], 可選) — 載入模型和分詞器時傳遞給 mlx.lm.load 方法的額外關鍵字引數。
  • apply_chat_template_kwargs (dict, 可選) — 傳遞給分詞器的 apply_chat_template 方法的額外關鍵字引數。
  • kwargs (dict, 可選) — 您希望在 model.generate() 中使用的任何其他關鍵字引數,例如 max_tokens

一個用於與在 Apple silicon 上使用 MLX 載入的模型進行互動的類。

您的機器上必須安裝 mlx-lm。如果尚未安裝,請執行 pip install smolagents[mlx-lm]

示例

>>> engine = MLXModel(
...     model_id="mlx-community/Qwen2.5-Coder-32B-Instruct-4bit",
...     max_tokens=10000,
... )
>>> messages = [
...     {
...         "role": "user",
...         "content": "Explain quantum mechanics in simple terms."
...     }
... ]
>>> response = engine(messages, stop_sequences=["END"])
>>> print(response)
"Quantum mechanics is the branch of physics that studies..."

VLLMModel

用於使用 vLLM 進行快速 LLM 推理和服務的模型。

from smolagents import VLLMModel

model = VLLMModel(model_id="HuggingFaceTB/SmolLM-135M-Instruct")

print(model([{"role": "user", "content": "Ok!"}], stop_sequences=["great"]))

您的機器上必須安裝 vllm。如果尚未安裝,請執行 pip install smolagents[vllm]

class smolagents.VLLMModel

< >

( model_id model_kwargs: dict[str, typing.Any] | None = None **kwargs )

引數

  • model_id (str) — 用於推理的 Hugging Face 模型 ID。這可以是來自 Hugging Face 模型中心的路徑或模型識別符號。
  • model_kwargs (dict[str, Any], 可選) — 傳遞給 vLLM 模型的額外關鍵字引數(如 revision、max_model_len 等)。

用於使用 vLLM 進行快速 LLM 推理和服務的模型。

< > 在 GitHub 上更新

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