from flask import Flask, request, jsonify, send_from_directory
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from dotenv import load_dotenv

load_dotenv()
app = Flask(__name__)

# --- (2) LCEL 체인: 프롬프트 → 모델 → 문자열 ---
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
prompt = ChatPromptTemplate.from_messages([
    ("system", "당신은 친절한 한국어 도우미입니다. 간결하게 답하세요."),
    ("human", "{question}"),
])
chain = prompt | llm | StrOutputParser()


# --- (1) 채팅 화면 ---
@app.get("/")
def index():
    return send_from_directory(app.static_folder, "01.html")


# --- (3) 질의응답 API: 문서 없이 그냥 모델에게 묻는다 ---
@app.post("/ask")
def ask():
    answer = chain.invoke({"question": request.json["question"]})
    return jsonify({"answer": answer})


if __name__ == "__main__":
    app.run(debug=True, port=5000)
