100xdemo / app.py
abhilashnl2006's picture
Update app.py
7847af5 verified
raw
history blame
1.93 kB
import gradio as gr
import openai
# Replace with your actual OpenAI API key
openai.api_key = "sk-proj-zVyjTUhcNh6MVzZpoHh3T3BlbkFJzsEfIBENz7WlbVIKv5tS"
def get_python_help(history):
try:
# Construct the messages from the history
messages = [{"role": "system", "content": "You are a helpful assistant that teaches Python programming. You always refer to the latest Python documentation when answering questions. If you're not sure about something, you say so and suggest checking the official documentation."}]
for h in history:
messages.append({"role": "user", "content": h[0]})
messages.append({"role": "assistant", "content": h[1]})
messages.append({"role": "user", "content": history[-1][0]})
# Generate a response using gpt-3.5-turbo
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=messages,
max_tokens=500,
n=1,
stop=None,
temperature=0.7,
stream=True
)
# Stream the response
reply = ""
for chunk in response:
reply += chunk['choices'][0]['delta'].get('content', '')
history[-1] = (history[-1][0], reply)
return history
except Exception as e:
return history + [("Error", str(e))]
# Create the Gradio interface
with gr.Blocks() as demo:
chatbot = gr.Chatbot()
state = gr.State([])
def respond(message, chat_history):
chat_history.append((message, None))
return "", get_python_help(chat_history)
with gr.Row():
with gr.Column():
user_input = gr.Textbox(
show_label=False,
placeholder="Type your message here...",
lines=1
)
user_input.submit(respond, [user_input, state], [user_input, chatbot, state])
# Launch the app
demo.launch()