AI 에이전트 엔드 투 엔드 - 워크숍

1. 학습할 내용

AI 에이전트 Vibe 풀 스택

환영합니다. 이제 소프트웨어 개발의 다음 핵심 기술인 인공지능을 효과적으로 안내하여 프로덕션 등급 소프트웨어를 빌드, 테스트, 배포하는 방법을 알아봅니다. 생성형 AI는 '자동 조종 장치'가 아니라 숙련된 감독이 필요한 강력한 부조종사입니다.

이 워크숍에서는 전문 소프트웨어 개발 수명 주기 (SDLC)의 모든 단계에서 AI와 협력하기 위한 구조화되고 반복 가능한 방법론을 제공합니다. 한 줄씩 코드를 작성하는 사람에서 비전을 가진 설계자이자 AI를 사용하여 비전을 정확하게 실행하는 일반 계약자인 기술 감독으로 바뀌게 됩니다. 🚀

demo

이 튜토리얼을 마치면 다음을 수행할 수 있습니다.

  • AI를 사용하여 대략적인 아이디어를 클라우드 아키텍처로 변환했습니다.
  • 타겟팅된 구체적인 프롬프트로 완전한 Python 백엔드를 생성했습니다.
  • AI를 페어링 프로그래머로 사용하여 코드를 디버그하고 수정했습니다.
  • 모의를 포함한 단위 테스트 생성을 AI에 위임했습니다.

Terraform을 사용하여 프로덕션 준비가 완료된 코드형 인프라 (IaC)를 생성했습니다.

단일 프롬프트로 GitHub Actions에서 전체 CI/CD 파이프라인을 만들었습니다.

AI 기반 운영 도구를 사용하여 라이브 애플리케이션을 모니터링하고 관리했습니다.

작동하는 앱뿐만 아니라 AI 기반 개발을 위한 청사진도 얻을 수 있습니다. 지금부터 시작하겠습니다

2. 기본 요건 및 설정

시작하기 전에 환경을 준비하겠습니다. 원활한 워크숍 경험을 위해 이 단계를 반드시 완료해야 합니다.

AI 에이전트를 지원하려면 기반을 제공하는 Google Cloud 프로젝트와 Google의 강력한 모델에 액세스할 수 있는 Gemini API 키가 필요합니다.

1단계: 결제 계정 사용 설정하기

  • 배포에 필요한 5달러 크레딧으로 결제 계정을 청구합니다. Gmail 계정으로 로그인해야 합니다.

2단계: 새 GCP 프로젝트 만들기

  • Google Cloud 콘솔로 이동하여 새 프로젝트를 만듭니다.

새 GCP 계정 만들기

  • Google Cloud 콘솔로 이동하여 새 프로젝트를 만듭니다.
  • 왼쪽 패널을 열고 Billing을 클릭하여 결제 계정이 이 GCP 계정에 연결되어 있는지 확인합니다.

결제 계정을 GCP 계정에 연결

이 페이지가 표시되면 manage billing account을 확인하고 Google Cloud Trial One을 선택하여 연결합니다.

3단계: Gemini API 키 생성하기

