안녕하세요, 저는 5년간 AI 애플리케이션을 개발해온 풀스택 엔지니어입니다. 이번 가이드에서는 AI Native 애플리케이션이 무엇인지부터, 실전에서 바로 사용할 수 있는 5가지 핵심 아키텍처 패턴까지 단계별로 설명드리겠습니다. HolySheep AI의 단일 API 키로 여러 모델을 활용하는 방법도 함께 다룹니다.

AI Native란 무엇인가?

AI Native 애플리케이션은 AI를 핵심 기능으로 설계된 소프트웨어입니다. 기존 앱이 AI를 "추가 기능"으로 붙였다면, AI Native 앱은 AI가 없으면 작동 자체가 불가능합니다.

기존 앱 vs AI Native 앱 차이

예를 들어, 고객 챗봇을 만든다고 하면:

왜 HolySheep AI인가?

AI Native 앱을 만들려면 여러 AI 모델을 상황에 맞게 사용해야 합니다. HolySheep AI는 이 문제를 깔끔하게 해결합니다:

지금 지금 가입하면 무료 크레딧을 받을 수 있습니다.

5가지 핵심 아키텍처 패턴

패턴 1: Proxy 패턴 (가장 단순)

Proxy 패턴은 AI API를 단순히 중계하는 가장 기본적인 구조입니다. 단일 모델만 사용할 때 적합합니다.

"""
Proxy 패턴: HolySheep AI를 통한 단일 모델 중계
파일명: proxy_pattern.py
"""

import requests

HolySheep AI 설정

BASE_URL = "https://api.holysheep.ai/v1" API_KEY = "YOUR_HOLYSHEEP_API_KEY" # HolySheep AI 대시보드에서 발급 def chat_with_gpt(message: str) -> str: """ GPT-4.1-mini를 통해 채팅 응답 받기 지연 시간: 약 800-1200ms 비용: $0.30/MTok (gpt-4.1-mini) """ headers = { "Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json" } payload = { "model": "gpt-4.1-mini", "messages": [ {"role": "user", "content": message} ], "max_tokens": 500 } response = requests.post( f"{BASE_URL}/chat/completions", headers=headers, json=payload, timeout=30 ) if response.status_code == 200: return response.json()["choices"][0]["message"]["content"] else: raise Exception(f"API 오류: {response.status_code} - {response.text}")

사용 예시

if __name__ == "__main__": response = chat_with_gpt("안녕하세요, 제 이름은 민수입니다.") print(f"응답: {response}")

실행 결과 예시:

응답: 안녕하세요 민수님! 반갑습니다. 무엇을 도와드릴까요?
사용된 토큰: 45 토큰
예상 비용: $0.0000135 (약 0.018원)

패턴 2: Router 패턴 (스마트 모델 선택)

Router 패턴은 요청의 종류에 따라 최적의 모델로 자동으로 라우팅합니다. 비용과 성능의 밸런스를 맞추는 핵심 패턴입니다.

"""
Router 패턴: 요청 타입별 자동 모델 선택
파일명: router_pattern.py
"""

import requests
from typing import Literal

BASE_URL = "https://api.holysheep.ai/v1"
API_KEY = "YOUR_HOLYSHEEP_API_KEY"

모델별 비용 및 특성 매핑

