File size: 2,202 Bytes
9ee28b4 02e7d80 4ae99d5 02e7d80 4860ab4 02e7d80 4ae99d5 02e7d80 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
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) |