arrow_back

運用 Vertex AI Gemini 1.0 Pro 開發應用程式

登录 加入
欢迎加入我们的社区,一起测试和分享您的知识!
done
学习 700 多个动手实验和课程并获得相关技能徽章

運用 Vertex AI Gemini 1.0 Pro 開發應用程式

实验 1 小时 30 分钟 universal_currency_alt 1 积分 show_chart 入门级
info 此实验可能会提供 AI 工具来支持您学习。
欢迎加入我们的社区,一起测试和分享您的知识!
done
学习 700 多个动手实验和课程并获得相关技能徽章

總覽

Gemini 是一系列生成式 AI 模型,專為多模態用途而設計,並提供三種規模:Ultra、Pro 和 Nano。Gemini 1.0 Pro 可讓開發人員與企業根據自家用途進行建構,能以文字接收並生成內容。此外也有專屬的 Gemini 1.0 Pro Vision 多模態端點,可接收文字及圖像內容並生成文字。您可以透過 SDK 使用 Python、Android (Kotlin)、Node.js、Swift 和 JavaScript 建構應用程式。

在 Google Cloud 中,Vertex AI Gemini API 提供統一的 Gemini 模型互動介面。這個 API 支援多模態提示做為輸入內容,並輸出文字或程式碼。目前 Gemini API 有兩種可用模型:

  • Gemini 1.0 Pro 模型 (gemini-pro):專門處理自然語言工作、多輪文字和程式碼對話,也能生成程式碼。

  • Gemini 1.0 Pro Vision 模型 (gemini-pro-vision):支援多模態提示。您可以在提示要求中加入文字、圖片和影片,並取得文字或程式碼形式的回覆。

您可以透過 Vertex AI 這個機器學習 (ML) 平台訓練及部署 ML 模型和 AI 應用程式,並自訂大型語言模型 (LLM) 用於 AI 技術輔助應用程式。Vertex AI 可讓您自訂 Gemini、完全掌控資料,並享有更多 Google Cloud 功能保障企業安全性、隱私權,強化資料管理及法規遵循機制。如要進一瞭解 Vertex AI,請參閱本研究室結尾的「後續步驟」

在本研究室中,您會使用 Python 適用的 Vertex AI SDK 來呼叫 Vertex AI Gemini API。

目標

本研究室將說明如何執行下列工作:

  • 運用 Streamlit 架構開發 Python 應用程式。
  • 安裝 Python 適用的 Vertex AI SDK。
  • 使用 Vertex AI Gemini API 開發程式碼與 Gemini 1.0 Pro 模型 (gemini-pro) 互動。
  • 使用 Vertex AI Gemini API 開發程式碼與 Gemini 1.0 Pro Vision 模型 (gemini-pro-vision) 互動。
  • 將應用程式容器化,並在 Cloud Run 部署和測試。

設定

在每個研究室中,您都能在固定時間內免付費建立新的 Google Cloud 專案,並使用一組資源。

  1. 請透過無痕式視窗登入 Qwiklabs。

  2. 請記下研究室的存取時間 (例如 1:15:00),並確保自己能在時間限制內完成作業。
    研究室不提供暫停功能。如有需要,您可以重新開始,但原先的進度恕無法保留。

  3. 準備就緒後,請按一下「Start lab」

  4. 請記下研究室憑證 (使用者名稱密碼),這組資訊將用於登入 Google Cloud 控制台。

  5. 按一下「Open Google Console」

  6. 按一下「Use another account」,然後複製這個研究室的憑證,並貼入提示訊息。
    如果使用其他憑證,系統會顯示錯誤或向您收取費用

  7. 接受條款,然後略過資源復原頁面。

啟用 Cloud Shell

Cloud Shell 是含有多項開發工具的虛擬機器,提供永久的 5 GB 主目錄,並在 Google Cloud 中運作。Cloud Shell 可讓您透過指令列存取 Google Cloud 資源。gcloud 是 Google Cloud 的指令列工具,已預先安裝於 Cloud Shell,並支援 Tab 鍵完成功能。

  1. 在控制台的右上方,點按「啟用 Cloud Shell」按鈕 「啟用 Cloud Shell」圖示

  2. 點按「繼續」
    請稍候片刻,等待系統完成佈建作業並連線至環境。連線建立後,即代表您已通過驗證,且專案已設為「PROJECT_ID」

指令範例

  • 列出目前使用的帳戶名稱:
gcloud auth list

輸出內容

Credentialed accounts: - <myaccount>@<mydomain>.com (active)

輸出內容範例

Credentialed accounts: - google1623327_student@qwiklabs.net
  • 列出專案 ID:
gcloud config list project

輸出內容

[core] project = <project_ID>

輸出內容範例

[core] project = qwiklabs-gcp-44776a13dea667a6 注意:如需 gcloud 的完整說明,請參閱 gcloud CLI 總覽指南

工作 1:設定環境與專案

  1. 使用研究室憑證登入 Google Cloud 控制台,然後開啟 Cloud Shell 終端機視窗。

  2. 執行下列指令,在 Cloud Shell 設定專案 ID 和區域環境變數:

    PROJECT_ID=$(gcloud config get-value project) REGION={{{project_0.default_region|set at lab start}}} echo "PROJECT_ID=${PROJECT_ID}" echo "REGION=${REGION}"
  3. 如要在本研究室使用各種 Google Cloud 服務,您必須啟用幾個 API:

    gcloud services enable cloudbuild.googleapis.com cloudfunctions.googleapis.com run.googleapis.com logging.googleapis.com storage-component.googleapis.com aiplatform.googleapis.com

點選「Check my progress」,確認目標已達成。 啟用相關 API。

工作 2:設定應用程式環境

在這項工作中,您會設定 Python 虛擬環境,並安裝應用程式依附元件。

確認 Cloud Shell 已獲得授權

  1. 在 Cloud Shell 執行下列指令,確認 Cloud Shell 已獲得授權:

    gcloud auth list
  2. 如果系統提示您為 Cloud Shell 提供授權,請點選「授權」

建立應用程式目錄

  1. 執行下列指令,建立應用程式目錄:

    mkdir ~/gemini-app
  2. 切換到 ~/gemini-app 目錄:

    cd ~/gemini-app

    應用程式檔案會在 ~/gemini-app 目錄中建立。此目錄將含有 Python 應用程式來源檔案、依附元件及 Docker 檔案,本研究室的後續步驟會用到。

設定 Python 虛擬環境

在現有 Python 安裝版本上建立虛擬環境,區隔安裝在此環境中的所有套件,以及基礎環境環境中的套件。在虛擬環境使用時,pip 等安裝工具會將 Python 套件安裝到虛擬環境中。

  1. 執行下列指令,在 gemini-app 資料夾建立 Python 虛擬環境:

    python3 -m venv gemini-streamlit 「venv」模組會建立簡便的虛擬環境,具備專屬的獨立 Python 套件。
  2. 啟用 Python 虛擬環境:

    source gemini-streamlit/bin/activate

