MyChat4 / app.py
hayaboy's picture
Update app.py
f016720 verified
import gradio as gr
from openai import OpenAI
import os
import openai
# client = OpenAI(api_key="sk-9hWFK-_5UQgzJMqT44ng72sZbKQXVvVXeVd11yoER3T3BlbkFJmd2HDc-N7CaH6PDRCYZfqe8hkT7DnxZNwcVkf3eeUA")
openai.api_key ="sk-9hWFK-_5UQgzJMqT44ng72sZbKQXVvVXeVd11yoER3T3BlbkFJmd2HDc-N7CaH6PDRCYZfqe8hkT7DnxZNwcVkf3eeUA"
import gradio as gr
# from langchain.chat_models import ChatOpenAI
# from langchain.memory import ConversationBufferMemory
# from langchain.chains import ConversationChain
# from langchain.schema import AIMessage, HumanMessage, SystemMessage
# from langchain.document_loaders import TextLoader
# from langchain.document_loaders import PyPDFLoader
#from langchain_community.chat_models import ChatOpenAI
from langchain_openai import ChatOpenAI
# from langchain_community.memory import ConversationBufferMemory
from langchain.memory import ConversationBufferMemory
from langchain.chains import ConversationChain
from langchain.schema import AIMessage, HumanMessage, SystemMessage
from langchain_community.document_loaders import TextLoader
from langchain_community.document_loaders import PyPDFLoader
from langchain_core.runnables import RunnableWithMessageHistory
# LLMκ³Ό λ©”λͺ¨λ¦¬ μ΄ˆκΈ°ν™”
llm = ChatOpenAI(temperature=0.0, model='gpt-3.5-turbo', openai_api_key="sk-9hWFK-_5UQgzJMqT44ng72sZbKQXVvVXeVd11yoER3T3BlbkFJmd2HDc-N7CaH6PDRCYZfqe8hkT7DnxZNwcVkf3eeUA")
memory = ConversationBufferMemory()
#memory = RunnableWithMessageHistory()
conversation = ConversationChain(
llm=llm,
memory=memory)
# μ„Έμ…˜ νžˆμŠ€ν† λ¦¬ μ •μ˜
def get_session_history():
return [] # μ„Έμ…˜ νžˆμŠ€ν† λ¦¬λ₯Ό κ΄€λ¦¬ν•˜λŠ” λ‘œμ§μ„ κ΅¬ν˜„ν•  수 μžˆμŠ΅λ‹ˆλ‹€.
# λ©”λͺ¨λ¦¬ 및 λŒ€ν™” μ΄ˆκΈ°ν™”
# memory = RunnableWithMessageHistory(runnable=llm, get_session_history=get_session_history)
# conversation = RunnableWithMessageHistory(llm=llm, memory=memory)
# 상담봇 - μ±„νŒ… 및 λ‹΅λ³€
def counseling_bot_chat(message, chat_history):
if message == "":
return "", chat_history
else:
result_message = ""
if len(chat_history) <= 1:
messages = [
SystemMessage(content="당신은 ν—€μ΄λ§ˆνŠΈμ˜ μƒλ‹΄μ›μž…λ‹ˆλ‹€. 마트 μƒν’ˆκ³Ό κ΄€λ ¨λ˜μ§€ μ•Šμ€ μ§ˆλ¬Έμ—λŠ” μ •μ€‘νžˆ κ±°μ ˆν•˜μ„Έμš”."),
AIMessage(content="μ•ˆλ…•ν•˜μ„Έμš”, ν—€μ΄λ§ˆνŠΈμž…λ‹ˆλ‹€. 상담을 λ„μ™€λ“œλ¦¬κ² μŠ΅λ‹ˆλ‹€."),
HumanMessage(content=message)
]
result_message = conversation.predict(input=messages)
else:
result_message = conversation.predict(input=message)
chat_history.append([message, result_message])
return "", chat_history
# 상담봇 - 되돌리기
def counseling_bot_undo(chat_history):
if len(chat_history) > 1:
chat_history.pop()
return chat_history
# 상담봇 - μ΄ˆκΈ°ν™”
def counseling_bot_reset(chat_history):
chat_history = [[None, "μ•ˆλ…•ν•˜μ„Έμš”, ν—€μ΄λ§ˆνŠΈμž…λ‹ˆλ‹€. 상담을 λ„μ™€λ“œλ¦¬κ² μŠ΅λ‹ˆλ‹€."]]
return chat_history
# λ²ˆμ—­λ΄‡
def translate_bot(output_conditions, output_language, input_text):
if input_text == "":
return ""
else:
if output_conditions == "":
output_conditions = ""
else:
output_conditions = "λ²ˆμ—­ν•  λ•Œμ˜ 쑰건은 λ‹€μŒκ³Ό κ°™μŠ΅λ‹ˆλ‹€. " + output_conditions
completion = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "당신은 λ²ˆμ—­κ°€μž…λ‹ˆλ‹€. μž…λ ₯ν•œ μ–Έμ–΄λ₯Ό λ‹€λ₯Έ μ„€λͺ…없이 κ³§λ°”λ‘œ {0}둜 λ²ˆμ—­ν•΄μ„œ μ•Œλ €μ£Όμ„Έμš”. λ²ˆμ—­μ΄ λΆˆκ°€λŠ₯ν•œ 언어라면 λ²ˆμ—­μ΄ λΆˆκ°€λŠ₯ν•˜λ‹€κ³  λ§ν•œ ν›„ κ·Έ 이유λ₯Ό μ„€λͺ…ν•΄μ£Όμ„Έμš”. {1}".format(output_language, output_conditions)},
{"role": "user", "content": input_text}
])
return completion.choices[0].message.content
# λ²ˆμ—­λ΄‡ - Textμ—…λ‘œλ“œ
def translate_bot_Text_upload(files):
loader = TextLoader(files)
document = loader.load()
return document[0].page_content
# λ²ˆμ—­λ΄‡ - PDFμ—…λ‘œλ“œ
def translate_bot_PDF_upload(files):
loader = PyPDFLoader(files)
pages = loader.load_and_split()
return pages[0].page_content
# μ†Œμ„€λ΄‡
def novel_bot(model, temperature, detail):
completion = client.chat.completions.create(
model=model,
temperature=temperature,
messages=[
{"role": "system", "content": "당신은 μ†Œμ„€κ°€μž…λ‹ˆλ‹€. μš”μ²­ν•˜λŠ” 쑰건에 맞좰 μ†Œμ„€μ„ μž‘μ„±ν•΄μ£Όμ„Έμš”."},
{"role": "user", "content": detail}
])
return completion.choices[0].message.content
# λ ˆμ΄μ•„μ›ƒ
with gr.Blocks(theme=gr.themes.Default()) as app:
with gr.Tab("상담봇"):
#1
gr.Markdown(
value="""
# <center>상담봇</center>
<center>ν—€μ΄λ§ˆνŠΈ 상담 λ΄‡μž…λ‹ˆλ‹€. λ§ˆνŠΈμ—μ„œ νŒλ§€ν•˜λŠ” μƒν’ˆκ³Ό κ΄€λ ¨λœ μ§ˆλ¬Έμ— λ‹΅λ³€λ“œλ¦½λ‹ˆλ‹€.</center>
""")
#2
cb_chatbot = gr.Chatbot(
value=[[None, "μ•ˆλ…•ν•˜μ„Έμš”, ν—€μ΄λ§ˆνŠΈμž…λ‹ˆλ‹€. 상담을 λ„μ™€λ“œλ¦¬κ² μŠ΅λ‹ˆλ‹€."]],
show_label=False
)
with gr.Row():
#3
cb_user_input = gr.Text(
lines=1,
placeholder="μž…λ ₯ μ°½",
container=False,
scale=9
)
#4
cb_send_btn = gr.Button(
value="보내기",
scale=1,
variant="primary",
icon="https://cdn-icons-png.flaticon.com/128/12439/12439334.png"
)
with gr.Row():
#5
gr.Button(value="↩️ 되돌리기").click(fn=counseling_bot_undo, inputs=cb_chatbot, outputs=cb_chatbot)
#6
gr.Button(value="πŸ”„οΈ μ΄ˆκΈ°ν™”").click(fn=counseling_bot_reset, inputs=cb_chatbot, outputs=cb_chatbot)
# 보내기1
cb_send_btn.click(fn=counseling_bot_chat, inputs=[cb_user_input, cb_chatbot], outputs=[cb_user_input, cb_chatbot])
# 보내기2
cb_user_input.submit(fn=counseling_bot_chat, inputs=[cb_user_input, cb_chatbot], outputs=[cb_user_input, cb_chatbot])
with gr.Tab("λ²ˆμ—­λ΄‡"):
#1
gr.Markdown(
value="""
# <center>λ²ˆμ—­λ΄‡</center>
<center>λ‹€κ΅­μ–΄ λ²ˆμ—­ λ΄‡μž…λ‹ˆλ‹€.</center>
""")
with gr.Row():
#2
tb_output_conditions = gr.Text(
label="λ²ˆμ—­ 쑰건",
placeholder="μ˜ˆμ‹œ: μžμ—°μŠ€λŸ½κ²Œ",
lines=1,
max_lines=3
)
#3
tb_output_language = gr.Dropdown(
label="좜λ ₯ μ–Έμ–΄",
choices=["ν•œκ΅­μ–΄", "μ˜μ–΄", "일본어", "쀑ꡭ어"],
value="ν•œκ΅­μ–΄",
allow_custom_value=True,
interactive=True
)
with gr.Row():
#7
tb_TXTupload = gr.UploadButton(label="πŸ“„ Txt μ—…λ‘œλ“œ")
#8
tb_PDFupload = gr.UploadButton(label="πŸ“€ PDF μ—…λ‘œλ“œ")
#4
tb_submit = gr.Button(
value="λ²ˆμ—­ν•˜κΈ°",
variant="primary"
)
with gr.Row():
#5
tb_input_text = gr.Text(
placeholder="λ²ˆμ—­ν•  λ‚΄μš©μ„ μ μ–΄μ£Όμ„Έμš”.",
lines=10,
max_lines=20,
show_copy_button=True,
label=""
)
#6
tb_output_text = gr.Text(
lines=10,
max_lines=20,
show_copy_button=True,
label="",
interactive=False
)
# 보내기
tb_submit.click(
fn=translate_bot,
inputs=[tb_output_conditions,
tb_output_language,
tb_input_text],
outputs=tb_output_text
)
# Text파일 μ—…λ‘œλ“œ
tb_TXTupload.upload(
fn=translate_bot_Text_upload,
inputs=tb_TXTupload,
outputs=tb_input_text
)
# PDF파일 μ—…λ‘œλ“œ
tb_PDFupload.upload(
fn=translate_bot_PDF_upload,
inputs=tb_PDFupload,
outputs=tb_input_text
)
with gr.Tab("μ†Œμ„€λ΄‡"):
#1
gr.Markdown(
value="""
# <center>μ†Œμ„€λ΄‡</center>
<center>μ†Œμ„€μ„ μƒμ„±ν•΄μ£ΌλŠ” λ΄‡μž…λ‹ˆλ‹€.</center>
""")
with gr.Accordion(label="μ‚¬μš©μž μ„€μ •"):
with gr.Row():
with gr.Column(scale=1):
#2
nb_model = gr.Dropdown(
label="λͺ¨λΈ 선택",
choices=["gpt-3.5-turbo", "gpt-3.5-turbo-16k", "gpt-4", "gpt-4-32k", "gpt-4-1106-preview"],
value="gpt-4-1106-preview",
interactive=True
)
#3
nb_temperature = gr.Slider(
label="μ°½μ˜μ„±",
info="μˆ«μžκ°€ 높을 수둝 창의적",
minimum=0,
maximum=2,
step=0.1,
value=1,
interactive=True
)
#4
nb_detail = gr.Text(
container=False,
placeholder="μ†Œμ„€μ˜ 세뢀적인 섀정을 μž‘μ„±ν•©λ‹ˆλ‹€.",
lines=8,
scale=4
)
#5
nb_submit = gr.Button(
value="μƒμ„±ν•˜κΈ°",
variant="primary"
)
#6
nb_output = gr.Text(
label="",
placeholder="이곳에 μ†Œμ„€μ˜ λ‚΄μš©μ΄ 좜λ ₯λ©λ‹ˆλ‹€.",
lines=10,
max_lines=200,
show_copy_button=True
)
# 보내기
nb_submit.click(
fn=novel_bot,
inputs=[nb_model, nb_temperature, nb_detail],
outputs=nb_output
)
app.launch()