HTMLify

Chatgpt.py
Views: 235 | Author: amar
import gradio as gr
import openai
from kivy.core.clipboard import Clipboard

prompt = "Send a message"
    
def chat(prompt, apiKey, model):
    error_message = ""
    try:    
        response = openai.ChatCompletion.create(
          model = model,
          api_key = apiKey,
          messages = [{'role': 'user', 'content': prompt}],
          temperature = 0.7  
        )
        
    except Exception as e:
        error_message = str(e)

    if error_message:
        return "An error occurred: {}".format(error_message)
    else:
        return response['choices'][0]['message']['content']
        

def chatGPT(userMsg, history, modelType, apiKey):
    history = history or []
    comb = list(sum(history, ()))
    comb.append(userMsg)
    prompt = ' '.join(comb)
    output = chat(prompt, apiKey, modelType)
    history.append((userMsg, output))
    return history, history
    
def lastReply(history):
    if history is None:
        result = ""
    else:    
        result = history[-1][1]
        Clipboard.copy(result)
    return result

with gr.Blocks(theme=gr.themes.Monochrome(), css="pre {background: #f6f6f6} #submit {background-color: #fcf5ef; color: #c88f58;} #stop, #clear, #copy {max-width: 165px;} #myrow {justify-content: center;}") as demo:
    gr.Markdown("""<center><h1>🚀 ChatGPT</h1></center>""")
    with gr.Row():
        with gr.Column(scale=0.5):
            modelType = gr.Dropdown(choices=["gpt-3.5-turbo", "gpt-4"], value="gpt-3.5-turbo", label="Model", info="Select your model type" )
        with gr.Column(scale=0.5, min_width=0):            
            apiKey = gr.Textbox(label="API Key", info="Enter API Key", lines=1, placeholder="sk-xxxxxxxxxxx")
    chatbot = gr.Chatbot().style(height=250)
    state = gr.State()
    with gr.Row():
        with gr.Column(scale=0.85):
            msg = gr.Textbox(show_label=False, placeholder=prompt).style(container=False)
        with gr.Column(scale=0.15, min_width=0):
            submit = gr.Button("Submit", elem_id="submit")
    with gr.Row(elem_id="myrow"):
        stop = gr.Button("🛑 Stop", elem_id="stop")        
        clear = gr.Button("🗑️ Clear History", elem_id="clear")
        copy = gr.Button("📋 Copy last reply", elem_id="copy")
    clear.click(lambda: (None, None, None), None, outputs=[chatbot, state, msg], queue=False)        
    submit_event = submit.click(chatGPT, inputs=[msg, state, modelType, apiKey], outputs=[chatbot, state])
    submit2_event = msg.submit(chatGPT, inputs=[msg, state, modelType, apiKey], outputs=[chatbot, state])
    stop.click(None, None, None, cancels=[submit_event, submit2_event])
    copy.click(lastReply, inputs=[state], outputs=None)

demo.queue().launch(inbrowser=True, debug=True)

Comments