安裝應用程式依附元件

Python requirements 檔案是簡易的文字檔案,會列出專案所需的依附元件。首先,requirements 檔案中需要有三個模組。

我們的應用程式是以 Streamlit 編寫,這是一個開放原始碼 Python 程式庫,用來建立機器學習與數據資料學的網頁應用程式。應用程式會使用 Python 程式庫適用的 Vertex AI SDK 與 Gemini API 及模型互動。Cloud Logging 用於記錄應用程式資訊。

  1. 執行下列指令,建立 requirements 檔案:

    cat > ~/gemini-app/requirements.txt <<EOF streamlit google-cloud-aiplatform==1.38.1 google-cloud-logging==3.6.0 EOF
  2. 安裝應用程式依附元件:

    pip install -r requirements.txt

    pip 是 Python 適用的套件安裝程式。

    請等所有套件都安裝完畢後,再繼續下一項工作。

工作 3:開發應用程式

應用程式原始碼將以多個 .py 來源檔案編寫。讓我們從 app.py 的主要進入點開始。

編寫應用程式主要進入點

  1. 執行下列指令,建立 app.py 進入點程式碼:

    cat > ~/gemini-app/app.py <<EOF import os import streamlit as st from app_tab1 import render_story_tab from vertexai.preview.generative_models import GenerativeModel import vertexai import logging from google.cloud import logging as cloud_logging # configure logging logging.basicConfig(level=logging.INFO) # attach a Cloud Logging handler to the root logger log_client = cloud_logging.Client() log_client.setup_logging() PROJECT_ID = os.environ.get('PROJECT_ID') # Your Qwiklabs Google Cloud Project ID LOCATION = os.environ.get('REGION') # Your Qwiklabs Google Cloud Project Region vertexai.init(project=PROJECT_ID, location=LOCATION) @st.cache_resource def load_models(): text_model_pro = GenerativeModel("gemini-pro") multimodal_model_pro = GenerativeModel("gemini-pro-vision") return text_model_pro, multimodal_model_pro st.header("Vertex AI Gemini API", divider="rainbow") text_model_pro, multimodal_model_pro = load_models() tab1, tab2, tab3, tab4 = st.tabs(["Story", "Marketing Campaign", "Image Playground", "Video Playground"]) with tab1: render_story_tab(text_model_pro) EOF
  2. 查看 app.py 檔案內容:

    cat ~/gemini-app/app.py

    應用程式會使用 streamlit 在 UI 建立幾個分頁。在應用程式初始版本中,我們會建構第一個分頁「Story」,其中含有生成一篇故事的功能,接著在研究室的後續工作中逐步建構其他分頁。

    應用程式首先會初始化 Vertex AI SDK,傳入 PROJECT_ID 的值及 REGION 環境變數。

    接著使用代表 Gemini 模型的 GenerativeModel 類別,載入 gemini-progemini-pro-vision 模型。這個類型包含可協助透過文字、圖片及影片生成內容的方法。

    應用程式會在 UI 建立 4 個分頁,分別為「Story」(故事)、「Marketing Campaign」(行銷廣告活動)、「Image Playground」(圖片園地) 和「Video Playground」(影片園地)

    接著叫用 render_tab1() 函式,在應用程式 UI 為「Story」分頁建立 UI。

開發 tab1 -「Story」

  1. 執行下列指令來編寫程式碼,在應用程式 UI 轉譯「Story」分頁

    cat > ~/gemini-app/app_tab1.py <<EOF import streamlit as st from vertexai.preview.generative_models import GenerativeModel from response_utils import * import logging # create the model prompt based on user input. def generate_prompt(): # Story character input character_name = st.text_input("Enter character name: \n\n",key="character_name",value="Mittens") character_type = st.text_input("What type of character is it? \n\n",key="character_type",value="Cat") character_persona = st.text_input("What personality does the character have? \n\n", key="character_persona",value="Mitten is a very friendly cat.") character_location = st.text_input("Where does the character live? \n\n",key="character_location",value="Andromeda Galaxy") # Story length and premise length_of_story = st.radio("Select the length of the story: \n\n",["Short","Long"],key="length_of_story",horizontal=True) story_premise = st.multiselect("What is the story premise? (can select multiple) \n\n",["Love","Adventure","Mystery","Horror","Comedy","Sci-Fi","Fantasy","Thriller"],key="story_premise",default=["Love","Adventure"]) creative_control = st.radio("Select the creativity level: \n\n",["Low","High"],key="creative_control",horizontal=True) if creative_control == "Low": temperature = 0.30 else: temperature = 0.95 prompt = f"""Write a {length_of_story} story based on the following premise: \n character_name: {character_name} \n character_type: {character_type} \n character_persona: {character_persona} \n character_location: {character_location} \n story_premise: {",".join(story_premise)} \n If the story is "short", then make sure to have 5 chapters or else if it is "long" then 10 chapters. Important point is that each chapter should be generated based on the premise given above. First start by giving the book introduction, chapter introductions and then each chapter. It should also have a proper ending. The book should have a prologue and an epilogue. """ return temperature, prompt # function to render the story tab, and call the model, and display the model prompt and response. def render_story_tab (text_model_pro: GenerativeModel): st.write("Using Gemini 1.0 Pro - Text only model") st.subheader("Generate a story") temperature, prompt = generate_prompt() config = { "temperature": temperature, "max_output_tokens": 2048, } generate_t2t = st.button("Generate my story", key="generate_t2t") if generate_t2t and prompt: # st.write(prompt) with st.spinner("Generating your story using Gemini..."): first_tab1, first_tab2 = st.tabs(["Story response", "Prompt"]) with first_tab1: response = get_gemini_pro_text_response(text_model_pro, prompt, generation_config=config) if response: st.write("Your story:") st.write(response) logging.info(response) with first_tab2: st.text(prompt) EOF
  2. 查看 app_tab1.py 檔案內容:

    cat ~/gemini-app/app_tab1.py

    render_story_tab 函式叫用的函式會轉譯文字輸入欄位及其他選項,在分頁生成 UI 控制項。

    generate_prompt 函式會生成提供給 Gemini API 的文字提示。使用者在分頁 UI 為故事角色輸入值並選好選項後,系統會串連這些內容來建立提示字串。選項包括故事長度 (短、長)、創意程度 (低、高) 和故事前提。

    該函式也會根據指定的故事創意程度傳回 temperature 值。這個值會做為 temperature 設定參數提供給模型,用於決定模型預測結果的隨機程度。max_output_tokens 設定參數會指定每則訊息生成的符記數量上限。

    系統會在分頁 UI 建立按鈕,供使用者點選生成回覆。使用者點選按鈕後,系統會叫用 get_gemini_pro_text_response 函式,我們會在研究室的下一個步驟編寫此程式碼。

