CoolFace
Apppublic

dy2dx2/Physics-Assistant

sourceHugging Faceupdated 3y agoView on Hugging Face
5likes
app.py70 linesDownload Raw Back to root
1import os2from dotenv import load_dotenv3import openai4import gradio as gr5 6# Load environment variables from the .env file7load_dotenv()8 9openai.api_key = os.getenv("openai_api_key")10openai.organization = os.getenv("openai_organization_id")11 12 13message_history = [{"role": "system", "content":"You are a physics assistant chatbot and reject to answer anything unrealted to the physics."}, 14                   {"role": "assistant", "content":"Hi, I am a physics assistant. I can help you with your physics questions."}]15 16def predict(input):17    global message_history18 19    message_history.append({"role": "user", "content": f"{input}"})20 21    completion = openai.ChatCompletion.create(22        model="gpt-4",23        messages=message_history24    )25 26    reply_content = completion.choices[0].message.content27 28    if check_in_role(reply_content):29        message_history.append({"role": "assistant", "content": f"{reply_content}"})30    else:31        message_history.append({"role": "assistant", "content": "I'm sorry, but the question you have asked seems to be unrelated to the context of this conversation, and unfortunately, I'm not able to provide an answer. If you have any questions related to physics, I would be happy to try and assist you."})32    response = [(message_history[i]["content"], message_history[i+1]["content"]) for i in range(2, len(message_history)-1, 2)]  # convert to tuples of list33    return response34 35def check_in_role(reply_content):36 37    p = "Is the following question related to physics? Answer it using only 'yes' or 'no'.\n\n" + reply_content + "\n\n---\nLabel:"38    q = [{"role": "user", "content":f"{p}"}]39 40    res = openai.ChatCompletion.create(41        model="gpt-4",42        messages=q43    )44    label = res.choices[0].message.content.lower()45    print(label)46    if "yes" in label:47        return True48    return False49 50 51 52with gr.Blocks(theme=gr.themes.Soft(), title="Physics Assistant") as demo:53    54    with gr.Row():55        gr.Markdown("Get instant physics help with our chatbot! Ask any physics-related questions and receive accurate and reliable answers in seconds. Perfect for students, researchers, and anyone interested in the laws of the universe.")56 57    bot = gr.Chatbot().style(height=500)58    59    with gr.Row():60        with gr.Column(scale=0.85):61            txt = gr.Textbox(62                show_label=False,63                placeholder="Enter a physics related text",64            ).style(container=False)65        with gr.Column(scale=0.15, min_width=0):66            send = gr.Button("Send")67 68    send.click(predict, inputs=[txt], outputs=bot)69 70demo.launch()