Nadaal commited on
Commit
b48c51f
1 Parent(s): 149efb3

Upload 3 files

Browse files
Files changed (3) hide show
  1. app.py +135 -0
  2. promptsvocaba.csv +0 -0
  3. requirements.txt +1 -0
app.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import openai
4
+ import subprocess
5
+ import requests
6
+ import json
7
+ import csv
8
+ import os
9
+ import re
10
+
11
+ def get_openai_api_key():
12
+ url = "https://neuroclubs.com/api/config.py"
13
+ response = requests.get(url)
14
+
15
+ if response.status_code == 200:
16
+ config_content = response.text
17
+ api_key_match = re.search(r'OPENAI_API_KEY\s*=\s*[\'"](.+?)[\'"]', config_content)
18
+ if api_key_match:
19
+ return api_key_match.group(1)
20
+ else:
21
+ raise Exception("Failed to extract OPENAI_API_KEY from config.py content")
22
+ else:
23
+ raise Exception("Failed to fetch config.py from remote server")
24
+
25
+ openai.api_key = get_openai_api_key()
26
+
27
+ prompt_templates = {"Default": ""}
28
+
29
+ def get_empty_state():
30
+ return {"total_tokens": 0, "messages": []}
31
+
32
+ def download_prompt_templates():
33
+ with open('promptsvocaba.csv', newline='') as csvfile:
34
+ reader = csv.reader(csvfile, delimiter=',', quotechar='"')
35
+ next(reader) # skip header row
36
+ for row in reader:
37
+ act, prompt = row
38
+ prompt_templates[act] = prompt
39
+
40
+ choices = list(prompt_templates.keys())
41
+ return gr.update(value=choices[0], choices=choices)
42
+
43
+ def on_token_change(user_token):
44
+ openai.api_key = config.OPENAI_API_KEY
45
+
46
+ def on_prompt_template_change(prompt_template):
47
+ if not isinstance(prompt_template, str): return
48
+ return prompt_templates[prompt_template]
49
+
50
+ def submit_message(user_token, prompt, prompt_template, temperature, max_tokens, state):
51
+
52
+ history = state['messages']
53
+
54
+ if not prompt:
55
+ return gr.update(value='', visible=state['total_tokens'] < 1_000), [(history[i]['content'], history[i+1]['content']) for i in range(0, len(history)-1, 2)], f"Total tokens used: {state['total_tokens']} / 3000", state
56
+
57
+ prompt_template = prompt_templates[prompt_template]
58
+
59
+ system_prompt = []
60
+ if prompt_template:
61
+ system_prompt = [{ "role": "system", "content": prompt_template }]
62
+
63
+ prompt_msg = { "role": "user", "content": prompt }
64
+
65
+ try:
66
+ completion = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages=system_prompt + history + [prompt_msg], temperature=temperature, max_tokens=max_tokens)
67
+
68
+ history.append(prompt_msg)
69
+ history.append(completion.choices[0].message.to_dict())
70
+
71
+ state['total_tokens'] += completion['usage']['total_tokens']
72
+
73
+ except Exception as e:
74
+ history.append(prompt_msg)
75
+ history.append({
76
+ "role": "system",
77
+ "content": f"Error: {e}"
78
+ })
79
+
80
+ total_tokens_used_msg = f"Total tokens used: {state['total_tokens']} / 3000" if not user_token else ""
81
+ chat_messages = [(history[i]['content'], history[i+1]['content']) for i in range(0, len(history)-1, 2)]
82
+ input_visibility = user_token or state['total_tokens'] < 3000
83
+
84
+ return gr.update(value='', visible=input_visibility), chat_messages, total_tokens_used_msg, state
85
+
86
+ def clear_conversation():
87
+ return gr.update(value=None, visible=True), None, "", get_empty_state()
88
+
89
+ css = """
90
+ #col-container {max-width: 80%; margin-left: auto; margin-right: auto;}
91
+ #option-box {min-height: 250px; border-width: 2px; border-style: solid; border-color: #0000ff; border-radius: 4px;}
92
+ #text-box {min-height: 70px; border-width: 2px; border-style: solid; border-color: #ff0000; border-radius: 4px;}
93
+ #chatbox {min-height: 800px; border-width: 2px; border-style: solid; border-color: #008000; border-radius: 4px;}
94
+ #header {text-align: center;}
95
+ #prompt_template_preview {min-height: 250px; padding: 1em; border-width: 2px; border-style: solid; border-color: #23238E; border-radius: 4px;}
96
+ #total_tokens_str {text-align: right; font-size: 0.8em; color: #666; height: 1em;}
97
+ #clear-box {border-width: 2px; border-style: solid; border-color: #00ff00; border-radius: 4px;}
98
+ .message { font-size: 1.2em; }
99
+ """
100
+
101
+ with gr.Blocks(css=css) as demo:
102
+
103
+ state = gr.State(get_empty_state())
104
+
105
+ with gr.Column(elem_id="option-box"):
106
+ prompt_template = gr.Dropdown(label="Choose your prompt:", choices=list(prompt_templates.keys()))
107
+ prompt_template_preview = gr.Markdown(elem_id="prompt_template_preview", visible=False)
108
+ user_token = gr.Textbox(placeholder="OpenAI API Key", type="password", show_label=False, visible=False)
109
+ with gr.Accordion("Advanced parameters", open=False, visible=False):
110
+ temperature = gr.Slider(value=0.5, top_p=1, frequency_penalty=0, presence_penalty=0.6, interactive=False, label="Temperature")
111
+ max_tokens = gr.Slider(value=3000, interactive=False, label="Max tokens per response")
112
+
113
+ with gr.Column(elem_id="text-box"):
114
+ input_message = gr.Textbox(show_label=False, placeholder="Enter text and press enter", visible=True).style(container=True)
115
+ btn_submit = gr.Button("Submit")
116
+
117
+ with gr.Column(elem_id="chatbox"):
118
+ chatbot = gr.Chatbot(elem_id="AI")
119
+ total_tokens_str = gr.Markdown(elem_id="total_tokens_str")
120
+
121
+ with gr.Column(elem_id="clear-box"):
122
+ btn_clear_conversation = gr.Button("🔃 Start New Conversation")
123
+
124
+
125
+ btn_submit.click(submit_message, [user_token, input_message, prompt_template, temperature, max_tokens, state], [input_message, chatbot, total_tokens_str, state])
126
+ input_message.submit(submit_message, [user_token, input_message, prompt_template, temperature, max_tokens, state], [input_message, chatbot, total_tokens_str, state])
127
+ btn_clear_conversation.click(clear_conversation, [], [input_message, chatbot, total_tokens_str, state])
128
+ prompt_template.change(on_prompt_template_change, inputs=[prompt_template], outputs=[prompt_template_preview])
129
+ user_token.change(on_token_change, inputs=[user_token], outputs=[])
130
+
131
+
132
+ demo.load(download_prompt_templates, inputs=None, outputs=[prompt_template])
133
+
134
+
135
+ demo.launch(debug=True)
promptsvocaba.csv ADDED
The diff for this file is too large to render. See raw diff
 
requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ openai==0.27.0