開發 response_utils

response_utils.py 檔案包含生成模型回覆的函式。

  1. 執行下列指令碼,編寫生成模型文字回覆的程式碼:

    cat > ~/gemini-app/response_utils.py <<EOF from vertexai.preview.generative_models import (Content, GenerationConfig, GenerativeModel, GenerationResponse, Image, HarmCategory, HarmBlockThreshold, Part) def get_gemini_pro_text_response( model: GenerativeModel, prompt: str, generation_config: GenerationConfig, stream=True): safety_settings={ HarmCategory.HARM_CATEGORY_HARASSMENT: HarmBlockThreshold.BLOCK_NONE, HarmCategory.HARM_CATEGORY_HATE_SPEECH: HarmBlockThreshold.BLOCK_NONE, HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT: HarmBlockThreshold.BLOCK_NONE, HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT: HarmBlockThreshold.BLOCK_NONE, } responses = model.generate_content(prompt, generation_config = generation_config, safety_settings = safety_settings, stream=True) final_response = [] for response in responses: try: final_response.append(response.text) except IndexError: final_response.append("") continue return " ".join(final_response) EOF
  2. 查看 response_utils.py 檔案內容:

    cat ~/gemini-app/response_utils.py

    get_gemini_pro_text_response 函式會使用 Python 適用的 Vertex AI SDK 中 vertexai.preview.generative_models 套件內的 GenerativeModel 和其他類別。在類別的 generate_content 方法中,系統會使用傳遞至方法的文字提示生成回覆。

    safety_settings 物件也會傳遞至此方法,封鎖不安全的內容來控制模型的回覆。本研究室中,程式碼範例使用的安全性設定值會指示模型一律傳回內容,即使內容可能不安全。如果應用程式需要限制較多的設定,您可以評估生成內容,再調整這些設定。詳情請參閱安全設定說明文件。

工作 4:在本機執行與測試應用程式

在這項工作中,您會使用 streamlit 在本機執行應用程式,並測試應用程式功能。

執行應用程式

  1. 執行下列指令,在本機、Cloud Shell 執行應用程式:

    streamlit run app.py \ --browser.serverAddress=localhost \ --server.enableCORS=false \ --server.enableXsrfProtection=false \ --server.port 8080

    應用程式會啟動,並提供您存取應用程式的網址。

  2. 如要在瀏覽器中開啟應用程式首頁,請前往 Cloud Shell 選單列,依序點選「網頁預覽」和「透過以下通訊埠預覽:8080」

    透過以下通訊埠預覽:8080

    您也可以複製應用程式網址,並貼到不同的瀏覽器分頁來存取應用程式。

測試應用程式 -「Story」分頁

提供輸入內容來生成故事、查看提示及 Gemini 1.0 Pro 模型生成的回覆。

  1. 如要生成故事,請保留「Story」分頁預設設定,然後點選「Generate my story」

  2. 等待系統生成回覆,然後點選「Story response」分頁標籤

  3. 如要查看用來生成回覆的提示,請點選「Prompt」分頁標籤

  4. 前往 Cloud Shell 視窗,按下 Control-C 結束應用程式並返回命令提示字元。

點選「Check my progress」,確認目標已達成。 已開發應用程式「Story」分頁。

工作 5:生成行銷廣告活動

在這項工作中,您會使用 Gemini 1.0 Pro 文字模型,為公司生成行銷廣告活動。您會開發程式碼,在應用程式生成第二個分頁。

開發 tab2 -「Marketing Campaign」

  1. 執行下列指令來編寫程式碼,在應用程式 UI 轉譯「Marketing Campaign」分頁

    cat > ~/gemini-app/app_tab2.py <<EOF import streamlit as st from vertexai.preview.generative_models import GenerativeModel from response_utils import * import logging # create the model prompt based on user input. def generate_prompt(): st.write("Using Gemini 1.0 Pro - Text only model") st.subheader("Generate your marketing campaign") product_name = st.text_input("What is the name of the product? \n\n",key="product_name",value="ZomZoo") product_category = st.radio("Select your product category: \n\n",["Clothing","Electronics","Food","Health & Beauty","Home & Garden"],key="product_category",horizontal=True) st.write("Select your target audience: ") target_audience_age = st.radio("Target age: \n\n",["18-24","25-34","35-44","45-54","55-64","65+"],key="target_audience_age",horizontal=True) # target_audience_gender = st.radio("Target gender: \n\n",["male","female","trans","non-binary","others"],key="target_audience_gender",horizontal=True) target_audience_location = st.radio("Target location: \n\n",["Urban", "Suburban","Rural"],key="target_audience_location",horizontal=True) st.write("Select your marketing campaign goal: ") campaign_goal = st.multiselect("Select your marketing campaign goal: \n\n",["Increase brand awareness","Generate leads","Drive sales","Improve brand sentiment"],key="campaign_goal",default=["Increase brand awareness","Generate leads"]) if campaign_goal is None: campaign_goal = ["Increase brand awareness","Generate leads"] brand_voice = st.radio("Select your brand voice: \n\n",["Formal","Informal","Serious","Humorous"],key="brand_voice",horizontal=True) estimated_budget = st.radio("Select your estimated budget ($): \n\n",["1,000-5,000","5,000-10,000","10,000-20,000","20,000+"],key="estimated_budget",horizontal=True) prompt = f"""Generate a marketing campaign for {product_name}, a {product_category} designed for the age group: {target_audience_age}. The target location is this: {target_audience_location}. Aim to primarily achieve {campaign_goal}. Emphasize the product's unique selling proposition while using a {brand_voice} tone of voice. Allocate the total budget of {estimated_budget}. With these inputs, make sure to follow following guidelines and generate the marketing campaign with proper headlines: \n - Briefly describe the company, its values, mission, and target audience. - Highlight any relevant brand guidelines or messaging frameworks. - Provide a concise overview of the campaign's objectives and goals. - Briefly explain the product or service being promoted. - Define your ideal customer with clear demographics, psychographics, and behavioral insights. - Understand their needs, wants, motivations, and pain points. - Clearly articulate the desired outcomes for the campaign. - Use SMART goals (Specific, Measurable, Achievable, Relevant, and Time-bound) for clarity. - Define key performance indicators (KPIs) to track progress and success. - Specify the primary and secondary goals of the campaign. - Examples include brand awareness, lead generation, sales growth, or website traffic. - Clearly define what differentiates your product or service from competitors. - Emphasize the value proposition and unique benefits offered to the target audience. - Define the desired tone and personality of the campaign messaging. - Identify the specific channels you will use to reach your target audience. - Clearly state the desired action you want the audience to take. - Make it specific, compelling, and easy to understand. - Identify and analyze your key competitors in the market. - Understand their strengths and weaknesses, target audience, and marketing strategies. - Develop a differentiation strategy to stand out from the competition. - Define how you will track the success of the campaign. - Use relevant KPIs to measure performance and return on investment (ROI). Provide bullet points and headlines for the marketing campaign. Do not produce any empty lines. Be very succinct and to the point. """ return prompt # function to render the story tab, and call the model, and display the model prompt and response. def render_mktg_campaign_tab (text_model_pro: GenerativeModel): st.write("Using Gemini 1.0 Pro - Text only model") st.subheader("Generate a marketing campaign") prompt = generate_prompt() config = { "temperature": 0.8, "max_output_tokens": 2048, } generate_t2m = st.button("Generate campaign", key="generate_t2m") if generate_t2m and prompt: # st.write(prompt) with st.spinner("Generating a marketing campaign using Gemini..."): first_tab1, first_tab2 = st.tabs(["Campaign response", "Prompt"]) with first_tab1: response = get_gemini_pro_text_response(text_model_pro, prompt, generation_config=config) if response: st.write("Marketing campaign:") st.write(response) logging.info(response) with first_tab2: st.text(prompt) EOF

