68 lines
2.4 KiB
Python
68 lines
2.4 KiB
Python
import os
|
|
import json
|
|
from openai import OpenAI
|
|
from dotenv import load_dotenv
|
|
from models import ParsedRealEstate
|
|
|
|
load_dotenv()
|
|
|
|
class OpenAIParser:
|
|
"""OpenAI를 이용한 부동산 정보 파싱"""
|
|
|
|
def __init__(self):
|
|
api_key = os.getenv("OPENAI_API_KEY")
|
|
if not api_key or api_key == "your-api-key-here":
|
|
raise ValueError("OpenAI API key not configured in .env file")
|
|
self.client = OpenAI(api_key=api_key)
|
|
|
|
async def parse_real_estate_query(self, text: str) -> ParsedRealEstate:
|
|
"""자연어 텍스트에서 부동산 정보 추출"""
|
|
|
|
system_prompt = """
|
|
당신은 부동산 정보를 추출하는 전문가입니다.
|
|
사용자의 자연어 입력에서 다음 정보를 추출하세요.
|
|
단위는 붙여서 표기하세요. :
|
|
1. price: 가격 (전세금, 월세, 매매가 등) (string)
|
|
2. location: 위치 (지역명, 동, 구 등) (string)
|
|
3. area: 면적 (평수, 제곱미터) (string)
|
|
4. rooms: 방 개수 (string)
|
|
5. transaction_type: 거래 유형 (전세, 월세, 매매) (string)
|
|
|
|
JSON 형식으로만 응답하세요.
|
|
정보가 없는 항목은 null로 표시하세요.
|
|
"""
|
|
|
|
try:
|
|
response = self.client.chat.completions.create(
|
|
model="gpt-3.5-turbo",
|
|
messages=[
|
|
{"role": "system", "content": system_prompt},
|
|
{"role": "user", "content": text}
|
|
],
|
|
temperature=0.1,
|
|
response_format={"type": "json_object"}
|
|
)
|
|
|
|
result = json.loads(response.choices[0].message.content)
|
|
print(result)
|
|
|
|
return ParsedRealEstate(
|
|
price=result.get("price"),
|
|
location=result.get("location"),
|
|
area=result.get("area"),
|
|
rooms=result.get("rooms"),
|
|
transaction_type=result.get("transaction_type"),
|
|
raw_text=text
|
|
)
|
|
|
|
except Exception as e:
|
|
print(e)
|
|
# 에러 발생 시 기본값 반환
|
|
return ParsedRealEstate(
|
|
raw_text=text,
|
|
price=None,
|
|
location=None,
|
|
area=None,
|
|
rooms=None,
|
|
transaction_type=None
|
|
) |