# v6: Google Cloud 및 Vertex AI 설정 ## Google Cloud Platform (GCP) 소개 Google Cloud Platform은 Google이 제공하는 클라우드 컴퓨팅 서비스입니다. Vertex AI는 GCP의 AI/ML 플랫폼으로, Gemini 모델을 포함한 다양한 AI 모델을 제공합니다. ### Vertex AI vs Gemini API 비교 | 항목 | Vertex AI | Gemini API (Google AI Studio) | |------|-----------|-------------------------------| | 모델 | Gemini + 커스텀 모델 | Gemini만 | | 위치 | GCP 프로젝트 내 | Google AI | | 인증 | Service Account | API Key | | 비용 | 종량제 (약간 비쌈) | 종량제 (저렴) | | 엔터프라이즈 | ✅ 적합 | ⚠️ 개인/소규모용 | **이번 프로젝트에서는 Vertex AI를 사용합니다** (엔터프라이즈 수준 연습). ## Google Cloud 프로젝트 생성 ### 1. GCP 계정 생성 1. https://console.cloud.google.com 방문 2. Google 계정으로 로그인 3. 신규 가입 시 **$300 무료 크레딧** 제공 (90일간) 4. 결제 정보 등록 (크레딧 소진 후에만 과금) ### 2. 프로젝트 생성 1. GCP Console 상단의 프로젝트 선택 드롭다운 클릭 2. "새 프로젝트" 클릭 3. 프로젝트 정보 입력: ``` 프로젝트 이름: moneyforward-vertexai 프로젝트 ID: moneyforward-vertexai-123456 (자동 생성, 전역 고유값) 위치: 조직 없음 (개인 계정) ``` 4. "만들기" 클릭 ### 3. 프로젝트 ID 확인 프로젝트가 생성되면 **프로젝트 ID**를 메모해둡니다. 이는 API 호출 시 필요합니다. 예: `moneyforward-vertexai-123456` ## Vertex AI API 활성화 ### 1. API 라이브러리 접속 1. 좌측 메뉴에서 "API 및 서비스" > "라이브러리" 선택 2. 검색창에 "Vertex AI" 입력 3. "Vertex AI API" 선택 4. "사용 설정" 클릭 ### 2. 필요한 API 활성화 다음 API들도 활성화합니다: - **Vertex AI API**: AI 모델 사용 - **Cloud Resource Manager API**: 프로젝트 관리 - **Service Usage API**: API 사용량 추적 활성화 완료까지 1-2분 소요될 수 있습니다. ## 서비스 계정 생성 및 인증 ### 서비스 계정이란? 서비스 계정은 애플리케이션이 GCP 리소스에 접근할 때 사용하는 특수한 계정입니다. 사용자 계정 대신 앱이 자체적으로 인증할 수 있게 해줍니다. ### 1. 서비스 계정 생성 1. 좌측 메뉴에서 "IAM 및 관리자" > "서비스 계정" 선택 2. "서비스 계정 만들기" 클릭 3. 서비스 계정 정보 입력: ``` 서비스 계정 이름: vertexai-service-account 서비스 계정 ID: vertexai-sa (자동 생성) 설명: Vertex AI API 호출용 서비스 계정 ``` 4. "만들고 계속하기" 클릭 ### 2. 권한 부여 (IAM 역할) 서비스 계정에 다음 역할을 부여합니다: **필수 역할**: - **Vertex AI User** (`roles/aiplatform.user`) - Vertex AI 모델 사용 권한 **선택 역할** (로깅 등): - **Logs Writer** (`roles/logging.logWriter`) - 로그 작성 권한 역할 선택 후 "계속" 클릭 ### 3. JSON 키 파일 생성 1. "완료" 클릭하여 서비스 계정 생성 완료 2. 서비스 계정 목록에서 방금 생성한 계정 클릭 3. "키" 탭 선택 4. "키 추가" > "새 키 만들기" 클릭 5. 키 유형: **JSON** 선택 6. "만들기" 클릭 JSON 키 파일이 자동으로 다운로드됩니다. **중요**: 이 파일에는 민감한 인증 정보가 포함되어 있으므로 안전하게 보관하세요! ### 4. JSON 키 파일 저장 다운로드한 JSON 파일을 프로젝트 루트에 저장합니다: ```bash # 파일명 예시: service-account-key.json mv ~/Downloads/moneyforward-vertexai-xxxxx.json ./service-account-key.json ``` 파일 내용 예시: ```json { "type": "service_account", "project_id": "moneyforward-vertexai-123456", "private_key_id": "abc123...", "private_key": "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n", "client_email": "vertexai-sa@moneyforward-vertexai-123456.iam.gserviceaccount.com", "client_id": "123456789", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://oauth2.googleapis.com/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "client_x509_cert_url": "..." } ``` ## 환경 변수 설정 ### .env 파일 업데이트 ```bash # Money Forward API MONEYFORWARD_CLIENT_ID=abc123... MONEYFORWARD_CLIENT_SECRET=xyz789... MONEYFORWARD_REDIRECT_URI=http://localhost:3000/callback # Google Cloud Vertex AI GOOGLE_CLOUD_PROJECT=moneyforward-vertexai-123456 GOOGLE_APPLICATION_CREDENTIALS=./service-account-key.json VERTEX_AI_LOCATION=us-central1 VERTEX_AI_MODEL=gemini-1.5-flash # Application NODE_ENV=development PORT=3000 ``` ### 주요 환경 변수 설명 - **GOOGLE_CLOUD_PROJECT**: GCP 프로젝트 ID - **GOOGLE_APPLICATION_CREDENTIALS**: 서비스 계정 JSON 키 파일 경로 - **VERTEX_AI_LOCATION**: Vertex AI 리전 - `us-central1` (추천): 미국 중부, 가장 안정적 - `asia-northeast1`: 도쿄 - `europe-west1`: 벨기에 - **VERTEX_AI_MODEL**: 사용할 모델 ID - `gemini-1.5-flash`: 빠르고 저렴 (추천) - `gemini-1.5-pro`: 강력하지만 비쌈 ## Vertex AI SDK 설치 이미 v3에서 설치했지만, 확인 차 다시 실행: ```bash npm install @google-cloud/aiplatform ``` ## Vertex AI 클라이언트 구현 ### src/vertexai/client.ts ```typescript import { PredictionServiceClient } from '@google-cloud/aiplatform'; import { VertexAIConfig, VertexAIRequest, VertexAIResponse } from '../types'; export class VertexAIClient { private client: PredictionServiceClient; private projectId: string; private location: string; private model: string; constructor() { // 환경 변수 확인 this.projectId = process.env.GOOGLE_CLOUD_PROJECT!; this.location = process.env.VERTEX_AI_LOCATION || 'us-central1'; this.model = process.env.VERTEX_AI_MODEL || 'gemini-1.5-flash'; if (!this.projectId) { throw new Error('GOOGLE_CLOUD_PROJECT 환경 변수가 설정되지 않았습니다'); } // Vertex AI 클라이언트 초기화 this.client = new PredictionServiceClient({ apiEndpoint: `${this.location}-aiplatform.googleapis.com`, }); console.log(`✅ Vertex AI 클라이언트 초기화 완료`); console.log(` 프로젝트: ${this.projectId}`); console.log(` 위치: ${this.location}`); console.log(` 모델: ${this.model}`); } /** * 텍스트 생성 (Gemini API) */ async generateText(request: VertexAIRequest): Promise { const { prompt, temperature = 0.2, maxOutputTokens = 2048, topP = 0.8, topK = 40, } = request; // Vertex AI 엔드포인트 const endpoint = `projects/${this.projectId}/locations/${this.location}/publishers/google/models/${this.model}`; // 요청 파라미터 const instanceValue = { content: prompt, }; const instance = { structValue: { fields: { content: { stringValue: prompt, }, }, }, }; const parameters = { structValue: { fields: { temperature: { numberValue: temperature }, maxOutputTokens: { numberValue: maxOutputTokens }, topP: { numberValue: topP }, topK: { numberValue: topK }, }, }, }; const predictRequest = { endpoint, instances: [instance], parameters, }; try { console.log('🤖 Vertex AI에 요청 중...'); const [response] = await this.client.predict(predictRequest); // 응답 파싱 const predictions = response.predictions; if (!predictions || predictions.length === 0) { throw new Error('Vertex AI 응답이 비어있습니다'); } const prediction = predictions[0]; const text = prediction.structValue?.fields?.content?.stringValue || ''; console.log('✅ Vertex AI 응답 수신 완료\n'); return { text, safetyRatings: [], // 필요시 파싱 }; } catch (error) { if (error instanceof Error) { throw new Error(`Vertex AI 호출 실패: ${error.message}`); } throw error; } } } ``` ## 연결 테스트 스크립트 ### src/cli-test-vertexai.ts ```typescript import 'dotenv/config'; import { VertexAIClient } from './vertexai/client'; async function main() { console.log('🧪 Vertex AI 연결 테스트\n'); try { const client = new VertexAIClient(); // 간단한 테스트 프롬프트 const prompt = ` 다음은 간단한 테스트입니다. "Hello, Vertex AI!"라고 답변해주세요. `.trim(); console.log('📝 프롬프트:'); console.log(prompt); console.log('\n' + '─'.repeat(50) + '\n'); const response = await client.generateText({ prompt }); console.log('🤖 Vertex AI 응답:'); console.log(response.text); console.log('\n' + '─'.repeat(50) + '\n'); console.log('✅ 연결 테스트 성공!'); } catch (error) { console.error('❌ 연결 테스트 실패:', error); process.exit(1); } } main(); ``` ### package.json 스크립트 추가 ```json { "scripts": { "dev": "tsx src/index.ts", "auth": "tsx src/cli-auth.ts", "fetch": "tsx src/cli-fetch-transactions.ts", "test:ai": "tsx src/cli-test-vertexai.ts", "build": "tsc" } } ``` ## 실행 및 테스트 ### 1. 환경 변수 확인 ```bash # .env 파일에 다음이 설정되어 있는지 확인 cat .env | grep GOOGLE ``` 예상 출력: ``` GOOGLE_CLOUD_PROJECT=moneyforward-vertexai-123456 GOOGLE_APPLICATION_CREDENTIALS=./service-account-key.json ``` ### 2. JSON 키 파일 확인 ```bash ls -la service-account-key.json ``` 파일이 존재하고 읽기 권한이 있는지 확인 ### 3. Vertex AI 연결 테스트 ```bash npm run test:ai ``` 예상 출력: ``` 🧪 Vertex AI 연결 테스트 ✅ Vertex AI 클라이언트 초기화 완료 프로젝트: moneyforward-vertexai-123456 위치: us-central1 모델: gemini-1.5-flash 📝 프롬프트: 다음은 간단한 테스트입니다. "Hello, Vertex AI!"라고 답변해주세요. ────────────────────────────────────────────────── 🤖 Vertex AI에 요청 중... ✅ Vertex AI 응답 수신 완료 🤖 Vertex AI 응답: Hello, Vertex AI! ────────────────────────────────────────────────── ✅ 연결 테스트 성공! ``` ## 비용 확인 및 모니터링 ### 1. Vertex AI 요금 Gemini 1.5 Flash (2025년 기준): - **입력 토큰**: $0.000075 / 1K tokens - **출력 토큰**: $0.0003 / 1K tokens 예상 비용 (한 달 매일 분석): - 하루 1회 분석 (약 2K 입력 + 1K 출력) - 비용: 약 $0.00045 x 30 = $0.0135/월 (**매우 저렴!**) ### 2. 비용 모니터링 GCP Console에서: 1. "결제" 메뉴 선택 2. "예산 및 알림" 설정 3. 월 예산 설정 (예: $10) 4. 80% 도달 시 이메일 알림 설정 ## 보안 고려사항 ### 1. 서비스 계정 키 보호 **.gitignore 확인**: ``` service-account-key.json *-key.json ``` **절대 GitHub에 커밋하지 마세요!** ### 2. 최소 권한 원칙 서비스 계정에 필요한 최소 권한만 부여: - ✅ Vertex AI User - ❌ Owner, Editor (과도한 권한) ### 3. 키 교체 주기 프로덕션 환경에서는 서비스 계정 키를 주기적으로 교체합니다 (예: 90일마다). ## 문제 해결 ### 에러: "The caller does not have permission" **원인**: 서비스 계정에 권한이 없음 **해결**: 1. IAM 페이지에서 서비스 계정 확인 2. "Vertex AI User" 역할 추가 ### 에러: "API not enabled" **원인**: Vertex AI API가 활성화되지 않음 **해결**: 1. API 라이브러리에서 "Vertex AI API" 검색 2. "사용 설정" 클릭 ### 에러: "Invalid credentials" **원인**: JSON 키 파일 경로 오류 **해결**: 1. `.env` 파일의 `GOOGLE_APPLICATION_CREDENTIALS` 확인 2. 파일 경로가 올바른지 확인 (`./service-account-key.json`) ## 체크리스트 v6을 완료하기 전에 다음을 확인하세요: - [ ] Google Cloud 계정 생성 완료 - [ ] GCP 프로젝트 생성 완료 - [ ] Vertex AI API 활성화 완료 - [ ] 서비스 계정 생성 및 권한 부여 - [ ] JSON 키 파일 다운로드 및 프로젝트에 저장 - [ ] `.env` 파일에 GCP 정보 추가 - [ ] `.gitignore`에 서비스 계정 키 추가 확인 - [ ] `VertexAIClient` 클래스 구현 - [ ] `npm run test:ai` 실행하여 연결 테스트 성공 ## 다음 단계 v7에서는 Vertex AI와 본격적으로 연동하여 재무 데이터 분석 프롬프트를 작성하고 테스트합니다. --- **작성일**: 2025-11-30 **상태**: ✅ 완료 **다음**: v7 - Vertex AI 재무 분석 프롬프트 작성