키를 보호하려면 키가 있어야 합니다.

  • Google AI Studio(https://aistudio.google.com/)로 이동합니다.
  • Gmail 계정으로 로그인합니다.
  • 'API 키 가져오기' 버튼을 클릭합니다. 이 버튼은 일반적으로 왼쪽 탐색 창이나 오른쪽 상단에 있습니다.
  • 'API 키' 대화상자에서 '새 프로젝트에 API 키 만들기'를 클릭합니다. 새 프로젝트에 API 키 만들기
  • 결제 계정이 설정된 새로 만든 프로젝트를 선택합니다. 새 프로젝트 선택
  • 새 API 키가 생성됩니다. 이 키를 즉시 복사하여 비밀번호 관리자나 보안 메모와 같은 안전한 곳에 임시로 저장합니다. 다음 단계에서 사용할 값입니다.

GitHub 인증

Google Cloud 콘솔로 이동하여 오른쪽 상단의 'Cloud Shell 활성화' 버튼을 클릭하여 Cloud Shell을 엽니다.

1단계: Cloud Shell 열기

👉Google Cloud 콘솔 상단에서 Cloud Shell 활성화를 클릭합니다 (Cloud Shell 창 상단의 터미널 모양 아이콘). cloud-shell.png

👉'편집기 열기' 버튼 (연필이 있는 열린 폴더 모양)을 클릭합니다. 이렇게 하면 창에 Cloud Shell 코드 편집기가 열립니다. 왼쪽에 파일 탐색기가 표시됩니다. open-editor.png

👉Google Cloud 프로젝트 ID를 찾습니다.

  • Google Cloud 콘솔(https://console.cloud.google.com)을 엽니다.
  • 페이지 상단의 프로젝트 드롭다운에서 이 워크숍에 사용할 프로젝트를 선택합니다.
  • 프로젝트 ID는 대시보드의 프로젝트 정보 카드에 표시됩니다.

03-04-project-id.png

👉클라우드 IDE에서 터미널을 열고

03-05-new-terminal.png

👉💻 터미널에서 다음 명령어를 사용하여 이미 인증되었는지, 프로젝트가 프로젝트 ID로 설정되어 있는지 확인합니다.

gcloud auth list

2단계: GitHub로 인증 및 포크

GitHub로 인증:

👉💻

gh auth login

git1.png

로그인 인증 페이지에 코드를 복사합니다.

git2.png

저장소 포크 및 클론: 👉💻

gh repo fork cuppibla/storygen-learning --clone=true

3. 아키텍처: Cloud Assist를 사용하여 아이디어에서 청사진으로

모든 훌륭한 프로젝트는 명확한 비전에서 시작됩니다. AI 공동 파일럿인 Cloud Assist를 사용하여 앱 아키텍처를 설계합니다.

아키텍처

작업

  • Google Cloud 콘솔(https://console.cloud.google.com)을 엽니다.
  • 오른쪽 상단에서 'Cloud Assist 채팅 열기'를 클릭합니다.

cloud_assist_1

Cloud Assist 사용 설정

  • Get Gemini Assist을 클릭한 다음 Enable Cloud Assist at no cost을 클릭합니다.
  • 채팅을 시작하세요.

cloud_assist_3 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가 아키텍처 다이어그램을 생성합니다. 이것이 시각적 청사진입니다. cloud_assist_4

주요 학습 순간: AI는 높은 수준의 시스템 설계에 탁월합니다. 쉬운 언어로 된 요구사항을 전문적인 시각적 아키텍처로 즉시 변환할 수 있습니다.

4. 개발: Gemini CLI로 ADK 빌드

SDLC

초기 설정

Gemini CLI를 사용하여 저장소를 포크하고 작업공간을 준비해야 합니다.

환경 구성

Cloud Shell로 이동하여 '터미널 열기' 버튼을 클릭합니다.

  1. 환경 템플릿을 복사합니다.
    cd ~/storygen-learning
    cp ~/storygen-learning/env.template ~/storygen-learning/.env
    

.env를 찾을 수 없는 경우 편집기에서 숨겨진 파일 보기

  • 상단 메뉴 바에서 보기를 클릭합니다.
  • 숨김 파일 전환을 선택합니다.

.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=testprojectGENMEDIA_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 웹 UI 및 웹사이트에 오류가 표시됩니다.

—————————————— 여기부터 솔루션 시작 ——————————————–

해결 방법

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 UI가 표시됩니다.

adkweb

다음 섹션으로 이동하기 전에 Ctrl+C를 눌러 프로세스를 종료합니다.

5. 개발: Imagen으로 맞춤 에이전트 빌드

2adk

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 웹 UI 및 웹사이트에 오류가 표시됩니다.

—————————————- 여기부터 솔루션 시작 ——————————————–

해결 방법

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 UI가 표시됩니다.

adkweb

다음 섹션으로 이동하기 전에 Ctrl+C를 눌러 프로세스를 종료합니다.

6. 테스트: 에이전트 평가

앱은 작동하지만 자동화된 테스트 안전망이 필요합니다. 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 탭에서 테스트 사례를 확인할 수 있습니다.

eval1

여기에서 측정항목을 조정합니다.

eval2

평가 실행 결과는 여기에서 확인할 수 있습니다.

eval3

7. 코드형 인프라 (IaC): 클라우드에 홈 구축하기

코드는 테스트를 거쳤지만 프로덕션에 사용할 수 있는 홈이 필요합니다. '코드형 인프라'를 사용하여 환경을 정의합니다.

deployprocess

작업

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

배포 결과와 인프라 생성이 표시됩니다.

8. 자동화 (CI/CD): 디지털 조립 라인

앱을 수동으로 배포하는 것은 속도가 느리고 위험합니다. AI에게 GitHub Actions를 사용하여 완전한 CI/CD 파이프라인을 작성해 달라고 요청해 보겠습니다.

작업

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'(작업) 탭으로 이동하여 자동 배포가 실행되는 것을 확인합니다.

주요 학습 내용: 복잡하고 중요한 DevOps 요소인 전체 CI/CD 파이프라인을 AI로 생성할 수 있습니다.

9. 운영: AI 컨트롤 타워

라이브 스트리밍이 시작되었습니다. 하지만 여정은 끝나지 않았습니다. 이것이 '2일차'인 운영입니다. Cloud Assist로 돌아가 실행 중인 애플리케이션을 관리해 보겠습니다.

작업

  1. Google Cloud 콘솔에서 Cloud Run 서비스로 이동합니다. 라이브 앱과 상호작용하여 트래픽과 로그를 생성합니다.
  2. 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 공동 파일럿은 프로덕션에서 애플리케이션을 모니터링, 문제 해결, 최적화하는 데 없어서는 안 될 파트너입니다.