gpt4omini / app.py
yoon2566's picture
Update app.py
4860ab4 verified
import os
from langchain.chat_models import ChatOpenAI
from langchain import ConversationChain
from openai import OpenAI
import gradio as gr
# API ํ‚ค๋ฅผ ํ™˜๊ฒฝ ๋ณ€์ˆ˜๋กœ ์„ค์ •
os.environ["OPENAI_API_KEY"] = os.environ.get("GPT_API_KEY")
# LangChain์„ ์œ„ํ•œ LLM ์ดˆ๊ธฐํ™”
llm = ChatOpenAI(temperature=0, # ์ฐฝ์˜์„ฑ 0์œผ๋กœ ์„ค์ •
model_name='gpt-4o-mini', # ๋ชจ๋ธ๋ช… (์˜ˆ: "gpt-4")
)
# ConversationChain ์ดˆ๊ธฐํ™”
conversation = ConversationChain(llm=llm, verbose=True)
# OpenAI ํด๋ผ์ด์–ธํŠธ ์ดˆ๊ธฐํ™”
client = OpenAI()
# ์ฑ—๋ด‡ ์‘๋‹ต ํ•จ์ˆ˜
def chatbot_response(message, chat_history):
# ConversationChain์„ ์‚ฌ์šฉํ•˜์—ฌ ์‘๋‹ต ์ƒ์„ฑ
bot_message = conversation.predict(input=message)
# ์ฑ„ํŒ… ํžˆ์Šคํ† ๋ฆฌ์— ์‚ฌ์šฉ์ž ๋ฉ”์‹œ์ง€์™€ ์ฑ—๋ด‡ ์‘๋‹ต ์ถ”๊ฐ€
chat_history.append((message, bot_message))
return "", chat_history
# Gradio ์ธํ„ฐํŽ˜์ด์Šค ์ƒ์„ฑ
with gr.Blocks() as demo:
# ์ฑ„ํŒ… ํžˆ์Šคํ† ๋ฆฌ๋ฅผ ์ €์žฅํ•  ์ปดํฌ๋„ŒํŠธ
chatbot = gr.Chatbot(label="์ฑ„ํŒ… ๊ธฐ๋ก")
# ์‚ฌ์šฉ์ž ์ž…๋ ฅ์„ ๋ฐ›์„ ํ…์ŠคํŠธ ๋ฐ•์Šค
msg = gr.Textbox(label="๋ฉ”์‹œ์ง€ ์ž…๋ ฅ", placeholder="์—ฌ๊ธฐ์— ๋ฉ”์‹œ์ง€๋ฅผ ์ž…๋ ฅํ•˜๊ณ  ์—”ํ„ฐ๋ฅผ ๋ˆ„๋ฅด์„ธ์š”.")
# ์ „์†ก ๋ฒ„ํŠผ (์˜ต์…˜)
send_button = gr.Button("์ „์†ก")
# ์ฑ„ํŒ… ํžˆ์Šคํ† ๋ฆฌ ์ดˆ๊ธฐํ™” ๋ฒ„ํŠผ
clear_button = gr.Button("์ดˆ๊ธฐํ™”")
# ์—”ํ„ฐ ํ‚ค ๋˜๋Š” ์ „์†ก ๋ฒ„ํŠผ ํด๋ฆญ ์‹œ ๋™์ž‘
msg.submit(
chatbot_response, # ์‘๋‹ต ํ•จ์ˆ˜
inputs=[msg, chatbot], # ์ž…๋ ฅ: ๋ฉ”์‹œ์ง€์™€ ์ฑ„ํŒ… ๊ธฐ๋ก
outputs=[msg, chatbot], # ์ถœ๋ ฅ: ๋ฉ”์‹œ์ง€ ๋ฐ•์Šค ์ดˆ๊ธฐํ™” ๋ฐ ์ฑ„ํŒ… ๊ธฐ๋ก ์—…๋ฐ์ดํŠธ
)
send_button.click(
chatbot_response, # ์‘๋‹ต ํ•จ์ˆ˜
inputs=[msg, chatbot], # ์ž…๋ ฅ: ๋ฉ”์‹œ์ง€์™€ ์ฑ„ํŒ… ๊ธฐ๋ก
outputs=[msg, chatbot], # ์ถœ๋ ฅ: ๋ฉ”์‹œ์ง€ ๋ฐ•์Šค ์ดˆ๊ธฐํ™” ๋ฐ ์ฑ„ํŒ… ๊ธฐ๋ก ์—…๋ฐ์ดํŠธ
)
# ์ดˆ๊ธฐํ™” ๋ฒ„ํŠผ ํด๋ฆญ ์‹œ ๋™์ž‘
clear_button.click(
lambda: None, # ์•„๋ฌด ๋™์ž‘๋„ ํ•˜์ง€ ์•Š์Œ
inputs=None,
outputs=chatbot, # ์ฑ„ํŒ… ๊ธฐ๋ก ์ดˆ๊ธฐํ™”
queue=False, # ํ ๋น„ํ™œ์„ฑํ™”
)
# ์ธํ„ฐํŽ˜์ด์Šค ์‹คํ–‰
demo.launch(share=True)