File size: 1,962 Bytes
f60f8fd |
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 openai, random, time
import gradio as gr
openai.api_key = "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"
with open('prompt.txt') as f:
prompt = f.read()
messages = [
{"role": "system", "content": prompt},
]
with gr.Blocks() as demo:
chatbot = gr.Chatbot()
msg = gr.Textbox()
clear = gr.Button("Clear")
def user(user_message, history):
return "", history + [[user_message, None]]
def gpt_chatbot(input):
if input:
messages_with_formatting = []
for line in messages:
if line['role'] == "user":
messages_with_formatting.append({"role": "user", "content": "Them: " + line['content']})
if line['role'] == "assistant":
messages_with_formatting.append({"role": "assistant", "content": "You: " + line['content']})
if line['role'] == "system":
messages_with_formatting.append({"role": "system", "content": line['content']})
messages_with_formatting.append({"role": "user", "content": "Them: " + input})
chat = openai.ChatCompletion.create(
model="gpt-3.5-turbo", messages=messages_with_formatting
)
reply = chat.choices[0].message.content
# Remove the "You: " prefix from the assistant's response
if reply.startswith("You: "):
reply = reply[4:].strip()
return reply
def bot(history):
input = history[-1][0]
messages.append({"role": "user", "content": input})
bot_message = gpt_chatbot(input)
messages.append({"role": "assistant", "content": bot_message})
history[-1][1] = bot_message
return history
msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(
bot, chatbot, chatbot
)
clear.click(lambda: None, None, chatbot, queue=False)
demo.launch(share=True)
|