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)