修改應用程式主要進入點

  • 執行下列指令,將 tab2 新增至應用程式:

    cat >> ~/gemini-app/app.py <<EOF from app_tab2 import render_mktg_campaign_tab with tab2: render_mktg_campaign_tab(text_model_pro) EOF

測試應用程式 -「Marketing campaign」分頁

提供輸入內容來生成行銷廣告活動、查看提示及 Gemini 1.0 Pro 模型生成的回覆。

  1. 執行下列指令,在本機、Cloud Shell 執行應用程式:

    streamlit run app.py \ --browser.serverAddress=localhost \ --server.enableCORS=false \ --server.enableXsrfProtection=false \ --server.port 8080

    應用程式會啟動,並提供您存取應用程式的網址。

  2. 如要在瀏覽器中開啟應用程式首頁,請前往 Cloud Shell 選單列,依序點選「網頁預覽」和「透過以下通訊埠預覽:8080」

  3. 如要生成行銷廣告活動,請保留「Marketing campaign」分頁預設設定,然後點選「Generate campaign」

  4. 等待系統生成回覆,然後點選「Campaign response」分頁標籤。

  5. 如要查看用來生成回覆的提示,請點選「Prompt」分頁標籤

  6. 重複上述步驟,即可透過產品類別、目標對象、地區及廣告活動目標等不同的參數值,生成行銷廣告活動。

  7. 前往 Cloud Shell 視窗,按下 Ctrl + C 結束應用程式並返回命令提示字元。

點選「Check my progress」,確認目標已達成。 已開發應用程式「Marketing Campaign」分頁。

工作 6:生成圖片園地

在這項工作中,您會使用 Gemini 1.0 Pro Vision 模型處理圖片,從提供給模型的圖片取得建議與資訊。

開發 tab3 -「Image Playground」

在這項子工作中,您會導入「Image Playground」分頁程式碼,以及與模型互動的程式碼,透過圖片生成建議。

  1. 執行下列指令來編寫程式碼,在應用程式 UI 轉譯「Image Playground」分頁

    cat > ~/gemini-app/app_tab3.py <<EOF import streamlit as st from vertexai.preview.generative_models import GenerativeModel, Part from response_utils import * import logging # render the Image Playground tab with multiple child tabs def render_image_playground_tab(multimodal_model_pro: GenerativeModel): st.write("Using Gemini 1.0 Pro Vision - Multimodal model") recommendations, screens, diagrams, equations = st.tabs(["Furniture recommendation", "Oven instructions", "ER diagrams", "Math reasoning"]) with recommendations: room_image_uri = "gs://cloud-training/OCBL447/gemini-app/images/living_room.jpeg" chair_1_image_uri = "gs://cloud-training/OCBL447/gemini-app/images/chair1.jpeg" chair_2_image_uri = "gs://cloud-training/OCBL447/gemini-app/images/chair2.jpeg" chair_3_image_uri = "gs://cloud-training/OCBL447/gemini-app/images/chair3.jpeg" chair_4_image_uri = "gs://cloud-training/OCBL447/gemini-app/images/chair4.jpeg" room_image_url = "https://storage.googleapis.com/"+room_image_uri.split("gs://")[1] chair_1_image_url = "https://storage.googleapis.com/"+chair_1_image_uri.split("gs://")[1] chair_2_image_url = "https://storage.googleapis.com/"+chair_2_image_uri.split("gs://")[1] chair_3_image_url = "https://storage.googleapis.com/"+chair_3_image_uri.split("gs://")[1] chair_4_image_url = "https://storage.googleapis.com/"+chair_4_image_uri.split("gs://")[1] room_image = Part.from_uri(room_image_uri, mime_type="image/jpeg") chair_1_image = Part.from_uri(chair_1_image_uri,mime_type="image/jpeg") chair_2_image = Part.from_uri(chair_2_image_uri,mime_type="image/jpeg") chair_3_image = Part.from_uri(chair_3_image_uri,mime_type="image/jpeg") chair_4_image = Part.from_uri(chair_4_image_uri,mime_type="image/jpeg") st.image(room_image_url,width=350, caption="Image of a living room") st.image([chair_1_image_url,chair_2_image_url,chair_3_image_url,chair_4_image_url],width=200, caption=["Chair 1","Chair 2","Chair 3","Chair 4"]) st.write("Our expectation: Recommend a chair that would complement the given image of a living room.") prompt_list = ["Consider the following chairs:", "chair 1:", chair_1_image, "chair 2:", chair_2_image, "chair 3:", chair_3_image, "and", "chair 4:", chair_4_image, "\n" "For each chair, explain why it would be suitable or not suitable for the following room:", room_image, "Only recommend for the room provided and not other rooms. Provide your recommendation in a table format with chair name and reason as columns.", ] tab1, tab2 = st.tabs(["Response", "Prompt"]) generate_image_description = st.button("Generate recommendation", key="generate_image_description") with tab1: if generate_image_description and prompt_list: with st.spinner("Generating recommendation using Gemini..."): response = get_gemini_pro_vision_response(multimodal_model_pro, prompt_list) st.markdown(response) logging.info(response) with tab2: st.write("Prompt used:") st.text(prompt_list) EOF
  2. 查看 app_tab3.py 檔案內容:

    cat ~/gemini-app/app_tab3.py

    render_image_playground_tab 函式建構的 UI 可讓應用程式使用者與 Gemini 1.0 Pro Vision 模型互動。該函式會在 UI 建立一系列分頁:「Furniture recommendation」(家具建議)、「Oven instructions」(烤箱操作說明)、「ER diagrams」(實體關係圖表) 和「Math reasoning」(數學推論)。您會在本研究室的子工作中,為其餘分頁編寫程式碼。

    在「Furniture recommendation」分頁中,客廳場景會用來執行圖像解讀作業。程式碼會指定一組椅子圖片,並叫用 Gemini 1.0 Pro Vision 多模態 API 端點,取得可搭配客廳場景的椅子建議。

    客廳場景

    程式碼會使用多個文字提示及客廳和椅子圖片,並以清單提供給模型。系統會使用 Part 類別,從託管於 Cloud Storage 值區的多部分內容 URI 取得圖片。提示也會指定以表格提供模型輸出內容,並附上建議理由。

