使用 Google AI Studio 將 Gemma 3 部署至 Cloud Run

本指南說明如何在 Google AI 工作室中,透過單鍵點選在 Cloud Run 上部署 Gemma 3 開放模型。

Google AI Studio 是以瀏覽器為基礎的平台,可讓您快速試用模型,以及測試不同提示。輸入對話方塊提示訊息後,您就可以設計使用所選 Gemma 3 模型的原型網頁應用程式,然後選取「Deploy to Cloud Run」,在支援 GPU 的 Cloud Run 服務上執行 Gemma 模型。

使用 Google AI Studio 將產生的前端服務部署至 Cloud Run,即可略過大部分的容器設定步驟,因為 Cloud Run 提供預先建構的容器,可在支援 Google Gen AI SDK 的 Cloud Run 上提供 Gemma 開放式模型。

開始使用 Google AI Studio

本節將引導您使用 Google AI Platform Studio 將 Gemma 3 部署至 Cloud Run。

  1. 在 Google AI Studio 中選取 Gemma 模型。

    前往 Google AI Studio

    在「Chat」頁面的「執行設定」面板中,使用預設的 Gemma 模型,或選取其中一個 Gemma 模型。

  2. 在頂端列中,選取「查看更多動作」,然後按一下「部署至 Cloud Run」

  3. 在「在 Google Cloud Run 上部署 Gemma 3」對話方塊中,按照提示建立新的 Google Cloud 專案,或選取現有專案。如果沒有相關聯的帳單帳戶,系統可能會提示您啟用帳單功能。

  4. Google AI 工作室驗證專案後,請按一下「Deploy to Google Cloud」

  5. Gemma 3 模型成功部署至 Google Cloud 後,對話方塊會顯示以下內容:

    • 執行 Gemma 3 和 Ollama 的 Cloud Run 服務 Cloud Run 端點網址。
    • 產生的 API 金鑰,用於驗證 Gemini API 程式庫。這個金鑰會設為部署 Cloud Run 服務的環境變數,用於授權傳入要求。建議您修改 API 金鑰,以便使用 IAM 驗證。詳情請參閱「安全地與 Google Gen AI SDK 互動」。
    • 連結至 Google Cloud 控制台中的 Cloud Run 服務。如要瞭解 Cloud Run 服務的預設配置設定,請前往連結,然後選取「編輯並部署新修訂版本」,即可查看或修改配置設定。
  6. 如要查看用於建立 Cloud Run 服務的 Gemini API 範例程式碼,請選取「Get Code」(取得程式碼)

  7. 選用:複製程式碼,並視需要進行修改。

您可以使用程式碼,搭配 Google Gen AI SDK 使用已部署的 Cloud Run 端點和 API 金鑰。

舉例來說,如果您使用 Google Gen AI SDK for Python,Python 程式碼可能會如下所示:

from google import genai
from google.genai.types import HttpOptions

# Configure the client to use your Cloud Run endpoint and API key
client = genai.Client(api_key="<YOUR_API_KEY>", http_options=HttpOptions(base_url="<cloud_run_url>"))


# Example: Generate content (non-streaming)
response = client.models.generate_content(
   model="<model>", # Replace model with the Gemma 3 model you selected in Google AI Studio, such as "gemma-3-1b-it".
   contents=["How does AI work?"]
)
print(response.text)


# Example: Stream generate content
response = client.models.generate_content_stream(
   model="<model>", # Replace model with the Gemma 3 model you selected in Google AI Studio, such as "gemma-3-1b-it".
   contents=["Write a story about a magic backpack. You are the narrator of an interactive text adventure game."]
)
for chunk in response:
   print(chunk.text, end="")

注意事項

從 Google AI Studio 部署 Cloud Run 服務時,請考量下列事項:

  • 定價Cloud Run 是可計費的元件。如要根據預測用量產生預估費用,請使用Pricing Calculator
  • 配額:Cloud Run 會自動針對 Cloud Run Admin API 下的 Request Total Nvidia L4 GPU allocation, per project per region 配額提出要求。
  • 應用程式 Proxy 伺服器:已部署的服務會使用 Google AI Studio Gemini 應用程式 Proxy 伺服器包裝 Ollama,讓服務與 Gemini API 相容。
  • 權限:如果您需要修改 Cloud Run 服務,必須將必要的 IAM 角色授予專案中的帳戶。
  • 驗證:根據預設,當您從 Google AI Studio 部署 Cloud Run 服務時,系統會以公開 (未驗證) 存取權 (--allow-unauthenticated 標記) 部署服務。如要使用更強大的安全機制,建議您使用 IAM 進行驗證

後續步驟

瞭解從 Google AI 工作室部署至 Cloud Run 時,如何最佳化效能並確保安全的最佳做法。