84 lines
2.2 KiB
Python
84 lines
2.2 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""
|
|
공통 유틸리티 함수
|
|
- Claude API 호출
|
|
- JSON/HTML 추출
|
|
"""
|
|
|
|
import os
|
|
import re
|
|
import json
|
|
import anthropic
|
|
from api_config import API_KEYS
|
|
|
|
# Claude API 클라이언트
|
|
client = anthropic.Anthropic(
|
|
api_key=API_KEYS.get('CLAUDE_API_KEY', '')
|
|
)
|
|
|
|
|
|
def call_claude(system_prompt: str, user_message: str, max_tokens: int = 8000) -> str:
|
|
"""Claude API 호출"""
|
|
response = client.messages.create(
|
|
model="claude-sonnet-4-20250514",
|
|
max_tokens=max_tokens,
|
|
system=system_prompt,
|
|
messages=[{"role": "user", "content": user_message}]
|
|
)
|
|
return response.content[0].text
|
|
|
|
|
|
def extract_json(text: str) -> dict:
|
|
"""텍스트에서 JSON 추출"""
|
|
# 코드 블록 제거
|
|
if '```json' in text:
|
|
text = text.split('```json')[1].split('```')[0]
|
|
elif '```' in text:
|
|
text = text.split('```')[1].split('```')[0]
|
|
|
|
text = text.strip()
|
|
|
|
# JSON 파싱 시도
|
|
try:
|
|
return json.loads(text)
|
|
except json.JSONDecodeError:
|
|
# JSON 부분만 추출 시도
|
|
match = re.search(r'\{[\s\S]*\}', text)
|
|
if match:
|
|
try:
|
|
return json.loads(match.group())
|
|
except:
|
|
pass
|
|
return None
|
|
|
|
|
|
def extract_html(text: str) -> str:
|
|
"""텍스트에서 HTML 추출"""
|
|
# 코드 블록 제거
|
|
if '```html' in text:
|
|
text = text.split('```html')[1].split('```')[0]
|
|
elif '```' in text:
|
|
parts = text.split('```')
|
|
if len(parts) >= 2:
|
|
text = parts[1]
|
|
|
|
text = text.strip()
|
|
|
|
# <!DOCTYPE 또는 <html로 시작하는지 확인
|
|
if not text.startswith('<!DOCTYPE') and not text.startswith('<html'):
|
|
# HTML 부분만 추출
|
|
match = re.search(r'(<!DOCTYPE html[\s\S]*</html>)', text, re.IGNORECASE)
|
|
if match:
|
|
text = match.group(1)
|
|
|
|
return text
|
|
|
|
|
|
def load_prompt(prompts_dir: str, filename: str) -> str:
|
|
"""프롬프트 파일 로드"""
|
|
prompt_path = os.path.join(prompts_dir, filename)
|
|
try:
|
|
with open(prompt_path, 'r', encoding='utf-8') as f:
|
|
return f.read()
|
|
except FileNotFoundError:
|
|
return None |