| | import gradio as gr |
| | import openai |
| | import time |
| |
|
| | with gr.Blocks() as demo: |
| | with gr.Row(): |
| | key = gr.Textbox(placeholder="API_KEY") |
| | with gr.Row(): |
| | with gr.Column(): |
| | msg = gr.Textbox(placeholder="Question") |
| | submit = gr.Button("Submit") |
| | clear = gr.Button("Clear") |
| | with gr.Column(): |
| | chatbot = gr.Chatbot() |
| |
|
| |
|
| | |
| |
|
| | def user(user_message, history): |
| | return "", history + [[user_message, None]] |
| |
|
| |
|
| | def bot(history, key): |
| | openai.api_key = key |
| | bot_message = ask_gpt(history) |
| | print(history) |
| | history[-1][1] = bot_message |
| | time.sleep(1) |
| | return history |
| |
|
| |
|
| | def ask_gpt(history): |
| | messages = [] |
| | for i in range(len(history) - 1): |
| | messages.append({"role": "user", "content": history[i][0]}) |
| | messages.append({"role": "assistant", "content": history[i][1]}) |
| | messages.append({"role": "user", "content": history[-1][0]}) |
| | try: |
| | response = openai.ChatCompletion.create( |
| | model="gpt-3.5-turbo", |
| | messages=messages |
| | ) |
| | return response['choices'][0]['message']['content'].replace("```", "") |
| | except Exception as e: |
| | print(e) |
| | return e |
| |
|
| |
|
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| |
|
| | |
| | |
| | |
| |
|
| | submit.click(user, inputs=[msg, chatbot], outputs=[msg, chatbot], queue=True, api_name="submit").then( |
| | bot, [chatbot, key], chatbot, api_name="bot_response" |
| | ) |
| | clear.click(lambda: None, None, chatbot, queue=True, api_name="clear") |
| |
|
| | |
| |
|
| | demo.queue() |
| | demo.launch() |
| |
|