配置模板参数

从 BentoML v1.4.8 开始,您可以使用 use_arguments() API 为 Service 定义模板参数。它允许您在 serve、build 和 deploy 时传递动态和经过验证的参数。

由于这些参数可直接在 Python 代码中使用,因此您可以在 service.py 中的任何位置替换值,包括条件语句、循环或任何动态逻辑内部。这在使用 Service 模板处理不同的模型或配置时特别有用。

使用 Pydantic 定义 Schema

使用 pydantic.BaseModel,您可以为参数设置默认值并启用数据验证。这是一个示例

service.py
from pydantic import BaseModel
import bentoml

class BentoArgs(BaseModel):
    model_name: str
    gpu: int = 8
    gpu_type: str = "nvidia-h200-141gb"

args = bentoml.use_arguments(BentoArgs)

然后您可以像引用常规 Python 变量一样引用这些参数。

service.py
import bentoml

@bentoml.service(
    resources={
        "gpu": args.gpu,
        "gpu_type": args.gpu_type
    }
)
class LLM:
    model = bentoml.models.HuggingFaceModel(args.model_name)
    ...

不使用 Pydantic 定义 Schema

您可以直接使用 use_arguments() 而无需 Pydantic 模型。这将返回一个包含所有参数值的 types.SimpleNamespace 对象,但不提供验证或默认值支持。

service.py
import bentoml

args = bentoml.use_arguments()

@bentoml.service(resources={"gpu": int(args.gpu)})
class LLM:
    model = bentoml.models.HuggingFaceModel(args.model_name)
    ...

提供参数值

设置模板参数后,您可以在运行 bentoml serve, bentoml build, bentoml deploy (传递 Bento 路径时) 以及 bentoml code 等命令时,通过 CLI 动态提供它们的值。例如

bentoml build --arg model_name=meta-llama/Llama-3.3-70B-Instruct --arg gpu=4
bentoml serve --arg model_name=deepseek-ai/DeepSeek-V3
bentoml deploy --arg model_name=deepseek-ai/DeepSeek-V3
bentoml deployment update <deployment_name> --arg model_tag=$MODEL_TAG --bento ./project/directory

警告

如果缺少必需的参数,BentoML 将在运行命令时引发错误。