Day 4 실습: Colab으로 봇 만들기
실습 시간: 1시간
필요 도구: Google Colab, Google AI Studio
📚 공식 문서
| 도구 | 공식 문서 | 용도 |
|---|---|---|
| Google Colab | Colab Help · Colab Quickstart | Python 노트북 실행 |
| Google AI Studio | AI Studio · Quickstart | API 키 발급, 프롬프트 테스트 |
| Gemini API | API Docs · Python SDK | AI 모델 호출 |
사전 준비
1. Google AI Studio에서 API 키 발급
flowchart LR
A["aistudio.google.com<br/>접속"] --> B["Google 로그인"]
B --> C["Get API key<br/>클릭"]
C --> D["Create API key"]
D --> E["🔑 키 복사 & 보관"]
- aistudio.google.com 접속
- Google 계정 로그인
- 좌측 메뉴 “Get API key” 클릭
- “Create API key” 클릭
- 생성된 키 복사해서 안전하게 보관
⚠️ 주의: API 키는 절대 공개하지 마세요!
2. Google Colab 접속
- colab.google 접속
- “새 노트북” 클릭
- 노트북 이름을 “InquiryBot”으로 변경
실습 1: 기본 설정
라이브러리 설치
새 셀에 아래 코드 입력 후 실행 (Shift+Enter):
!pip install google-generativeai
API 설정
import google.generativeai as genai
# API 키 설정 (자신의 키로 교체)
API_KEY = "YOUR_API_KEY_HERE"
genai.configure(api_key=API_KEY)
# 모델 선택
model = genai.GenerativeModel('gemini-pro')
print("설정 완료!")
실습 2: 이메일 분류 봇
분류 함수 만들기
def classify_email(subject, body):
"""
이메일을 분석하여 카테고리, 긴급도, 자동응답 여부를 판단
"""
prompt = f"""
당신은 한국 화장품 수출회사의 이메일 분류 전문가입니다.
아래 바이어 이메일을 분석하고 분류해주세요.
=== 이메일 ===
제목: {subject}
본문:
{body}
=============
다음 형식으로 정확히 답변하세요:
카테고리: [가격문의/샘플요청/기술문의/배송문의/클레임/일반문의]
긴급도: [높음/보통/낮음]
자동응답 가능: [예/아니오]
핵심 요청: [한 문장으로 요약]
권장 조치: [담당자에게 추천하는 행동]
"""
response = model.generate_content(prompt)
return response.text
테스트
# 테스트 이메일 1: 가격 문의
test1_subject = "Price inquiry for skincare products"
test1_body = """
Dear Sales Team,
We are ABC Distribution from Vietnam, one of the leading
cosmetics distributors in Southeast Asia.
We are interested in your skincare product line, especially:
- Vitamin C Serum
- Hyaluronic Acid Cream
- Green Tea Cleanser
Could you please send us your price list and MOQ information?
We are planning to place an initial order of 1,000 units.
Best regards,
Nguyen Van Minh
Purchasing Manager
ABC Distribution
"""
result = classify_email(test1_subject, test1_body)
print("=== 분류 결과 ===")
print(result)
더 많은 테스트
# 테스트 이메일 2: 긴급 클레임
test2_subject = "URGENT: Damaged products received"
test2_body = """
Hello,
We received our order #12345 yesterday and unfortunately
30% of the products are damaged. The outer packaging was
crushed and many bottles are broken.
We need immediate response and replacement.
Our customer orders are pending.
Please call me urgently at +84-123-4567.
John Park
"""
result2 = classify_email(test2_subject, test2_body)
print("=== 분류 결과 ===")
print(result2)
실습 3: 자동 응답 생성
응답 생성 함수
def generate_reply(subject, body, category):
"""
이메일 카테고리에 맞는 자동 응답 초안 생성
"""
prompt = f"""
당신은 한국 화장품 수출회사의 해외영업 담당자입니다.
아래 바이어 이메일에 대한 전문적인 답장을 작성해주세요.
=== 원본 이메일 ===
제목: {subject}
카테고리: {category}
본문:
{body}
==================
요구사항:
- 영어로 작성
- 전문적이면서 친근한 톤
- 150단어 이내
- 구체적인 다음 단계 제시
- 필요시 추가 정보 요청
답장 형식:
Subject: Re: [원본 제목]
Dear [이름],
[본문]
Best regards,
[담당자명]
Export Sales Team
ABC Cosmetics Korea
"""
response = model.generate_content(prompt)
return response.text
응답 테스트
# 가격 문의에 대한 응답 생성
reply = generate_reply(
test1_subject,
test1_body,
"가격문의"
)
print("=== 자동 생성된 답장 ===")
print(reply)
실습 4: 통합 봇
전체 플로우
flowchart TD
E["📧 새 이메일 수신"]
C["🔍 이메일 분석<br/>(Gemini API)"]
D{"자동응답<br/>가능?"}
A["✅ 답장 초안 생성"]
M["⚠️ 담당자 확인 필요"]
E --> C --> D
D -->|"예"| A
D -->|"아니오"| M
def process_inquiry(subject, body):
"""
이메일 수신 → 분류 → 응답 생성 전체 플로우
"""
print("=" * 50)
print("📧 새 이메일 수신")
print("=" * 50)
print(f"제목: {subject}")
print(f"본문 미리보기: {body[:100]}...")
print()
# Step 1: 분류
print("🔍 이메일 분석 중...")
classification = classify_email(subject, body)
print("\n📋 분류 결과:")
print(classification)
print()
# Step 2: 자동응답 가능 여부 확인
if "자동응답 가능: 예" in classification:
print("✅ 자동응답 가능 - 답장 초안 생성 중...")
# 카테고리 추출 (간단한 파싱)
category = "일반문의" # 기본값
for cat in ["가격문의", "샘플요청", "기술문의", "배송문의"]:
if cat in classification:
category = cat
break
reply = generate_reply(subject, body, category)
print("\n📝 생성된 답장 초안:")
print(reply)
else:
print("⚠️ 자동응답 불가 - 담당자 확인 필요")
print("\n" + "=" * 50)
실행
# 통합 테스트
process_inquiry(test1_subject, test1_body)
실습 5: 여러 이메일 처리
배치 처리
# 여러 이메일 리스트
emails = [
{
"subject": "Price list request",
"body": "Hi, can you send me your current price list for skincare? Thanks, Maria"
},
{
"subject": "Sample request for trade show",
"body": "We have a trade show next month. Can you send samples of your top 5 products? We'll cover shipping."
},
{
"subject": "URGENT: Order delay inquiry",
"body": "Our order #5678 was supposed to arrive last week. What's the status? Our customers are waiting!"
}
]
# 모든 이메일 처리
for i, email in enumerate(emails, 1):
print(f"\n{'#'*60}")
print(f"이메일 {i}/{len(emails)}")
print(f"{'#'*60}")
process_inquiry(email["subject"], email["body"])
확장 아이디어
Google Sheets 연동
# (실제 사용 시 추가 설정 필요)
# 결과를 스프레드시트에 기록
def log_to_sheet(data):
"""
분류 결과를 Google Sheets에 기록
- 날짜/시간
- 이메일 제목
- 카테고리
- 긴급도
- 처리 상태
"""
# gspread 라이브러리 활용
pass
정기 실행 (Apps Script)
// Google Apps Script에서 정기적으로 실행
// Gmail 새 메일 체크 → Colab API 호출 → 결과 처리
트러블슈팅
API 오류
# API 호출 시 에러 처리
import time
def safe_generate(prompt, max_retries=3):
for attempt in range(max_retries):
try:
response = model.generate_content(prompt)
return response.text
except Exception as e:
print(f"시도 {attempt+1} 실패: {e}")
if attempt < max_retries - 1:
time.sleep(2) # 2초 대기 후 재시도
return "오류: 응답 생성 실패"
응답 파싱
# 구조화된 응답을 위한 JSON 요청
import json
def classify_email_json(subject, body):
prompt = f"""
이메일을 분석하고 반드시 아래 JSON 형식으로만 답변하세요:
{{
"category": "가격문의|샘플요청|기술문의|배송문의|클레임|일반문의",
"urgency": "높음|보통|낮음",
"auto_reply": true|false,
"summary": "한 문장 요약"
}}
이메일:
제목: {subject}
본문: {body}
"""
response = model.generate_content(prompt)
try:
# JSON 파싱 시도
result = json.loads(response.text)
return result
except:
return {"error": "파싱 실패", "raw": response.text}
다음 단계
- 저장: 노트북을 Google Drive에 저장
- 확장: 실제 Gmail 연동 시도
- 개선: 분류 정확도 향상을 위한 프롬프트 튜닝
- 배포: Google Apps Script로 자동화
체크리스트
□ API 키 발급 완료
□ Colab 노트북 생성
□ 라이브러리 설치
□ 분류 함수 작동 확인
□ 응답 생성 함수 작동 확인
□ 통합 봇 테스트 완료
□ 노트북 저장