|
import gradio as gr |
|
from openai import OpenAI |
|
import random |
|
import time |
|
import datetime |
|
import os |
|
|
|
|
|
if __name__ == '__main__': |
|
|
|
|
|
client = OpenAI(api_key=os.environ['API']) |
|
|
|
system_message = {"role": "system", "content": "You are ChatGPT, a large language model trained by OpenAI. Your answer should be as detailed as possible."} |
|
|
|
with gr.Blocks(css="footer {visibility: hidden}", title = 'Hello, Yoda.') as demo: |
|
gr.Markdown("""<h1><center>Hello, Yoda.</center></h1>""") |
|
chatbot = gr.Chatbot() |
|
msg = gr.Textbox(show_label=False, placeholder="Ask me a question and press enter.") |
|
btn=gr.Button("submit") |
|
clear = gr.Button("clear") |
|
|
|
|
|
state = gr.State([]) |
|
|
|
def user(user_message, history): |
|
return "", history + [[user_message, None]] |
|
|
|
def bot(history, messages_history, model_name = 'gpt-4o'): |
|
user_message = history[-1][0] |
|
now = datetime.datetime.now() |
|
if now.year == 2024 and now.month == 2: |
|
bot_message, messages_history = ask_gpt(user_message, messages_history, 'gpt-3.5-turbo-0125') |
|
else: |
|
bot_message, messages_history = ask_gpt(user_message, messages_history, model_name) |
|
messages_history += [{"role": "assistant", "content": bot_message}] |
|
history[-1][1] = bot_message |
|
time.sleep(1) |
|
return history, messages_history |
|
|
|
def ask_gpt(message, messages_history, model_name): |
|
if len(messages_history) == 0: |
|
messages_history = [system_message] |
|
messages_history += [{"role": "user", "content": message}] |
|
response = client.chat.completions.create( |
|
model=model_name, |
|
|
|
|
|
messages=messages_history |
|
) |
|
|
|
return response.choices[0].message.content, messages_history |
|
|
|
def init_history(messages_history): |
|
messages_history = [] |
|
messages_history += [system_message] |
|
return messages_history |
|
|
|
msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then( |
|
bot, [chatbot, state], [chatbot, state] |
|
) |
|
|
|
btn.click(user, [msg, chatbot], [msg, chatbot], queue=False).then( |
|
bot, [chatbot, state], [chatbot, state] |
|
) |
|
|
|
clear.click(lambda: None, None, chatbot, queue=False).success(init_history, [state], [state]) |
|
|
|
demo.launch(share = False, show_api = False, auth = (os.environ['ID'], os.environ['PWD'])) |
|
|
|
|