1. 學習內容
AI 代理程式 Vibe 全端
歡迎!您即將學習軟體開發的下一個重要技能:如何有效引導人工智慧建構、測試及部署生產級軟體。生成式 AI 並非「自動駕駛」,而是需要熟練的導演才能發揮威力的「副駕駛」。
本研討會提供可重複使用的結構化方法,協助您在專業軟體開發生命週期 (SDLC) 的每個階段與 AI 合作。您將從逐行編寫程式碼的程式設計師,轉變為技術總監,也就是有遠見的架構師,以及運用 AI 精準執行遠見的總承包商。🚀
完成本教學課程後,您將:
- 使用 AI 將高階概念轉換為雲端架構。
- 透過明確的提示,生成完整的 Python 後端。
- 使用 AI 擔任程式設計師,協助偵錯及修正程式碼。
- 將單元測試 (包括模擬) 的建立作業委派給 AI。
- 使用 Terraform 產生可供正式環境使用的基礎架構即程式碼 (IaC)。
- 在 GitHub Actions 中,使用單一提示建立完整的 CI/CD pipeline。
- 使用 AI 輔助作業工具監控及管理上線的應用程式。
您不僅能帶回可運作的應用程式,還能獲得 AI 輔助開發的藍圖。我們馬上開始!
2. 事前準備和設定
開始之前,請先準備好環境。這是確保研討會順利進行的重要步驟。
建立新的 GCP 帳戶並連結帳單
如要為 AI 代理程式提供支援,我們需要兩項資源:提供基礎的 Google Cloud 專案,以及用來存取 Google 強大模型的 Gemini API 金鑰。
步驟 1:啟用帳單帳戶
- 請先申請帳單帳戶並取得 $5 美元抵免額,以便部署應用程式。請務必使用 Gmail 帳戶。
步驟 2:建立新的 GCP 專案
- 前往 Google Cloud 控制台,然後建立新專案。
- 開啟左側面板,按一下
Billing
,確認帳單帳戶是否已連結至這個 GCP 帳戶。
如果看到這個頁面,請檢查 manage billing account
,選擇 Google Cloud Trial One 並連結至該頁面。
步驟 3:產生 Gemini API 金鑰
您必須先擁有金鑰,才能保護金鑰。
- 前往 Google AI Studio:https://aistudio.google.com/
- 使用 Gmail 帳戶登入。
- 按一下「取得 API 金鑰」按鈕,通常位於左側導覽窗格或右上角。
- 在「API keys」對話方塊中,按一下「Create API key in new project」(在新專案中建立 API 金鑰)。
- 選擇您建立的新專案,並設定帳單帳戶。
- 系統會為您產生新的 API 金鑰。立即複製這組金鑰,並暫時存放在安全的地方 (例如密碼管理工具或安全記事)。您會在後續步驟中使用這個值。
GitHub 驗證
前往 Google Cloud 控制台,然後點選右上角的「啟用 Cloud Shell」按鈕,即可開啟 Cloud Shell。
步驟 1:開啟 Cloud Shell
👉按一下 Google Cloud 控制台頂端的「啟用 Cloud Shell」(這是 Cloud Shell 窗格頂端的終端機形狀圖示)
👉按一下「Open Editor」(開啟編輯器) 按鈕 (類似於開啟資料夾和鉛筆的圖示)。這會在視窗中開啟 Cloud Shell 程式碼編輯器。左側會顯示檔案總管。
👉開啟編輯器後,在雲端 IDE 中開啟終端機,
👉💻 在終端機中,使用下列指令驗證您是否已通過驗證,以及專案是否已設為您的專案 ID:
gcloud auth list
步驟 2:透過 GitHub 驗證並 Fork
透過 GitHub 進行驗證:
👉💻 複製指令並貼到雲端終端機:
gh auth login
- 在「Where do you use GitHub」(你在哪裡使用 GitHub) 中,選擇「GitHub.com」
- 「What is you preferred protocol for Git operations on this host?」(您偏好使用哪種通訊協定,在這個主機上執行 Git 作業?),選擇「HTTPS」
- 「Authenticate Git with your GitHub credentials?」(是否要使用 GitHub 憑證驗證 Git?),選擇「Yes」(是)
- 「How would you like to authenticate GitHub CLI?」(您要如何驗證 GitHub CLI?),選擇「Login with a web browser」(透過網路瀏覽器登入)
重要事項:請勿按下「Enter」鍵
從終端機複製驗證碼,然後貼到登入驗證頁面
輸入程式碼後,請返回 Cloud Shell 終端機,然後按下「Enter」鍵繼續操作。
步驟 4:分叉及複製存放區:
👉💻 複製指令並貼到雲端終端機:
gh repo fork cuppibla/storygen-learning --clone=true
3. 架構:從構想變成藍圖 (Cloud Assist)
每個偉大的專案都始於明確的願景。我們將使用 AI 副駕駛 Cloud Assist 設計應用程式架構。
動作
- 開啟 Google Cloud 控制台:[https://console.cloud.google.com](Google Cloud 控制台)
- 按一下右上角的「開啟 Cloud Assist Chat」
啟用 Cloud Assist
- 依序按一下
Get Gemini Assist
和Enable Cloud Assist at no cost
。 - 開始聊天!
向 Cloud Assist 提供下列詳細提示:
輸入想法
Generate a Python web application that uses AI to generate children's stories and illustrations. It has Python backend and React frontend host separately on Cloudrun. They communicate through Websocket. It needs to use a generative model for text and another for images. The generated images must be used by Imagen from Vertex AI and stored in a Google Cloud Storage bucket so that frontend can fetch from the bucket to render images. I do not want any load balancer or a database for the story text. We need a solution to store the API key.
取得應用程式藍圖
- 按一下「編輯應用程式設計」,您會看到圖表。按一下右上方面板的「<> 取得程式碼」,即可下載 Terraform 程式碼。
- Cloud Assist 會生成架構圖。這是我們的視覺藍圖。
您無須對此代碼採取任何行動。詳情請參閱下文
瞭解產生的 Terraform 程式碼。您剛收到 Cloud Assist 傳送的一組完整 Terraform 檔案。目前不需要對這段程式碼採取任何行動,但我們先快速瞭解這段程式碼的用途,以及為何如此強大。
什麼是 Terraform?Terraform 是基礎架構即程式碼 (IaC) 工具,您可以將其視為以程式碼編寫的雲端環境藍圖。您不必手動點選 Google Cloud 控制台來建立服務、儲存空間和權限,而是要在這些設定檔中定義所有資源。接著 Terraform 會讀取藍圖,並自動為您建構完全相同的環境。
從視覺化計畫到可執行的程式碼。Cloud Assist 提供的架構圖就是您的視覺化計畫。Terraform 程式碼是該計畫的機器可讀版本。這是將設計概念轉化為可重現的自動化實體的關鍵環節。以程式碼定義基礎架構的好處包括:
- 自動建立:反覆建構相同的環境。
- 使用版本管控:在 Git 中追蹤基礎架構的變更,就像追蹤應用程式程式碼一樣。
- 避免錯誤:避免透過網頁介面點選時可能發生的人為錯誤。
在本研討會中,您不需要自行執行這段 Terraform 程式碼。您可以將其視為專業藍圖,也就是您在後續步驟中建構及部署基礎架構的「答案」。
4. 開發:Gemini CLI 簡介
👉💻 在 Cloud Shell 終端機中,前往個人目錄。
cd ~/storygen-learning
👉💻 首次試用 Gemini。
clear
gemini --model=gemini-2.5-flash
如果系統詢問 Do you want to connect Cloud Shell editor to Gemini CLI?
,請選擇「否」。
👉✨ 每個 Gemini 工具都有說明。立即閱讀。在 Gemini 提示中輸入:
在 Gemini CLI 中
/help
👉✨ Gemini CLI 內建一組功能。如要檢查這些項目,請按照下列步驟操作:
在 Gemini CLI 中
/tools
清單會顯示 ReadFile
、WriteFile
和 GoogleSearch
等項目。這些是預設技術,您可直接呼叫,不必從外部工具庫中提取。
👉✨ Gemini Blade 可以掌握「戰術意識」(脈絡),引導後續動作。
在 Gemini CLI 中
/memory show
目前為空白狀態。
👉✨ 首先,將角色新增至服務專員的記憶體。這會定義其專業領域:
在 Gemini CLI 中
/memory add "I am master at python development"
再次執行 /memory show
,確認刀鋒伺服器已吸收這項知識。
👉✨ 為示範如何使用 @ 符號參照檔案,我們先建立「任務簡報」檔案。
開啟新的終端機,然後執行下列指令來建立任務檔案:
!echo "## Mission Objective: Create Imagen ADK Agent for Story Book" > mission.md
👉✨現在,請使用 Gemini CLI 分析簡報並回報結果:
在 Gemini CLI 中
Explain the contents of the file @mission.md
現在,主要武器已瞭解目標。
👉💻 按下 Ctrl+C
鍵兩次,即可結束 Gemini CLI
學習:
Gemini CLI 如何獲得超能力:gemini.md 在繼續之前,請務必瞭解如何根據特定專案調整 Gemini CLI。雖然你可以將其做為一般用途的聊天工具,但 gemini.md 這個特殊設定檔才是真正的強大之處。
執行 gemini 指令時,系統會自動在目前目錄中尋找 gemini.md 檔案。這個檔案就像是專案專屬的 AI 指令手冊,它可以定義三項重要事項:
- 人物角色:你可以告訴 AI 該角色應有的特質。例如:「您是專精於 Google Cloud 的 Python 開發人員。」這會影響回覆內容和風格。
- 工具:你可以授予存取特定檔案 (@file.py) 甚至是 Google 搜尋 (@google) 的權限。讓 AI 瞭解專案程式碼的背景資訊,以便回答相關問題。
- 記憶體:您可以提供 AI 應始終記住的事實或規則,有助於維持一致性。
只要使用 gemini.md
檔案,就能將一般 Gemini 模型變成專門的助理,事先瞭解專案目標並存取正確資訊。
5. 開發:使用 Gemini CLI 建構 ADK
初始設定
請務必使用 Gemini CLI 分叉存放區,並準備工作區:
環境設定
前往 Cloud Shell,然後按一下「Open Terminal」(開啟終端機) 按鈕。
- 複製環境範本:
cd ~/storygen-learning cp ~/storygen-learning/env.template ~/storygen-learning/.env
在編輯器中查看隱藏檔案 (如果找不到 .env)
- 按一下頂端選單列中的「查看」。
- 選取「切換隱藏檔案」。
👉找出 Google Cloud 專案 ID:
- 開啟 Google Cloud 控制台:連結
- 在頁面頂端的專案下拉式選單中,選取要用於本研討會的專案。
- 專案 ID 會顯示在資訊主頁的「專案資訊」資訊卡中
👉找出 GitHub 使用者名稱:
- 前往 GitHub 並找出 GitHub 使用者名稱
編輯 .env 檔案 2. 在 .env
中替換下列值:
GOOGLE_API_KEY=[REPLACE YOUR API KEY HERE]
GOOGLE_CLOUD_PROJECT_ID=[REPLACE YOUR PROJECT ID]
GITHUB_USERNAME=[REPLACE YOUR USERNAME]
GENMEDIA_BUCKET=[REPLACE YOUR PROJECT ID]-bucket
例如,如果專案 ID 為 testproject
,則應輸入 GOOGLE_CLOUD_PROJECT_ID=testproject
和 GENMEDIA_BUCKET=testproject-bucket
設定指令碼
前往 00_Starting_Here 開啟新的終端機 (不是 Gemini CLI)
cd ~/storygen-learning/00_Starting_Here
執行完整設定:
./setup-complete.sh
終端機應會顯示設定結果
建立第一個代理程式
前往 01a_First_Agent_Ready。我們將使用 Gemini CLI 建立 ADK 代理程式:**
cd ~/storygen-learning/01a_First_Agent_Ready
開啟 Gemini CLI
gemini
在 Gemini CLI 視窗中,嘗試輸入以下提示:
I need you to help me create a Google ADK (Agent Development Kit) agent for story generation. I'm working on a children's storybook app that generates creative stories with visual scenes.
Please create a complete `agent.py` file that implements an LlmAgent using Google's ADK framework. The agent should:
**Requirements:**
1. Use the `google.adk.agents.LlmAgent` class
2. Use the "gemini-2.5-flash" model (supports streaming)
3. Be named "story_agent"
4. Generate structured stories with exactly 4 scenes each
5. Output valid JSON with story text, main characters, and scene data
6. No tools needed (images are handled separately)
**Agent Specifications:**
- **Model:** gemini-2.5-flash
- **Name:** story_agent
- **Description:** "Generates creative short stories and accompanying visual keyframes based on user-provided keywords and themes."
**Story Structure Required:**
- Exactly 4 scenes: Setup → Inciting Incident → Climax → Resolution
- 100-200 words total
- Simple, charming language for all audiences
- Natural keyword integration
**JSON Output Format:**
{
"story": "Complete story text...",
"main_characters": [
{
"name": "Character Name",
"description": "VERY detailed visual description with specific colors, features, size, etc."
}
],
"scenes": [
{
"index": 1,
"title": "The Setup",
"description": "Scene action and setting WITHOUT character descriptions",
"text": "Story text for this scene"
}
// ... 3 more scenes
]
}
**Key Instructions for the Agent:**
- Extract 1-2 main characters maximum
- Character descriptions should be extremely detailed and visual
- Scene descriptions focus on ACTION and SETTING only
- Do NOT repeat character appearance in scene descriptions
- Always respond with valid JSON
Please include a complete example in the instructions showing the exact format using keywords like "tiny robot", "lost kitten", "rainy city".
The file should start with necessary imports, define an empty tools list, include a print statement for initialization, and then create the LlmAgent with all the detailed instructions.
Can you create this agent in backend/story_agent/agent.py
完成後,使用 Control+C
關閉 Gemini CLI 終端機
—————————————— 選用,您可以跳至「解決方案」部分——————————————–
現在請在 ADK 網頁中驗證變更
cd ~/storygen-learning/01a_First_Agent_Ready/backend
source ../../.venv/bin/activate
adk web --port 8080
如要繼續,請開啟命令提示字元。
啟動網站
cd ~/storygen-learning/01a_First_Agent_Ready
./start.sh
如果變更無效,您應該會在 ADK 網頁使用者介面和網站中看到錯誤。
—————————————— 解決方案從這裡開始 ——————————————
解決方案
使用 Control+C
結束先前的程序,或開啟另一個終端機:
cd ~/storygen-learning/01b_First_Agent_Done
啟動網站:
./start.sh
您會看到網站:
嘗試使用 ADK UI:開啟另一個終端機:
cd ~/storygen-learning/01b_First_Agent_Done/backend
source ../../.venv/bin/activate
adk web --port 8080
系統會顯示 ADK 使用者介面,您可以在這裡向專員提問
在移至下一個部分之前,請按下 Ctrl+C 鍵結束程序。
6. 開發:使用 Imagen 建構自訂代理程式
生成 Imagen 工具 (第二個代理程式)
cd ~/storygen-learning/02a_Image_Agent_Ready
使用 Gemini CLI 建立圖片生成代理:
gemini generate "I need you to help me create a custom Google ADK (Agent Development Kit) agent for image generation. This is different from the story agent - this one handles image generation directly using the BaseAgent pattern for full control over tool execution.
Please create a complete `agent.py` file that implements a custom image generation agent. The agent should:
**Requirements:**
1. Use the `google.adk.agents.BaseAgent` class (NOT LlmAgent)
2. Be named "custom_image_agent"
3. Directly execute the ImagenTool without LLM intermediation
4. Handle JSON input with scene descriptions and character descriptions
5. Store results in session state for retrieval by main.py
6. Use async generators and yield Events
**Key Specifications:**
- **Class Name:** CustomImageAgent (inherits from BaseAgent)
- **Agent Name:** "custom_image_agent"
- **Tool:** Uses ImagenTool for direct image generation
- **Purpose:** Bypass LLM agent limitations and directly call ImagenTool
**Input Format:**
The agent should handle JSON input like:
{
"scene_description": "Scene action and setting",
"character_descriptions": {
"CharacterName": "detailed visual description"
}
}
**Core Method:** `async def _run_async_impl(self, ctx: InvocationContext) -> AsyncGenerator[Event, None]:`
- Extract user message from `ctx.user_content.parts`
- Parse JSON input or fallback to plain text
- Extract scene_description and character_descriptions
- Build image prompt with style prefix: "Children's book cartoon illustration with bright vibrant colors, simple shapes, friendly characters."
- Include character descriptions for consistency
- Call `await self.imagen_tool.run()` directly
- Store results in `ctx.session.state["image_result"]`
- Yield Event with results
**Session State:**
- Store JSON results in `ctx.session.state["image_result"]`
- Include success/error status
- Store actual image URLs or error messages
Expected Output Structure:
- Successful results stored as JSON with image URLs
- Error results stored as JSON with error messages
- Results accessible via session state in main.py
Can you create this agent in backend/story_image_agent/agent.py
"
—————————————— 選用,您可以跳至「解決方案」部分——————————————–
現在請在 ADK 網頁中驗證變更
cd ~/storygen-learning/02a_Image_Agent_Ready/backend
source ../../.venv/bin/activate
adk web --port 8080
啟動網站
cd ~/storygen-learning/02a_Second_Agent_Ready
./start.sh
如果變更無效,您應該會在 ADK 網頁使用者介面和網站中看到錯誤。
—————————————— 解決方案從這裡開始 ——————————————–
解決方案
使用 Control+C
結束先前的程序,或開啟另一個終端機:
# Open new terminal
cd ~/storygen-learning/02b_Image_Agent_Done
啟動網站:
./start.sh
您會看到網站:
嘗試使用 ADK UI:開啟另一個終端機:
# Open new terminal
cd ~/storygen-learning/02b_Image_Agent_Done/backend
source ../../.venv/bin/activate
adk web --port 8080
您會看到 ADK 使用者介面,可以在這裡向專員提問:
在移至下一個部分之前,請按下 Ctrl+C 鍵結束程序。
學習
第一個代理程式很擅長生成文字,但現在我們需要生成圖片。我們需要更直接的控制權,才能完成這項工作。我們不希望 LLM 決定是否要建立圖片,而是要直接命令它這麼做。這項工作非常適合 BaseAgent。
與宣告式 LlmAgent 不同,BaseAgent 是命令式。也就是說,開發人員會在 _run_async_impl 方法中,撰寫確切的 Python 邏輯步驟。您可以完全掌控執行流程。
需要下列功能時,請選擇 BaseAgent:
確定性邏輯:服務專員必須按照特定且不可變更的步驟順序操作。
直接執行工具:您想直接呼叫工具,不需要 LLM 介入。
複雜的工作流程:這個程序涉及自訂資料操縱、API 呼叫和邏輯,複雜程度超出 LLM 的能力範圍,無法單從提示可靠地推斷。
在我們的應用程式中,我們會使用 BaseAgent 接收第一個代理程式的場景描述,並直接呼叫 Imagen 工具,確保每個場景都會生成圖片。
7. 測試:代理程式評估
我們的應用程式可以運作,但我們需要自動測試安全網。這項工作很適合交給 AI 副駕駛。
動作
cd ~/storygen-learning/03a_Agent_Evaluation_Ready/backend
使用 Gemini CLI 編寫全面測試:
開啟 Gemini CLI
gemini
在 Gemini CLI 視窗中,嘗試輸入以下提示:
I need you to create comprehensive test files for my backend/story_agent in Google ADK. I need three specific JSON files that match the testing structure used in ADK evaluation.
**Context:**
- The story agent generates structured JSON stories with exactly 4 scenes
- It uses LlmAgent with no tools, just direct LLM responses
- Input: Keywords
- Output: JSON with story, main_characters, and scenes arrays
**Files to Create:**
### 1. `story_agent_eval.evalset.json` (Comprehensive Integration Tests)
Create a comprehensive evaluation set with:
- **eval_set_id**: "story_agent_comprehensive_evalset"
- **name**: "Story Agent Comprehensive Evaluation Set"
- **description**: "Comprehensive evaluation scenarios for story_agent covering various keyword combinations, edge cases, and story quality metrics"
Each eval_case should include:
- Full conversation arrays with invocation_id, user_content, final_response
- Complete expected JSON responses with detailed stories, characters, and 4 scenes
- session_input with app_name "story_agent"
- All fields: story (narrative text), main_characters (with detailed visual descriptions), scenes (with index, title, description, text)
### 2. `story_generation.test.json` (Unit Tests)
Create basic generation tests with:
- **eval_set_id**: "story_agent_basic_generation_tests"
- **name**: "Story Agent Basic Generation Tests"
- **description**: "Unit tests for story_agent focusing on JSON structure compliance, scene generation, and keyword integration"
### 3. `test_config.json` (Evaluation Configuration)
Create test configuration with:
- **criteria**: response_match_score: 0.7, tool_trajectory_avg_score: 1.0
- **custom_evaluators**:
- json_structure_validator (validates required fields, scene count, character fields)
- story_quality_metrics (word count 80-250, keyword integration threshold 0.8)
- **evaluation_notes**: Story agent specifics and trajectory expectations
**Important Requirements:**
1. All responses must be valid, parseable JSON
2. Stories must have exactly 4 scenes with indices 1-4
3. Each scene must have: index, title, description, text
4. Main characters must have detailed visual descriptions
5. No tool_uses expected (empty arrays) since story agent uses direct LLM
6. Word count should be 100-200 words total
7. Keywords must be naturally integrated into the narrative
Please generate all three files with realistic example stories and comprehensive test coverage matching the ADK evaluation format.
—————————————— 選用,您可以跳至「解決方案」部分——————————————–
如何查看評估結果:
./run_adk_web_persistent.sh
前往 ADK UI 的「eval
」分頁。
您應該會看到 ADK 網頁版 UI,其中包含持續測試功能
重要學習時刻:AI 是強大的合作夥伴,可自動執行品保程序。這項工具可處理測試編寫的樣板,讓您專注於建構功能。
—————————————— 解決方案從這裡開始 ——————————————
解決方案
- 前往解決方案資料夾:
cd ~/storygen-learning/03b_Agent_Evaluation_Done/backend
- 開啟 ADK 網頁版 UI
./run_adk_web_persistent.sh
您可以從「Eval
」分頁查看測試案例:
如要調整指標,請按照下列步驟操作:
在此查看評估執行結果:
學習
代理程式可以「運作」,也就是執行時不會發生錯誤,但我們如何知道代理程式是否產生正確的輸出內容?故事是否精彩?JSON 格式是否正確?這時 ADK 的評估架構就能派上用場。
代理程式評估是一套自動測試系統,用於評估代理程式回覆的品質和正確性。這項功能不只會檢查程式碼錯誤,還會檢查代理程式的行為是否符合預期。這個架構主要使用下列幾個重要檔案:
evalset.json:這是主要測試套件。這個檔案中的每個「評估案例」都包含範例對話 (例如使用者提示) 和您預期代理程式產生的理想「黃金」回應。
test_config.json:這個檔案定義成功規則。您可以在這裡設定條件,例如:
response_match_score:代理程式的回應與「黃金」回應的相似程度。(分數為 1.0 表示必須完全相同)。
custom_evaluators:您可以建立自己的規則,例如「回覆必須是有效的 JSON」或「故事必須包含超過 100 個字」。
執行評估時,系統會自動針對數十種情境測試服務專員,確保提示或工具的變更不會意外破壞核心功能。這項功能可做為強大的安全網,協助您建構可用於正式環境的 AI 代理。
8. 基礎架構即程式碼 (IaC):在雲端建構家園
我們的程式碼已通過測試,但需要實際工作環境專用的主機。我們會使用「基礎架構即程式碼」定義環境。
什麼是 Docker?
Docker 平台可建立及執行容器中的應用程式。您可以將容器視為軟體的標準化運輸容器。它會將執行應用程式所需的一切資源封裝成單一獨立套件:
- 應用程式程式碼本身
- 必要的執行階段 (例如特定版本的 Python)
- 所有系統工具和程式庫
接著,只要在安裝 Docker 的機器上執行這個容器化應用程式,即可解決「成果僅存在於特定機器」的經典問題。
在本節中,我們會要求 Gemini 生成 Dockerfile,這只是建構應用程式容器映像檔的配方或藍圖
動作
cd ~/storygen-learning/04a_Manual_Deployment_Ready
使用 Gemini CLI 為後端建立 Dockerfile:開啟 Gemini CLI
Gemini
在 Gemini CLI 中,嘗試輸入以下提示:
Create a manual deployment plan for my StoryGen app with Google Cloud Platform. I have a Next.js frontend, Python backend, and Terraform infrastructure.
Generate these deployment files:
1. **01-setup.sh** - Environment setup and authentication
2. **02-build-images.sh** - Build and push Docker images to Google Container Registry
3. **03-deploy-infrastructure.sh** - Deploy with Terraform and configure services
4. **load-env.sh** - Load environment variables for deployment
**Requirements:**
- Use Google Cloud Run for both frontend and backend
- Configure Imagen API and storage buckets
- Set up proper IAM permissions
- Use environment variables from .env file
- Include error handling and status checks
Keep scripts simple, well-commented, and production-ready for manual execution.
解決方式:
cd ~/storygen-learning/04b_Manual_Deployment_Done
執行作業:
source ../.venv/bin/activate
./01-setup.sh
./02-build-images.sh
./03-deploy-infrastructure.sh
您應該會看到部署結果和基礎架構建立作業
9. 自動化 (CI/CD):數位裝配線
手動部署應用程式是瞭解各個環節的好方法,但速度緩慢、需要人工操作,且可能導致人為錯誤。在專業軟體開發中,整個程序會透過稱為 CI/CD 的做法自動執行。
CI/CD 是指持續整合和持續部署。這項方法會在您每次變更程式碼時,自動建構、測試及部署程式碼。
- 持續整合 (CI):這是「建構及測試」階段。開發人員將程式碼變更推送到共用存放區 (例如 GitHub) 後,自動化系統就會啟動。這項作業會建構應用程式並執行所有測試 (例如我們建立的代理程式評估),確保新程式碼正確整合,且不會造成任何錯誤。
- 持續部署 (CD):這是「發布」階段。如果 CI 階段順利通過,系統會自動將經過測試的新版應用程式部署到正式版,供使用者使用。
這個自動化管道會建立「數位裝配線」,將開發人員電腦中的程式碼快速、安全且可靠地投入實際工作環境。在本節中,我們將要求 AI 助理使用 GitHub Actions 和 Google Cloud Build,為我們建構這條裝配線。
動作
cd ~/storygen-learning/05a_CICD_Pipeline_Ready
使用 Gemini CLI 搭配 GitHub 建構 CI/CD 管道:
開啟 Gemini CLI
Gemini
在 Gemini CLI 中,嘗試輸入以下提示:
Create a CI/CD pipeline for my StoryGen app using Google Cloud Build and GitHub integration.
Generate these automation files:
1. **cloudbuild.yaml** (for backend) - Automated build, test, and deploy pipeline
2. **GitHub Actions workflow** - Trigger builds on push/PR
3. **Deployment automation scripts** - Streamlined deployment process
**Requirements:**
- Auto-trigger on GitHub push to main branch
- Build and push Docker images
- Run automated tests if available
- Deploy to Google Cloud Run
- Environment-specific deployments (staging/prod)
- Notification on success/failure
Focus on fully automated deployment with minimal manual intervention. Include proper secret management and rollback capabilities.
—————————————— 解決方案從這裡開始 ——————————————
解決方式:
cd ~/storygen-learning/06_Final_Solution/
# Copy the GitHub workflow to parent folder
cp -r 06_Final_Solution/.GitHub ../../../.GitHub
返回 06_Final_Solution 資料夾,然後執行指令碼:
cd ~/storygen-learning/06_Final_Solution/
./setup-cicd-complete.sh
您應該會看到 CI/CD 管道設定完成的訊息
觸發工作流程:將程式碼提交並推送至 main。請注意,您必須設定 GitHub 電子郵件和名稱,才能允許這項權限。
git add .
git commit -m "feat: Add backend, IaC, and CI/CD workflow"
git push origin main
前往 GitHub 存放區的「Actions」分頁,觀看自動部署作業的執行情況。
10. 作業:AI 控制中心
我們正在直播!但這趟旅程尚未結束。這是「第 2 天」的作業。讓我們返回 Cloud Assist,管理正在執行的應用程式。
動作
- 在 Google Cloud 控制台中,前往 Cloud Run 服務。與上線的應用程式互動,產生一些流量和記錄檔。
- 開啟 Cloud Assist 窗格,並將其做為作業副駕駛,使用下列提示:
記錄檔分析:
Summarize the errors in my Cloud Run logs for the service 'genai-backend' from the last 15 minutes.
效能調整:
My Cloud Run service 'genai-backend' has high startup latency. What are common causes for a Python app and how can I investigate with Cloud Trace?
成本最佳化:
Analyze the costs for my 'genai-backend' service and its GCS bucket. Are there any opportunities to save money?
重要學習時刻:AI SDLC 是持續循環的過程。在實際執行環境中,協助建構應用程式的 AI 副駕駛,也是監控、排解問題及最佳化應用程式的不可或缺夥伴。