更新 response_utils

response_utils.py 檔案包含生成模型回覆的函式。

  • 更新檔案,新增生成模型多模態回覆的程式碼:

    cat >> ~/gemini-app/response_utils.py <<EOF def get_gemini_pro_vision_response(model: GenerativeModel, prompt_list, generation_config={}, stream=True): generation_config = {'temperature': 0.1, 'max_output_tokens': 2048 } responses = model.generate_content(prompt_list, generation_config = generation_config, stream=True) final_response = [] for response in responses: try: final_response.append(response.text) except IndexError: final_response.append("") continue return(" ".join(final_response)) EOF

修改應用程式主要進入點

  • 執行下列指令,將 tab3 新增至應用程式:

    cat >> ~/gemini-app/app.py <<EOF from app_tab3 import render_image_playground_tab with tab3: render_image_playground_tab(multimodal_model_pro) EOF

測試應用程式 -「Image Playground」分頁

  1. 使用本研究室先前步驟提供的指令執行應用程式。

  2. 如要在瀏覽器中開啟應用程式首頁,請前往 Cloud Shell 選單列,依序點選「網頁預覽」和「透過以下通訊埠預覽:8080」

  3. 依序點選「Image Playground」和「Furniture recommendation」

    分頁會顯示「客廳」和「椅子」的圖片。

  4. 點選「Generate recommendation」

    如果收到下列錯誤:FailedPrecondition: 400 We are preparing necessary resources. Please wait few minutes and retry. (不符合先決條件:400 我們正在準備必要資源。請稍待片刻,然後再試一次。),請稍等幾分鐘再點選一次「Generate recommendation」
  5. 查看 Gemini 1.0 Pro Vision 模型的回覆。

    模型依提示要求以表格提供回覆,建議四張椅子中的兩張並附上建議理由。

  6. 前往 Cloud Shell 視窗,按下 Ctrl + C 結束應用程式並返回命令提示字元。

點選「Check my progress」,確認目標已達成。 已開發應用程式「Image Playground」和「Furniture recommendation」分頁。

工作 7:分析圖片配置

在這項工作中,您會使用 Gemini 1.0 Pro Vision 模型,在分析文字與圖片的圖示配置後,從中擷取資訊。

更新「Image Playground」分頁 - 烤箱操作說明

Gemini 能夠從畫面上的圖像元素擷取資訊,分析螢幕截圖、圖示及配置來全面解讀描繪的場景。在這項工作中,您會提供廚房烤箱控制面板的圖片給模型,並提示模型生成特定功能的操作說明。

  • 執行下列指令,在應用程式 UI 為「Image Playground」分頁導入「Oven instructions」分頁程式碼:

    cat >> ~/gemini-app/app_tab3.py <<EOF with screens: oven_screen_uri = "gs://cloud-training/OCBL447/gemini-app/images/oven.jpg" oven_screen_url = "https://storage.googleapis.com/"+oven_screen_uri.split("gs://")[1] oven_screen_img = Part.from_uri(oven_screen_uri, mime_type="image/jpeg") st.image(oven_screen_url, width=350, caption="Image of an oven control panel") st.write("Provide instructions for resetting the clock on this appliance in English") prompt = """How can I reset the clock on this appliance? Provide the instructions in English. If instructions include buttons, also explain where those buttons are physically located. """ tab1, tab2 = st.tabs(["Response", "Prompt"]) generate_instructions_description = st.button("Generate instructions", key="generate_instructions_description") with tab1: if generate_instructions_description and prompt: with st.spinner("Generating instructions using Gemini..."): response = get_gemini_pro_vision_response(multimodal_model_pro, [oven_screen_img, prompt]) st.markdown(response) logging.info(response) with tab2: st.write("Prompt used:") st.text(prompt+"\n"+"input_image") EOF

    上方程式碼會建構「Oven instructions」分頁 UI。您使用文字和廚房烤箱控制面板的圖片,提示模型生成面板上特定功能的操作說明,在本例中是重設時鐘。

    烤箱控制面板

測試應用程式 -「Image playground」-「Oven instructions」分頁

  1. 使用本研究室先前步驟提供的指令執行應用程式。

  2. 如要在瀏覽器中開啟應用程式首頁,請前往 Cloud Shell 選單列,依序點選「網頁預覽」和「透過以下通訊埠預覽:8080」

  3. 依序點選「Image Playground」和「Oven instructions」

    分頁會顯示烤箱控制面板的圖片。

  4. 點選「Generate instructions」

  5. 查看 Gemini 1.0 Pro Vision 模型的回覆。

    回覆包含在烤箱控制面板上重設時鐘的步驟,以及找出面板按鈕位置的指示,展現模型分析圖片中面板配置的能力。

  6. 前往 Cloud Shell 視窗,按下 Ctrl + C 結束應用程式並返回命令提示字元。

點選「Check my progress」,確認目標已達成。 已開發「Image Playground」和「Oven instructions」分頁。

工作 8:分析實體關係圖表

Gemini 的多模態功能可理解圖表並採取可行步驟,例如生成文件或程式碼。在這項工作中,您會使用 Gemini 1.0 Pro Vision 模型分析實體關係圖表,並根據圖表中的實體與關係生成說明文件。

更新「Image Playground」分頁 - 實體關係圖表

在這項工作中,您會提供實體關係圖表的圖片給模型,並提示模型生成說明文件。

  • 執行下列指令,在應用程式 UI 為「Image Playground」分頁導入「ER diagrams」分頁程式碼:

    cat >> ~/gemini-app/app_tab3.py <<EOF with diagrams: er_diag_uri = "gs://cloud-training/OCBL447/gemini-app/images/er.png" er_diag_url = "https://storage.googleapis.com/"+er_diag_uri.split("gs://")[1] er_diag_img = Part.from_uri(er_diag_uri,mime_type="image/png") st.image(er_diag_url, width=350, caption="Image of an ER diagram") st.write("Document the entities and relationships in this ER diagram.") prompt = """Document the entities and relationships in this ER diagram.""" tab1, tab2 = st.tabs(["Response", "Prompt"]) er_diag_img_description = st.button("Generate documentation", key="er_diag_img_description") with tab1: if er_diag_img_description and prompt: with st.spinner("Generating..."): response = get_gemini_pro_vision_response(multimodal_model_pro,[er_diag_img,prompt]) st.markdown(response) logging.info(response) with tab2: st.write("Prompt used:") st.text(prompt+"\n"+"input_image") EOF

    上方程式碼會建構「ER diagrams」分頁 UI。您使用文字和實體關係圖表的圖片,提示模型生成說明文件,說明圖表中的實體與關係。

    實體關係圖表

