import os import gradio as gr import random import time from pydantic import BaseModel import openai openai.api_key = os.environ["apikey"] def chatgpt(input, chat_history): try: messages = [] for message, bot_message in chat_history: messages.append({"role": "user", "content": message}) messages.append({"role": "assistant", "content": bot_message}) prompt = {"role": "user", "content": input} messages.append(prompt) result = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages=messages) output = result.get('choices')[0].get('message').get('content') except Exception as e: output = str(e) return output with gr.Blocks() as demo: chatbot = gr.Chatbot() msg = gr.Textbox() clear = gr.Button("Clear") def respond(message, chat_history): # bot_message = random.choice(["How are you?", "I love you", "I'm very hungry"]) bot_message = chatgpt(message, chat_history) chat_history.append((message, bot_message)) time.sleep(1) return "", chat_history msg.submit(respond, [msg, chatbot], [msg, chatbot]) clear.click(lambda: None, None, chatbot, queue=False) demo.launch(server_name='0.0.0.0')