dy2dx2 commited on
Commit
edc4821
1 Parent(s): e9951c3

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +70 -0
app.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from dotenv import load_dotenv
3
+ import openai
4
+ import gradio as gr
5
+
6
+ # Load environment variables from the .env file
7
+ load_dotenv()
8
+
9
+ openai.api_key = os.getenv("openai_api_key")
10
+ openai.organization = os.getenv("openai_organization_id")
11
+
12
+
13
+ message_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
+
16
+ def predict(input):
17
+ global message_history
18
+
19
+ message_history.append({"role": "user", "content": f"{input}"})
20
+
21
+ completion = openai.ChatCompletion.create(
22
+ model="gpt-4",
23
+ messages=message_history
24
+ )
25
+
26
+ reply_content = completion.choices[0].message.content
27
+
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 list
33
+ return response
34
+
35
+ def 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=q
43
+ )
44
+ label = res.choices[0].message.content.lower()
45
+ print(label)
46
+ if "yes" in label:
47
+ return True
48
+ return False
49
+
50
+
51
+
52
+ with 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
+
70
+ demo.launch()