測試應用程式 -「Image playground」-「ER diagrams」分頁

  1. 使用本研究室先前步驟提供的指令執行應用程式。

  2. 如要在瀏覽器中開啟應用程式首頁,請前往 Cloud Shell 選單列,依序點選「網頁預覽」和「透過以下通訊埠預覽:8080」

  3. 依序點選「Image Playground」和「ER diagrams」

    分頁會顯示實體關係圖表的圖片。

  4. 點選「Generate documentation」

  5. 查看 Gemini 1.0 Pro Vision 模型的回覆。

    回覆列出在圖表中的實體,以及實體之間的關係。

  6. 前往 Cloud Shell 視窗,按下 Ctrl + C 結束應用程式並返回命令提示字元。

點選「Check my progress」,確認目標已達成。 已開發「Image Playground」和「ER diagrams」分頁。

工作 9:數學推論

Gemini 1.0 Pro Vision 也能辨識數學公式和方程式,並從中擷取特定資訊。這項功能特別適用於生成數學問題的解答。

更新「Image Playground」分頁 - 數學推論

在這項工作中,您會使用 Gemini 1.0 Pro Vision 模型,從圖片擷取數學公式並解讀。

  • 執行下列指令,在應用程式 UI 為「Image Playground」分頁導入「Math reasoning」分頁程式碼:

    cat >> ~/gemini-app/app_tab3.py <<EOF with equations: math_image_uri = "gs://cloud-training/OCBL447/gemini-app/images/math_eqn.jpg" math_image_url = "https://storage.googleapis.com/"+math_image_uri.split("gs://")[1] math_image_img = Part.from_uri(math_image_uri,mime_type="image/jpeg") st.image(math_image_url,width=350, caption="Image of a math equation") st.markdown(f""" Ask questions about the math equation as follows: - Extract the formula. - What is the symbol right before Pi? What does it mean? - Is this a famous formula? Does it have a name? """) prompt = """Follow the instructions. Surround math expressions with $. Use a table with a row for each instruction and its result. INSTRUCTIONS: - Extract the formula. - What is the symbol right before Pi? What does it mean? - Is this a famous formula? Does it have a name? """ tab1, tab2 = st.tabs(["Response", "Prompt"]) math_image_description = st.button("Generate answers", key="math_image_description") with tab1: if math_image_description and prompt: with st.spinner("Generating answers for formula using Gemini..."): response = get_gemini_pro_vision_response(multimodal_model_pro, [math_image_img, prompt]) st.markdown(response) logging.info(response) with tab2: st.write("Prompt used:") st.text(prompt) EOF

    上方程式碼會建構「Math reasoning」分頁 UI。您使用文字和數學方程式的圖片,提示模型生成方程式的解答及其他特點。

    數學方程式

測試應用程式 -「Image playground」-「Math reasoning」分頁

  1. 使用本研究室先前步驟提供的指令執行應用程式。

  2. 如要在瀏覽器中開啟應用程式首頁,請前往 Cloud Shell 選單列,依序點選「網頁預覽」和「透過以下通訊埠預覽:8080」

  3. 依序點選「Image Playground」和「Math reasoning」

    分頁會顯示含有數學方程式的圖片。

  4. 點選「Generate answers」

  5. 查看 Gemini 1.0 Pro Vision 模型的回覆。

    回覆包含提示中問題的解答。

  6. 前往 Cloud Shell 視窗,按下 Ctrl + C 結束應用程式並返回命令提示字元。

點選「Check my progress」,確認目標已達成。 已開發「Image Playground」和「Math reasoning」分頁。

工作 10:生成影片園地

在這項工作中,您會使用 Gemini 1.0 Pro Vision 模型處理影片,從提供給模型的影片生成標記和資訊。

開發 tab4 -「Video Playground」

Gemini 1.0 Pro Vision 模型也能說明影片內容。在這項子工作中,您會導入「Video Playground」分頁程式碼,以及與模型互動的程式碼來生成影片說明。

  1. 執行下列指令來編寫程式碼,在應用程式 UI 轉譯「Video Playground」分頁

    cat > ~/gemini-app/app_tab4.py <<EOF import streamlit as st from vertexai.preview.generative_models import GenerativeModel, Part from response_utils import * import logging # render the Video Playground tab with multiple child tabs def render_video_playground_tab(multimodal_model_pro: GenerativeModel): st.write("Using Gemini 1.0 Pro Vision - Multimodal model") video_desc, video_tags, video_highlights, video_geoloc = st.tabs(["Video description", "Video tags", "Video highlights", "Video geolocation"]) with video_desc: video_desc_uri = "gs://cloud-training/OCBL447/gemini-app/videos/mediterraneansea.mp4" video_desc_url = "https://storage.googleapis.com/"+video_desc_uri.split("gs://")[1] video_desc_vid = Part.from_uri(video_desc_uri, mime_type="video/mp4") st.video(video_desc_url) st.write("Generate a description of the video.") prompt = """Describe what is happening in the video and answer the following questions: \n - What am I looking at? - Where should I go to see it? - What are other top 5 places in the world that look like this? """ tab1, tab2 = st.tabs(["Response", "Prompt"]) video_desc_description = st.button("Generate video description", key="video_desc_description") with tab1: if video_desc_description and prompt: with st.spinner("Generating video description"): response = get_gemini_pro_vision_response(multimodal_model_pro, [prompt, video_desc_vid]) st.markdown(response) logging.info(response) with tab2: st.write("Prompt used:") st.write(prompt,"\n","{video_data}") EOF
  2. 查看 app_tab4.py 檔案內容:

    cat ~/gemini-app/app_tab4.py

    render_video_playground_tab 函式建構的 UI 可讓應用程式使用者與 Gemini 1.0 Pro Vision 模型互動。該函式會在 UI 建立一系列分頁:「Video description」(影片說明)、「Video tags」(影片標記)、「Video highlights」(影片重點) 和「Video geolocation」(影片地理位置)。您會在本研究室的子工作中,為其餘分頁編寫程式碼。

    Video description」分頁會使用提示及影片來生成影片說明,並找出與影片中地點相似的其他地方。

修改應用程式主要進入點

  • 執行下列指令,將 tab4 新增至應用程式:

    cat >> ~/gemini-app/app.py <<EOF from app_tab4 import render_video_playground_tab with tab4: render_video_playground_tab(multimodal_model_pro) EOF

