快速入门:构建 Python (smolagents) Web 应用并将其部署到 Cloud Run
本文档介绍了如何构建 smolagents 应用并将其部署到 Cloud Run。
按照本快速入门中的步骤操作时,Cloud Run 会在您从源代码进行部署时自动为您构建 Dockerfile。
准备工作
- 登录您的 Google Cloud 账号。如果您是 Google Cloud新手,请 创建一个账号来评估我们的产品在实际场景中的表现。新客户还可获享 $300 赠金,用于运行、测试和部署工作负载。
-
安装 Google Cloud CLI。
-
如果您使用的是外部身份提供方 (IdP),则必须先使用联合身份登录 gcloud CLI。
-
如需初始化 gcloud CLI,请运行以下命令:
gcloud init -
选择或创建项目所需的角色
- 选择项目:选择项目不需要特定的 IAM 角色,您可以选择已获授角色的任何项目。
-
创建项目:如需创建项目,您需要拥有 Project Creator 角色 (
roles/resourcemanager.projectCreator),该角色包含resourcemanager.projects.create权限。了解如何授予角色。
-
创建 Google Cloud 项目:
gcloud projects create PROJECT_ID
将
PROJECT_ID替换为您要创建的 Google Cloud 项目的名称。 -
选择您创建的 Google Cloud 项目:
gcloud config set project PROJECT_ID
将
PROJECT_ID替换为您的 Google Cloud 项目名称。
-
如果您要使用现有项目来完成本指南,请验证您是否拥有完成本指南所需的权限。如果您创建了新项目,则您已拥有所需的权限。
-
安装 Google Cloud CLI。
-
如果您使用的是外部身份提供方 (IdP),则必须先使用联合身份登录 gcloud CLI。
-
如需初始化 gcloud CLI,请运行以下命令:
gcloud init -
选择或创建项目所需的角色
- 选择项目:选择项目不需要特定的 IAM 角色,您可以选择已获授角色的任何项目。
-
创建项目:如需创建项目,您需要拥有 Project Creator 角色 (
roles/resourcemanager.projectCreator),该角色包含resourcemanager.projects.create权限。了解如何授予角色。
-
创建 Google Cloud 项目:
gcloud projects create PROJECT_ID
将
PROJECT_ID替换为您要创建的 Google Cloud 项目的名称。 -
选择您创建的 Google Cloud 项目:
gcloud config set project PROJECT_ID
将
PROJECT_ID替换为您的 Google Cloud 项目名称。
-
如果您要使用现有项目来完成本指南,请验证您是否拥有完成本指南所需的权限。如果您创建了新项目,则您已拥有所需的权限。
-
启用 Cloud Run Admin API 和 Cloud Build API:
启用 API 所需的角色
如需启用 API,您需要拥有 Service Usage Admin IAM 角色 (
roles/serviceusage.serviceUsageAdmin),该角色包含serviceusage.services.enable权限。了解如何授予角色。gcloud services enable run.googleapis.com
cloudbuild.googleapis.com 启用 Cloud Run Admin API 后,系统会自动创建 Compute Engine 默认服务账号。
- 查看 Cloud Run 价格或使用价格计算器估算费用。
- 您需要使用 Google AI Studio 提供的 API 密钥才能部署使用 Gemini 模型的 smolagents 应用。如需使用 Google AI 工作室生成 API 密钥,请参阅 Gemini API 文档中的使用 Gemini API 密钥。
所需的角色
如需获得完成本教程所需的权限,请让您的管理员为您授予以下 IAM 角色:
-
项目的 Cloud Run Admin (
roles/run.admin) 角色 - 项目的 Cloud Run Source Developer (
roles/run.sourceDeveloper) 角色 -
服务身份的 Service Account User (
roles/iam.serviceAccountUser) 角色 -
项目的 Logs Viewer (
roles/logging.viewer) 角色
如需详细了解如何授予角色,请参阅管理对项目、文件夹和组织的访问权限。
授予 Cloud Build 服务账号对项目的访问权限
除非您替换此行为,否则 Cloud Build 会自动使用 Compute Engine 默认服务账号作为默认 Cloud Build 服务账号来构建源代码和 Cloud Run 资源。
为了让 Cloud Build 能够构建来源,请向 Cloud Build 服务账号授予项目的 Cloud Run Builder (roles/run.builder) 角色:
gcloud projects add-iam-policy-binding PROJECT_ID \ --member=serviceAccount:SERVICE_ACCOUNT_EMAIL_ADDRESS \ --role=roles/run.builder
将 PROJECT_ID 替换为您的 Google Cloud项目 ID,并将 SERVICE_ACCOUNT_EMAIL_ADDRESS 替换为 Cloud Build 服务账号的邮箱。如果您使用 Compute Engine 默认服务账号作为 Cloud Build 服务账号,则服务账号邮箱应采用以下格式:
PROJECT_NUMBER-compute@developer.gserviceaccount.com
将 PROJECT_NUMBER 替换为您的 Google Cloud项目编号。
如需详细了解如何查找项目 ID 和项目编号,请参阅创建和管理项目。
授予 Cloud Run Builder 角色之后,需要几分钟时间才能完成传播。
编写示例应用
如需使用 Python 编写应用,请执行以下操作:
创建名为
my-agent-app的新目录,并转到此目录中:mkdir my-agent-app cd my-agent-app创建名为
main.py的文件,并将以下代码粘贴到其中:import os from fastapi import FastAPI, HTTPException from pydantic import BaseModel from smolagents import CodeAgent, LiteLLMModel, tool # 1. Define a simple tool for the agent @tool def get_greeting(name: str) -> str: """ Returns a special greeting for the user. Args: name: The name of the person to greet. """ return f"Hello {name}, welcome to the agentic world running on Cloud Run!" # 2. Initialize the Gemini Model via LiteLLM # Make sure GEMINI_API_KEY is set in your environment variables model = LiteLLMModel( model_id="gemini/gemini-2.5-flash", # This is the model name. If a newer model is available, you can use that. api_key=os.environ.get("GEMINI_API_KEY") ) # 3. Create the CodeAgent agent = CodeAgent( tools=[get_greeting], model=model, add_base_tools=True # Adds basic python tools like print ) # 4. Setup FastAPI app = FastAPI() class AgentRequest(BaseModel): task: str @app.get("/") def health_check(): return {"status": "running", "service": "smolagents-fastapi"} @app.post("/run") def run_agent(request: AgentRequest): try: # Run the agent with the user's task response = agent.run(request.task) return {"response": str(response)} except Exception as e: raise HTTPException(status_code=500, detail=str(e))创建名为
requirements.txt的文件,并将以下代码粘贴到其中:fastapi uvicorn smolagents[toolkit] litellm
从源代码部署到 Cloud Run
从源代码部署会自动从源代码构建容器映像并进行部署。
如需从源代码进行部署,请使用以下命令:
gcloud run deploy smolagents-demo \
--source . \
--region us-central1 \
--no-allow-unauthenticated \
--set-env-vars GEMINI_API_KEY=API_KEY
将 API_KEY 替换为您的 Google AI Studio API 密钥。
成功部署应用后,Cloud Run 会显示服务网址,例如 https://smolagents-demo-xyz-uc.a.run.app。
测试 Cloud Run 服务
使用以下 curl 命令向代理发送任务,以测试您的服务:
curl -X POST YOUR-SERVICE-URL/run \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $(gcloud auth print-identity-token)" \
-d '{"task": "Use the greeting tool to say hello to Gemini User"}'
将 YOUR-SERVICE-URL 替换为您的服务的网址。
代理发送以下回答:
{
"response": "Hello Gemini User, welcome to the agentic world running on Cloud Run!"
}
如需验证服务是否正常运行,请检查 Cloud Run 服务的“日志”标签页。
清理
为避免因本页面中使用的资源导致您的 Google Cloud 账号产生费用,请删除包含这些资源的 Google Cloud 项目。
为避免您的 Google Cloud 账号产生额外费用,请删除您在本快速入门中部署的所有资源。
删除仓库
当您部署的服务未被使用时,Cloud Run 不会向您收取费用。不过,您可能仍需要支付将容器映像存储在 Artifact Registry 中而产生的相关费用。如需删除 Artifact Registry 仓库,请按照 Artifact Registry 文档中删除仓库的步骤操作。
删除服务
Cloud Run 服务在收到请求之前不会产生费用。如需删除 Cloud Run 服务,请按照以下步骤之一操作:
控制台
要删除服务,请执行以下操作:
在 Google Cloud 控制台中,前往 Cloud Run 服务页面:
在服务列表中找到要删除的服务,然后点击该服务对应的复选框以将其选中。
点击删除。这将删除服务的所有修订版本。
gcloud
要删除作业,请运行以下命令:
gcloud run services delete SERVICE --region REGION
替换以下内容:
- SERVICE:服务的名称。
- REGION:服务的 Google Cloud 区域。
删除测试项目
删除 Google Cloud 项目后,系统即会停止对该项目中的所有资源计费。如需释放项目中的所有 Google Cloud 资源,请按照以下步骤操作:
删除 Google Cloud 项目:
gcloud projects delete PROJECT_ID
后续步骤
如需详细了解如何使用代码源构建容器并推送到仓库,请参阅: