|
from dotenv import load_dotenv |
|
|
|
load_dotenv() |
|
import gradio as gr |
|
import openai |
|
|
|
|
|
def get_ai_reply(message, model="gpt-3.5-turbo", system_message=None, temperature=0, message_history=[]): |
|
|
|
messages = [] |
|
|
|
|
|
if system_message is not None: |
|
messages += [{"role": "system", "content": system_message}] |
|
|
|
|
|
if message_history is not None: |
|
messages += message_history |
|
|
|
|
|
messages += [{"role": "user", "content": message}] |
|
|
|
|
|
completion = openai.ChatCompletion.create( |
|
model=model, |
|
messages=messages, |
|
temperature=temperature |
|
) |
|
|
|
|
|
return completion.choices[0].message.content.strip() |
|
|
|
|
|
def chat(message, chatbot_messages, history_state): |
|
|
|
chatbot_messages = chatbot_messages or [] |
|
history_state = history_state or [] |
|
|
|
|
|
try: |
|
prompt = """ |
|
You are bot created to simulate the commands as a human only when the phrase "Simon says" is used. When simulating a command make sure to use the notation given below and respond with the appropriate action. |
|
If the phrase is not used then Simulate doing nothing. |
|
|
|
Simulate doing a command using this notation: |
|
:: <command> :: |
|
|
|
Simulate doing nothing with this notation: |
|
:: does nothing :: |
|
""" |
|
ai_reply = get_ai_reply(message, model="gpt-3.5-turbo", system_message=prompt.strip(), message_history=history_state) |
|
|
|
|
|
chatbot_messages.append((message, ai_reply)) |
|
|
|
|
|
history_state.append({"role": "user", "content": message}) |
|
history_state.append({"role": "assistant", "content": ai_reply}) |
|
|
|
|
|
except Exception as e: |
|
|
|
raise gr.Error(e) |
|
|
|
return None, chatbot_messages, history_state |
|
|
|
|
|
def get_chatbot_app(): |
|
|
|
with gr.Blocks() as app: |
|
|
|
chatbot = gr.Chatbot(label="Conversation") |
|
|
|
message = gr.Textbox(label="Message") |
|
|
|
history_state = gr.State() |
|
|
|
btn = gr.Button(value="Send") |
|
|
|
|
|
btn.click(chat, inputs=[message, chatbot, history_state], outputs=[message, chatbot, history_state]) |
|
|
|
return app |
|
|
|
|
|
app = get_chatbot_app() |
|
app.queue() |
|
app.launch() |
|
|