測試應用程式 -「Video Playground」分頁

  1. 使用本研究室先前步驟提供的指令執行應用程式。

  2. 如要在瀏覽器中開啟應用程式首頁,請前往 Cloud Shell 選單列,依序點選「網頁預覽」和「透過以下通訊埠預覽:8080」

  3. 依序點選「Video Playground」和「Video description」

  4. 分頁會顯示某地點的影片。點選即可播放影片。

  5. 點選「Generate video description」

  6. 查看 Gemini 1.0 Pro Vision 模型的回覆。

    回覆包含該地點的說明,以及其他 5 個相似的地方。

  7. 前往 Cloud Shell 視窗,按下 Ctrl + C 結束應用程式並返回命令提示字元。

點選「Check my progress」,確認目標已達成。 已開發應用程式「Video Playground」和「Video description」分頁。

工作 11:生成影片標記

在這項工作中,您會使用 Gemini 1.0 Pro Vision 模型,透過影片生成標記。

更新「Video Playground」分頁 - 影片標記

  • 執行下列指令,在應用程式 UI 為「Video Playground」分頁導入「Video tags」分頁程式碼:

    cat >> ~/gemini-app/app_tab4.py <<EOF with video_tags: video_tags_uri = "gs://cloud-training/OCBL447/gemini-app/videos/photography.mp4" video_tags_url = "https://storage.googleapis.com/"+video_tags_uri.split("gs://")[1] video_tags_vid = Part.from_uri(video_tags_uri, mime_type="video/mp4") st.video(video_tags_url) st.write("Generate tags for the video.") prompt = """Answer the following questions using the video only: 1. What is in the video? 2. What objects are in the video? 3. What is the action in the video? 4. Provide 5 best tags for this video? Write the answer in table format with the questions and answers in columns. """ tab1, tab2 = st.tabs(["Response", "Prompt"]) video_tags_desc = st.button("Generate video tags", key="video_tags_desc") with tab1: if video_tags_desc and prompt: with st.spinner("Generating video tags"): response = get_gemini_pro_vision_response(multimodal_model_pro, [prompt, video_tags_vid]) st.markdown(response) logging.info(response) with tab2: st.write("Prompt used:") st.write(prompt,"\n","{video_data}") EOF

    上方程式碼會建構「Video tags」分頁 UI。您使用文字和影片,提示模型生成標記並回答與影片場景相關的問題。

測試應用程式 -「Video Playground」-「Video tags」分頁

  1. 使用本研究室先前步驟提供的指令執行應用程式。

  2. 如要在瀏覽器中開啟應用程式首頁,請前往 Cloud Shell 選單列,依序點選「網頁預覽」和「透過以下通訊埠預覽:8080」

  3. 依序點選「Video Playground」和「Video tags」

  4. 分頁會顯示用於提示模型的影片。點選即可播放影片。

  5. 點選「Generate video tags」

  6. 查看 Gemini 1.0 Pro Vision 模型的回覆。

    回覆包含提示中問題的解答。模型按要求以表格輸出問題與答案,並附上 5 個標記。

  7. 前往 Cloud Shell 視窗,按下 Ctrl + C 結束應用程式並返回命令提示字元。

點選「Check my progress」,確認目標已達成。 已開發「Video Playground」和「Video tags」分頁。

工作 12:生成影片重點

在這項工作中,您會使用 Gemini 1.0 Pro Vision 模型,透過影片生成重點,其中包含與影片中物品、人物及情境相關的資訊。

更新「Video Playground」分頁 - 影片重點

  • 執行下列指令,在應用程式 UI 為「Video Playground」分頁導入「Video highlights」分頁程式碼:

    cat >> ~/gemini-app/app_tab4.py <<EOF with video_highlights: video_highlights_uri = "gs://cloud-training/OCBL447/gemini-app/videos/pixel8.mp4" video_highlights_url = "https://storage.googleapis.com/"+video_highlights_uri.split("gs://")[1] video_highlights_vid = Part.from_uri(video_highlights_uri, mime_type="video/mp4") st.video(video_highlights_url) st.write("Generate highlights for the video.") prompt = """Answer the following questions using the video only: What is the profession of the girl in this video? Which features of the phone are highlighted here? Summarize the video in one paragraph. Write these questions and their answers in table format. """ tab1, tab2 = st.tabs(["Response", "Prompt"]) video_highlights_description = st.button("Generate video highlights", key="video_highlights_description") with tab1: if video_highlights_description and prompt: with st.spinner("Generating video highlights"): response = get_gemini_pro_vision_response(multimodal_model_pro, [prompt, video_highlights_vid]) st.markdown(response) logging.info(response) with tab2: st.write("Prompt used:") st.write(prompt,"\n","{video_data}") EOF

    上方程式碼會建構「Video highlights」分頁 UI。您使用文字和影片,提示模型生成影片重點。

測試應用程式 -「Video Playground」-「Video highlights」分頁

  1. 使用本研究室先前步驟提供的指令執行應用程式。

  2. 如要在瀏覽器中開啟應用程式首頁,請前往 Cloud Shell 選單列,依序點選「網頁預覽」和「透過以下通訊埠預覽:8080」

  3. 依序點選「Video Playground」和「Video highlights」

  4. 分頁會顯示用於提示模型的影片。點選即可播放影片。

  5. 點選「Generate video highlights」

  6. 查看 Gemini 1.0 Pro Vision 模型的回覆。

    回覆包含提示中問題的解答。模型以表格輸出問題與答案,並列出影片內容的特徵,包括女生的職業,以及使用的手機功能。回覆也包含影片場景的簡短敘述。

  7. 前往 Cloud Shell 視窗,按下 Ctrl + C 結束應用程式並返回命令提示字元。

點選「Check my progress」,確認目標已達成。 已開發「Video Playground」和「Video highlights」分頁。

工作 13:生成影片地理位置

在這項工作中,您會使用 Gemini 1.0 Pro Vision 模型判斷影片場景的位置。

更新「Video Playground」分頁 - 影片地理位置

  • 執行下列指令,在應用程式 UI 為「Video Playground」分頁導入「Video geolocation」分頁程式碼:

    cat >> ~/gemini-app/app_tab4.py <<EOF with video_geoloc: video_geolocation_uri = "gs://cloud-training/OCBL447/gemini-app/videos/bus.mp4" video_geolocation_url = "https://storage.googleapis.com/"+video_geolocation_uri.split("gs://")[1] video_geolocation_vid = Part.from_uri(video_geolocation_uri, mime_type="video/mp4") st.video(video_geolocation_url) st.markdown("""Answer the following questions from the video: - What is this video about? - How do you know which city it is? - What street is this? - What is the nearest intersection? """) prompt = """Answer the following questions using the video only: What is this video about? How do you know which city it is? What street is this? What is the nearest intersection? Answer the following questions using a table format with the questions and answers as columns. """ tab1, tab2 = st.tabs(["Response", "Prompt"]) video_geolocation_description = st.button("Generate", key="video_geolocation_description") with tab1: if video_geolocation_description and prompt: with st.spinner("Generating location information"): response = get_gemini_pro_vision_response(multimodal_model_pro, [prompt, video_geolocation_vid]) st.markdown(response) logging.info(response) with tab2: st.write("Prompt used:") st.write(prompt,"\n","{video_data}") EOF

    上方程式碼會建構「Video geolocation」分頁 UI。您使用文字和影片,提示模型回答影片相關問題,包括影片中實體的位置資訊。