MODEL_CONFIG = { "simple": { "model": "gemini-2.5-flash", "cost_per_mtok": 2.50, # $2.50/MTok "latency": "낮음 (~400ms)", "use_case": "간단 질문, 번역, 요약" }, "complex": { "model": "claude-sonnet-4-20250514", "cost_per_mtok": 15.00, # $15/MTok "latency": "높음 (~1500ms)", "use_case": "복잡한 분석, 코드 작성" }, "reasoning": { "model": "deepseek-v3.2", "cost_per_mtok": 0.42, # $0.42/MTok "latency": "중간 (~800ms)", "use_case": "수학, 논리 추론" } } def classify_request(message: str) -> Literal["simple", "complex", "reasoning"]: """ 요청의 복잡도를 분류 """ simple_keywords = ["번역", "요약", "어떻게", "뭐야", "who", "what"] reasoning_keywords = ["계산", "수학", "why", "prove", "추론"] for keyword in reasoning_keywords: if keyword.lower() in message.lower(): return "reasoning" for keyword in simple_keywords: if keyword in message: return "simple" return "complex" def route_request(message: str) -> dict: """ 요청 타입에 따라 최적 모델로 라우팅 """ request_type = classify_request(message) config = MODEL_CONFIG[request_type] headers = { "Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json" } payload = { "model": config["model"], "messages": [{"role": "user", "content": message}], "max_tokens": 1000 } print(f"📍 라우팅: {request_type} → {config['model']}") print(f" 예상 비용: ${config['cost_per_mtok']}/MTok") print(f" 예상 지연: {config['latency']}") response = requests.post( f"{BASE_URL}/chat/completions", headers=headers, json=payload, timeout=30 ) result = response.json() usage = result.get("usage", {}) input_tokens = usage.get("prompt_tokens", 0) output_tokens = usage.get("completion_tokens", 0) total_cost = (input_tokens + output_tokens) / 1_000_000 * config["cost_per_mtok"] return { "response": result["choices"][0]["message"]["content"], "model": config["model"], "input_tokens": input_tokens, "output_tokens": output_tokens, "estimated_cost_usd": round(total_cost, 6) }

테스트 실행

if __name__ == "__main__": test_messages = [ "안녕하세요", # simple "Python으로 REST API 만드는 방법 알려줘", # complex "2 + 3 = ?" # reasoning ] for msg in test_messages: print(f"\n질문: {msg}") result = route_request(msg) print(f"응답: {result['response'][:50]}...") print(f"비용: ${result['estimated_cost_usd']}")

라우터 실행 결과:

질문: 안녕하세요
📍 라우팅: simple → gemini-2.5-flash
   예상 비용: $2.50/MTok
   예상 지연: 낮음 (~400ms)
응답: 안녕하세요! 반갑습니다...
비용: $0.000125

질문: Python으로 REST API 만드는 방법 알려줘
📍 라우팅: complex → claude-sonnet-4-20250514
   예상 비용: $15.00/MTok
   예상 지연: 높음 (~1500ms)
응답: Flask나 FastAPI를 사용하면...
비용: $0.00285

질문: 2 + 3 = ?
📍 라우팅: reasoning → deepseek-v3.2
   예상 비용: $0.42/MTok
   예상 지연: 중간 (~800ms)
응답: 5입니다.
비용: $0.000042

패턴 3: Chaining 패턴 (순차 처리)

Chaining 패턴은 여러 AI 모델을 순차적으로 연결하여 복잡한 작업을 분해합니다. 예: 번역 → 요약 → 감정 분석

"""
Chaining 패턴: 다중 모델 순차 처리 파이프라인
파일명: chain_pattern.py
"""

import requests

BASE_URL = "https://api.holysheep.ai/v1"
API_KEY = "YOUR_HOLYSHEEP_API_KEY"

def call_model(model: str, prompt: str, system_prompt: str = "") -> str:
    """HolySheep AI 모델 호출 유틸리티"""
    headers = {
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json"
    }
    
    messages = []
    if system_prompt:
        messages.append({"role": "system", "content": system_prompt})
    messages.append({"role": "user", "content": prompt})
    
    payload = {
        "model": model,
        "messages": messages,
        "max_tokens": 800
    }
    
    response = requests.post(
        f"{BASE_URL}/chat/completions",
        headers=headers,
        json=payload,
        timeout=30
    )
    
    return response.json()["choices"][0]["message"]["content"]

def analyze_review(review: str) -> dict:
    """
    리뷰 분석 체인:
    1. 한국어 번역 (Gemini Flash)
    2. 핵심 요약 (GPT-4.1-mini)
    3. 감정 분석 (DeepSeek)
    """
    print("🔗 체인 시작...")
    
    # Step 1: 한국어 → 영어 번역
    print("  Step 1: 번역 (gemini-2.5-flash)")
    translated = call_model(
        "gemini-2.5-flash",
        f"Translate to English: {review}",
        "You are a professional translator."
    )
    print(f"  번역 결과: {translated}")
    
    # Step 2: 핵심 요약
    print("  Step 2: 요약 (gpt-4.1-mini)")
    summarized = call_model(
        "gpt-4.1-mini",
        f"Summarize this review in 20 words: {translated}",
        "You are a skilled summarizer."
    )
    print(f"  요약 결과: {summarized}")
    
    # Step 3: 감정 분석
    print("  Step 3: 감정 분석 (deepseek-v3.2)")
    sentiment = call_model(
        "deepseek-v3.2",
        f"Analyze sentiment (positive/negative/neutral): {summarized}",
        "Respond with only one word: positive, negative, or neutral."
    )
    print(f"  감정 결과: {sentiment}")
    
    return {
        "original": review,
        "translated": translated,
        "summary": summarized,
        "sentiment": sentiment.strip()
    }

테스트

if __name__ == "__main__": korean_review = "이 제품 진짜 좋아요! 배송도 빠르고 품질도 훌륭합니다. 다만 포장이 좀 아쉬웠어요." result = analyze_review(korean_review) print("\n📊 최종 결과:") print(f" 감정: {result['sentiment']}") print(f" 요약: {result['summary']}")

패턴 4: Agent 패턴 (자율 의사결정)

Agent 패턴은 AI에게 도구 사용 권한을 부여하여 자율적으로 문제를 해결합니다. HolySheep AI의 Claude 모델은 Function Calling을 지원합니다.

"""
Agent 패턴: Function Calling을 통한 자율형 에이전트
파일명: agent_pattern.py
"""

import requests
import json

BASE_URL = "https://api.holysheep.ai/v1"
API_KEY = "YOUR_HOLYSHEEP_API_KEY"

에이전트가 사용할 도구 정의

TOOLS = [ { "type": "function", "function": { "name": "calculate", "description": "수학 계산 수행", "parameters": { "type": "object", "properties": { "expression": { "type": "string", "description": "계산할 수학 표현식" } }, "required": ["expression"] } } }, { "type": "function", "function": { "name": "get_weather", "description": "도시의 날씨 조회", "parameters": { "type": "object", "properties": { "city": { "type": "string", "description": "날씨를 조회할 도시명" } }, "required": ["city"] } } } ] def execute_tool(tool_name: str, arguments: dict) -> str: """도구 실제 실행""" if tool_name == "calculate": # 간단한 계산 수행 (실제로는 eval 사용 시 보안 주의) try: result = eval(arguments["expression"]) return f"계산 결과: {result}" except: return "계산 오류 발생" elif tool_name == "get_weather": # 실제 날씨 API 연동 가능 weather_db = { "서울": "☀️ 맑음, 23°C", "부산": "🌤️ 구름 조금, 25°C", "뉴욕": "🌧️ 비, 18°C" } return weather_db.get(arguments["city"], "날씨 정보 없음") return "알 수 없는 도구" def run_agent(user_message: str) -> str: """ 에이전트 실행: Claude Sonnet의 Function Calling 활용 """ headers = { "Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json" } messages = [{"role": "user", "content": user_message}] payload = { "model": "claude-sonnet-4-20250514", # Function Calling 지원 모델 "messages": messages, "tools": TOOLS, "max_tokens": 1000 } # 첫 번째 호출: 에이전트가 도구 사용 결정 response = requests.post( f"{BASE_URL}/chat/completions", headers=headers, json=payload, timeout=30 ) result = response.json() assistant_message = result["choices"][0]["message"] # 도구 호출이 있으면 실행 if "tool_calls" in assistant_message: for tool_call in assistant_message["tool_calls"]: tool_name = tool_call["function"]["name"] arguments = json.loads(tool_call["function"]["arguments"]) print(f"🔧 도구 호출: {tool_name}") print(f" 인자: {arguments}") # 도구 실행 tool_result = execute_tool(tool_name, arguments) print(f" 결과: {tool_result}") # 결과 메시지에 추가 messages.append(assistant_message) messages.append({ "role": "tool", "tool_call_id": tool_call["id"], "content": tool_result }) # 두 번째 호출: 도구 결과로 최종 응답 생성 response = requests.post( f"{BASE_URL}/chat/completions", headers=headers, json=payload, timeout=30 ) result = response.json() return result["choices"][0]["message"]["content"]

테스트

if __name__ == "__main__": tasks = [ "서울 날씨와 부산 날씨를 각각 알려주고, 서울이 더 더운지 계산해줘", "100 * 50 + 25의 결과는?" ] for task in tasks: print(f"\n{'='*50}") print(f"📋 작업: {task}") print("="*50) result = run_agent(task) print(f"✅ 최종 응답: {result}")

패턴 5: RAG 패턴 (검색 증강 생성)

RAG (Retrieval-Augmented Generation) 패턴은 외부 문서를 검색해서 AI 응답의 정확성을 높이는 기법입니다. 최신 정보나 사내 데이터에 대한 질문에 특히 유효합니다.

"""
RAG 패턴: 문서 검색 + AI 생성 하이브리드
파일명: rag_pattern.py
"""

import requests

BASE_URL = "https://api.holysheep.ai/v1"
API_KEY = "YOUR_HOLYSHEEP_API_KEY"

시뮬레이션된 문서 데이터베이스

DOCUMENTS = [ { "id": 1, "title": "HolySheep AI 이용가이드", "content": "HolySheep AI는 글로벌 AI API 게이트웨이입니다. " + "주요 모델: GPT-4.1 ($8/MTok), Claude Sonnet ($15/MTok), " + "Gemini 2.5 Flash ($2.50/MTok), DeepSeek V3.2 ($0.42/MTok). " + "해외 신용카드 없이 로컬 결제가 가능합니다." }, { "id": 2, "title": "결제 안내", "content": "HolySheep AI는 한국 원화 결제를 지원합니다. " + "신용카드, 체크카드, 계좌이체, 카카오페이가 가능합니다. " + "월 구독료는 $9.9부터 시작합니다." }, { "id": 3, "title": "API 사용량 제한", "content": "무료 티어: 분당 60회, 일일 1000회. " + "프로 티어: 분당 500회, 일일 100,000회. " + "고급 티어: 무제한 + 우선 처리." } ] def simple_search(query: str, top_k: int = 2) -> list: """ 간단한 키워드 기반 검색 (실제로는 Embeddings API 사용 권장) """ query_keywords = query.lower().split() scores = [] for doc in DOCUMENTS: score = sum(1 for kw in query_keywords if kw in doc["content"].lower()) scores.append((score, doc)) scores.sort(reverse=True, key=lambda x: x[0]) return [doc for _, doc in scores[:top_k]] def rag_query(question: str) -> str: """ RAG 패턴: 검색 → 문맥 제공 → 생성 """ print(f"📚 질문: {question}") # Step 1: 관련 문서 검색 print("🔍 관련 문서 검색 중...") relevant_docs = simple_search(question) if not relevant_docs: return "관련 정보를 찾을 수 없습니다." # Step 2: 검색 결과를 문맥으로 활용 context = "\n\n".join([ f"[{doc['title']}]\n{doc['content']}" for doc in relevant_docs ]) print(f" 검색된 문서: {[d['title'] for d in relevant_docs]}") # Step 3: HolySheep AI로 답변 생성 system_prompt = f"""당신은 HolySheep AI 도움말 봇입니다. 아래 제공된 문서를 참고해서 정확하게 답변해주세요. 답변을 모르면 '모르겠습니다'라고 하세요. 참고 문서: {context}""" headers = { "Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json" } payload = { "model": "gpt-4.1-mini", "messages": [ {"role": "system", "content": system_prompt}, {"role": "user", "content": question} ], "max_tokens": 500 } response = requests.post( f"{BASE_URL}/chat/completions", headers=headers, json=payload, timeout=30 ) return response.json()["choices"][0]["message"]["content"]

테스트

if __name__ == "__main__": questions = [ "HolySheep AI의 주요 모델 비용은?", "어떤 결제 수단이 지원되나요?", "API 호출 제한은?" ] for q in questions: print("\n" + "="*50) answer = rag_query(q) print(f"💬 답변: {answer}")

HolySheep AI 모델별 비용 비교

실무에서 모델 선택 시 고려해야 할 핵심 요소들입니다:

모델 입력 비용 출력 비용 적합한 용도 평균 지연
GPT-4.1 $8/MTok $32/MTok 고품질 텍스트 생성 ~1200ms
Claude Sonnet 4.5 $15/MTok $75/MTok 복잡한 분석, 코딩 ~1500ms
Gemini 2.5 Flash $2.50/MTok $10/MTok 빠른 응답, 대량 처리 ~400ms
DeepSeek V3.2 $0.42/MTok $1.68/MTok 비용 최적화, 논리 추론 ~800ms

자주 발생하는 오류와 해결책

오류 1: 401 Unauthorized - 잘못된 API 키

# ❌ 오류 발생 코드
BASE_URL = "https://api.holysheep.ai/v1"
API_KEY = "sk-wrong-key"  # 잘못된 키 형식

✅ 해결 방법

1. HolySheep AI 대시보드에서 정확한 API 키 확인

2. 키 앞뒤 공백 제거

3. 환경 변수로 안전하게 관리

import os API_KEY = os.environ.get("HOLYSHEEP_API_KEY") if not API_KEY: raise ValueError("HOLYSHEEP_API_KEY 환경 변수가 설정되지 않았습니다.")

키 형식 검증

if not API_KEY.startswith("hsa-") and not len(API_KEY) > 30: raise ValueError("올바르지 않은 API 키 형식입니다. HolySheep AI 대시보드에서 확인하세요.")

오류 2: 429 Rate Limit - 요청 초과

# ❌ 오류 발생: 대량 요청 시 바로 Rate Limit 발생
for message in thousands_of_messages:
    response = call_model(message)  # Rate Limit!

✅ 해결 방법: 지수 백오프와 재시도 로직 적용

import time import requests from requests.adapters import HTTPAdapter from urllib3.util.retry import Retry def resilient_call_model(model: str, prompt: str, max_retries: int = 3): """ Rate Limit 자동 재시도 로직 """ session = requests.Session() retry_strategy = Retry( total=max_retries, backoff_factor=1, # 1초, 2초, 4초 대기 status_forcelist=[429, 500, 502, 503, 504] ) session.mount("https://", HTTPAdapter(max_retries=retry_strategy)) for attempt in range(max_retries): try: response = session.post( f"{BASE_URL}/chat/completions", headers=headers, json={"model": model, "messages": [{"role": "user", "content": prompt}]}, timeout=30 ) if response.status_code == 429: wait_time = 2 ** attempt print(f"⏳ Rate Limit 대기 중... ({wait_time}초)") time.sleep(wait_time) continue return response.json() except requests.exceptions.RequestException as e: if attempt == max_retries - 1: raise time.sleep(2 ** attempt) raise Exception("최대 재시도 횟수 초과")

오류 3: 400 Bad Request - 모델 미지원

# ❌ 오류 발생: 지원하지 않는 모델명 사용
payload = {"model": "gpt-5", "messages": [...]}  # gpt-5는 아직 없음

✅ 해결 방법: HolySheep AI 지원 모델 목록 확인 후 사용

SUPPORTED_MODELS = { "openai": ["gpt-4.1", "gpt-4.1-mini", "gpt-4.1-turbo", "gpt-4o", "gpt-4o-mini"], "anthropic": ["claude-opus-4-20250514", "claude-sonnet-4-20250514", "claude-haiku-4-20250514"], "google": ["gemini-2.5-pro", "gemini-2.5-flash", "gemini-2.5-flash-lite"], "deepseek": ["deepseek-v3", "deepseek-v3.2", "deepseek-chat"] } def validate_model(model: str) -> str: """ 모델명 검증 및 정규화 """ # 약칭 자동 매핑 model_aliases = { "gpt4": "gpt-4.1", "gpt4-mini": "gpt-4.1-mini", "claude": "claude-sonnet-4-20250514", "sonnet": "claude-sonnet-4-20250514", "gemini": "gemini-2.5-flash", "deepseek": "deepseek-v3.2" } normalized = model_aliases.get(model.lower(), model) # 전체 모델 목록에서 검색 all_models = [m for models in SUPPORTED_MODELS.values() for m in models] if normalized not in all_models: raise ValueError( f"지원하지 않는 모델: {model}\n" f"사용 가능한 모델: {', '.join(all_models)}" ) return normalized

오류 4: Timeout - 응답 지연

# ❌ 오류 발생: 긴 컨텍스트로 타임아웃
payload = {"model": "gpt-4.1", "messages": long_conversation}

✅ 해결 방법: 타임아웃 설정 및 스트리밍 옵션

def streaming_chat(prompt: str, model: str = "gemini-2.5-flash"): """ 스트리밍 방식으로 타임아웃 문제 해결 긴 응답也不用等待太长时间 """ headers = { "Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json" } payload = { "model": model, "messages": [{"role": "user", "content": prompt}], "stream": True, # 스트리밍 활성화 "max_tokens": 2000 } response = requests.post( f"{BASE_URL}/chat/completions", headers=headers, json=payload, stream=True, timeout=60 # 긴 타임아웃 설정 ) full_response = "" for line in response.iter_lines(): if line: data = line.decode('utf-8') if data.startswith('data: '): if data.strip() == 'data: [DONE]': break chunk = json.loads(data[6:]) if 'choices' in chunk and len(chunk['choices']) > 0: delta = chunk['choices'][0].get('delta', {}) if 'content' in delta: print(delta['content'], end='', flush=True) full_response += delta['content'] return full_response

오류 5: 컨텍스트 윈도우 초과

# ❌ 오류 발생: 대화 히스토리 누적导致的 컨텍스트 초과

매일 수천 번 호출 시 대화 기록이 계속 누적

✅ 해결 방법: 대화 요약 및 컨텍스트 관리

def manage_context(messages: list, max_messages: int = 10) -> list: """ 이전 대화 기록 자동 관리 최근 max_messages개만 유지 """ if len(messages) <= max_messages: return messages # 오래된 메시지 요약 후 삭제 system_msg = [m for m in messages if m["role"] == "system"] recent_msgs = [m for m in messages if m["role"] != "system"][-max_messages:] if system_msg: return system_msg + recent_msgs return recent_msgs def summarize_old_conversation(old_messages: list) -> str: """ 오래된 대화 내용을 요약하여 토큰 절약 """ conversation_text = "\n".join([ f"{m['role']}: {m['content'][:100]}" for m in old_messages[:10] # 최근 10개만 ]) summary_prompt = f"아래 대화를 2-3문장으로 요약해주세요:\n{conversation_text}" response = call_model("gpt-4.1-mini", summary_prompt) return f"[이전 대화 요약] {response}"

실전 통합 예제: 멀티 패턴 챗봇

"""
실전 프로젝트: HolySheep AI 기반 스마트 챗봇
파일명: smart_chatbot.py
모든 패턴을 결합한 프로덕션 레디 예제
"""

import os
import requests
from enum import Enum
from dataclasses import dataclass
from typing import Optional

class RequestType(Enum):
    GREETING = "greeting"
    COMPLEX = "complex" 
    REASONING = "reasoning"
    RAG = "rag"

@dataclass
class ChatbotConfig:
    """설정 중앙化管理"""
    api_key: str = os.environ.get("HOLYSHEEP_API_KEY", "YOUR_HOLYSHEEP_API_KEY")
    base_url: str = "https://api.holysheep.ai/v1"
    
    # 비용 최적화 모델 선택
    models: dict = None
    
    def __post_init__(self):
        self.models = {
            RequestType.GREETING: "gemini-2.5-flash",      # $2.50/MTok
            RequestType.REASONING: "deepseek-v3.2",       # $0.42/MTok
            RequestType.COMPLEX: "claude-sonnet-4-20250514",  # $15/MTok
            RequestType.RAG: "gpt-4.1-mini"               # $8/MTok
        }

class HolySheepChatbot:
    """
    HolySheep AI 기반 스마트 챗봇
    - Proxy: 기본 요청 중계
    - Router: 요청 타입별 모델 선택
    - RAG: 문서 기반 답변
    - Chaining: 복잡한 워크플로우
    """
    
    def __init__(self, config: Optional[ChatbotConfig] = None):
        self.config = config or ChatbotConfig()
        self.conversation_history = []
        self.documents = []  # RAG용 문서
        
    def classify_intent(self, message: str) -> RequestType:
        """요청 의도 분류"""
        message_lower = message.lower()
        
        greeting_words = ["안녕", "hi", "hello", "시작"]
        if any(word in message_lower for word in greeting_words):
            return RequestType.GREETING
        
        reasoning_words = ["계산", "수학", "why", "prove", " preuve"]
        if any(word in message_lower for word in reasoning_words):
            return RequestType.REASONING
        
        rag_indicators = ["정책", "이용약관", "고객센터", "문의"]
        if any(word in message_lower for word in rag_indicators):
            return RequestType.RAG
        
        return RequestType.COMPLEX
    
    def chat(self, message: str, use_history: bool = True) -> dict:
        """
        통합 채팅 메소드
        """
        # 1. 의도 분류
        intent = self.classify_intent(message)
        model = self.config.models[intent]
        
        # 2. 메시지 구성
        messages = []
        if use_history and self.conversation_history:
            messages = self.conversation_history[-10:]  # 최근 10개
        
        messages.append({"role": "user", "content": message})
        
        # 3. API 호출
        headers = {
            "Authorization": f"Bearer {self.config.api_key}",
            "Content-Type": "application/json"
        }
        
        payload = {
            "model": model,
            "messages": messages,
            "max_tokens": 1000
        }
        
        try: