42 lines
1.5 KiB
Python
42 lines
1.5 KiB
Python
import logging
|
|
from openai import OpenAI
|
|
import json
|
|
import re
|
|
import logging
|
|
|
|
|
|
class GPTClient:
|
|
def __init__(self, model="gpt-4o-mini", temperature=0.2):
|
|
self.client = None
|
|
self.model = model
|
|
self.temperature = temperature
|
|
|
|
self.set_client(api_key='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')
|
|
|
|
def set_client(self, api_key):
|
|
self.client = OpenAI(api_key=api_key)
|
|
|
|
def ask(self, prompt: str) -> dict:
|
|
"""프롬프트를 이용하여 GPT 모델로부터 응답을 받습니다. 항상 JSON 형식으로 반환."""
|
|
try:
|
|
response = self.client.chat.completions.create(
|
|
model=self.model,
|
|
temperature=self.temperature,
|
|
messages=[{"role": "user", "content": prompt}]
|
|
)
|
|
# GPT 응답 내용 가져오기
|
|
content = response.choices[0].message.content.strip()
|
|
print(f'GPT 응답: {content}')
|
|
# 불필요한 포맷팅 제거 (```json```)
|
|
cleaned_content = re.sub(r"^```json|```$", "", content).strip()
|
|
|
|
# JSON 변환 시도
|
|
return json.loads(cleaned_content)
|
|
except json.JSONDecodeError as e:
|
|
print(f'JSON 디코딩 실패: {e}. 원본 응답: {content}')
|
|
|
|
return {}
|
|
except Exception as e:
|
|
print(f'GPT 통신 오류: {e}')
|
|
return {}
|