測試應用程式 -「Video Playground」-「Video geolocation」分頁

  1. 使用本研究室先前步驟提供的指令執行應用程式。

  2. 如要在瀏覽器中開啟應用程式首頁,請前往 Cloud Shell 選單列,依序點選「網頁預覽」和「透過以下通訊埠預覽:8080」

  3. 依序點選「Video Playground」和「Video geolocation」

  4. 分頁會顯示用於提示模型的影片。點選即可播放影片。

  5. 點選「Generate」

  6. 查看 Gemini 1.0 Pro Vision 模型的回覆。

    回覆包含提示中問題的解答。模型按要求以表格輸出問題與答案,並附上位置資訊。

  7. 前往 Cloud Shell 視窗,按下 Ctrl + C 結束應用程式並返回命令提示字元。

點選「Check my progress」,確認目標已達成。 已開發「Video Playground」和「Video geolocation」分頁。

工作 14:將應用程式部署至 Cloud Run

在本機測試應用程式後,即可部署至 Google Cloud 的 Cloud Run 供其他人使用。Cloud Run 是代管運算平台,能讓您在 Google 可擴充的基礎架構上執行應用程式容器。

設定環境

  1. 確認您位於 app 目錄:

    cd ~/gemini-app
  2. 確認已設定 PROJECT_ID 和 REGION 環境變數:

    echo "PROJECT_ID=${PROJECT_ID}" echo "REGION=${REGION}"
  3. 如果尚未設定上述環境變數,請執行下列指令:

    PROJECT_ID=$(gcloud config get-value project) REGION={{{project_0.default_region|set at lab start}}} echo "PROJECT_ID=${PROJECT_ID}" echo "REGION=${REGION}"
  4. 為服務和構件存放區設定環境變數:

    SERVICE_NAME='gemini-app-playground' # Name of your Cloud Run service. AR_REPO='gemini-app-repo' # Name of your repository in Artifact Registry that stores your application container image. echo "SERVICE_NAME=${SERVICE_NAME}" echo "AR_REPO=${AR_REPO}"

建立 Docker 存放區

  1. 執行下列指令,在 Artifact Registry 建立存放區:

    gcloud artifacts repositories create "$AR_REPO" --location="$REGION" --repository-format=Docker Artifact Registry 是 Google Cloud 服務,可讓您在同一位置儲存及管理軟體套件和 Docker 容器映像檔。
  2. 設定存放區驗證機制:

    gcloud auth configure-docker "$REGION-docker.pkg.dev"

建構容器映像檔

我們會使用 Dockerfile 為應用程式建構容器映像檔。Dockerfile 是文字文件,包含使用者可透過指令列呼叫來建立容器映像檔的所有指令。這份文件會與 Docker 一起使用,Docker 是建構與執行容器映像檔的容器平台。

  1. 執行下列指令,建立 Dockerfile

    cat > ~/gemini-app/Dockerfile <<EOF FROM python:3.8 EXPOSE 8080 WORKDIR /app COPY . ./ RUN pip install -r requirements.txt ENTRYPOINT ["streamlit", "run", "app.py", "--server.port=8080", "--server.address=0.0.0.0"] EOF
  2. 執行下列指令,為應用程式建構容器映像檔:

    gcloud builds submit --tag "$REGION-docker.pkg.dev/$PROJECT_ID/$AR_REPO/$SERVICE_NAME" gcloud builds submit 指令會提交使用 Cloud Build 執行的建構作業。與 tag 旗標搭配使用時,Cloud Build 會用運 Dockerfile,透過來源目錄中的應用程式檔案建構容器映像檔。

    Cloud Build 服務可在 Google Cloud 根據規格執行建構作業,並產生 Docker 容器或 Java 封存檔等構件。

    請等指令完成再繼續下一個步驟。

在 Cloud Run 部署和測試應用程式

最後一項工作是將服務部署至 Cloud Run,連同建構完成並推送至 Artifact Registry 存放區的映像檔。

  1. 執行下列指令,將應用程式部署至 Cloud Run:

    gcloud run deploy "$SERVICE_NAME" \ --port=8080 \ --image="$REGION-docker.pkg.dev/$PROJECT_ID/$AR_REPO/$SERVICE_NAME" \ --allow-unauthenticated \ --region=$REGION \ --platform=managed \ --project=$PROJECT_ID \ --set-env-vars=PROJECT_ID=$PROJECT_ID,REGION=$REGION
  2. 部署服務後,上一個指令的輸出內容會包含服務的網址。如要在 Cloud Run 上測試應用程式,請在不同的瀏覽器分頁或視窗中前往該網址。

  3. 選擇要測試的應用程式功能。應用程式會提示 Vertex AI Gemini API 生成並顯示回覆。

點選「Check my progress」,確認目標已達成。 應用程式已部署至 Cloud Run。

關閉研究室

如果您已完成研究室,請按一下「End Lab」(關閉研究室)。Qwiklabs 會移除您已用的資源,並清除使用帳戶。

您可以為研究室的使用體驗評分。請選取合適的星級評等並提供意見,然後按一下「Submit」(提交)

星級評等代表您的滿意程度:

  • 1 星 = 非常不滿意
  • 2 星 = 不滿意
  • 3 星 = 普通
  • 4 星 = 滿意
  • 5 星 = 非常滿意

如果不想提供意見回饋,您可以直接關閉對話方塊。

如有任何想法、建議或指教,請透過「Support」(支援) 分頁提交。

恭喜!

在本研究室中,您完成了下列工作:

  • 運用 Streamlit 架構開發 Python 應用程式。
  • 安裝 Python 適用的 Vertex AI SDK。
  • 使用 Vertex AI Gemini API 開發程式碼與 Gemini 1.0 Pro 模型 (gemini-pro) 互動。
  • 透過文字提示模型生成故事和行銷廣告活動。
  • 使用 Vertex AI Gemini API 開發程式碼與 Gemini 1.0 Pro Vision 模型 (gemini-pro-vision) 互動。
  • 使用文字、圖片及影片,讓模型處理圖片和影片並從中擷取資訊。
  • 在 Cloud Run 部署和測試應用程式。

後續步驟/瞭解詳情

Copyright 2023 Google LLC 保留所有權利。Google 和 Google 標誌是 Google LLC 的商標,其他公司和產品名稱則有可能是其關聯公司的商標。

此内容目前不可用

We will notify you via email when it becomes available

太好了!

We will contact you via email if it becomes available