rebornrulz
commited on
Commit
•
f091679
1
Parent(s):
c5d441e
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,203 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import os
|
3 |
+
import sys
|
4 |
+
import json
|
5 |
+
import requests
|
6 |
+
import random
|
7 |
+
|
8 |
+
|
9 |
+
MODEL = "o1-mini"
|
10 |
+
API_URL = os.getenv("API_URL")
|
11 |
+
DISABLED = os.getenv("DISABLED") == 'True'
|
12 |
+
OPENAI_API_KEYS = os.getenv("OPENAI_API_KEYS").split(',')
|
13 |
+
print (API_URL)
|
14 |
+
print (OPENAI_API_KEYS)
|
15 |
+
NUM_THREADS = int(os.getenv("NUM_THREADS"))
|
16 |
+
|
17 |
+
print (NUM_THREADS)
|
18 |
+
|
19 |
+
def exception_handler(exception_type, exception, traceback):
|
20 |
+
print("%s: %s" % (exception_type.__name__, exception))
|
21 |
+
sys.excepthook = exception_handler
|
22 |
+
sys.tracebacklimit = 0
|
23 |
+
|
24 |
+
#https://github.com/gradio-app/gradio/issues/3531#issuecomment-1484029099
|
25 |
+
def parse_codeblock(text):
|
26 |
+
lines = text.split("\n")
|
27 |
+
for i, line in enumerate(lines):
|
28 |
+
if "```" in line:
|
29 |
+
if line != "```":
|
30 |
+
lines[i] = f'<pre><code class="{lines[i][3:]}">'
|
31 |
+
else:
|
32 |
+
lines[i] = '</code></pre>'
|
33 |
+
else:
|
34 |
+
if i > 0:
|
35 |
+
lines[i] = "<br/>" + line.replace("<", "<").replace(">", ">")
|
36 |
+
return "".join(lines)
|
37 |
+
|
38 |
+
def predict(inputs, top_p, temperature, chat_counter, chatbot, history, request:gr.Request):
|
39 |
+
payload = {
|
40 |
+
"model": MODEL,
|
41 |
+
"messages": [{"role": "user", "content": f"{inputs}"}],
|
42 |
+
"temperature" : 1.0,
|
43 |
+
"top_p":1.0,
|
44 |
+
"n" : 1,
|
45 |
+
"stream": True,
|
46 |
+
"presence_penalty":0,
|
47 |
+
"frequency_penalty":0,
|
48 |
+
}
|
49 |
+
OPENAI_API_KEY = random.choice(OPENAI_API_KEYS)
|
50 |
+
print (OPENAI_API_KEY)
|
51 |
+
headers_dict = {key.decode('utf-8'): value.decode('utf-8') for key, value in request.headers.raw}
|
52 |
+
headers = {
|
53 |
+
"Content-Type": "application/json",
|
54 |
+
"Authorization": f"Bearer {OPENAI_API_KEY}",
|
55 |
+
"Headers": f"{headers_dict}"
|
56 |
+
}
|
57 |
+
|
58 |
+
# print(f"chat_counter - {chat_counter}")
|
59 |
+
if chat_counter != 0 :
|
60 |
+
messages = []
|
61 |
+
for i, data in enumerate(history):
|
62 |
+
if i % 2 == 0:
|
63 |
+
role = 'user'
|
64 |
+
else:
|
65 |
+
role = 'assistant'
|
66 |
+
message = {}
|
67 |
+
message["role"] = role
|
68 |
+
message["content"] = data
|
69 |
+
messages.append(message)
|
70 |
+
|
71 |
+
message = {}
|
72 |
+
message["role"] = "user"
|
73 |
+
message["content"] = inputs
|
74 |
+
messages.append(message)
|
75 |
+
payload = {
|
76 |
+
"model": MODEL,
|
77 |
+
"messages": messages,
|
78 |
+
"temperature" : temperature,
|
79 |
+
"top_p": top_p,
|
80 |
+
"n" : 1,
|
81 |
+
"stream": True,
|
82 |
+
"presence_penalty":0,
|
83 |
+
"frequency_penalty":0,
|
84 |
+
}
|
85 |
+
|
86 |
+
chat_counter += 1
|
87 |
+
|
88 |
+
history.append(inputs)
|
89 |
+
token_counter = 0
|
90 |
+
partial_words = ""
|
91 |
+
counter = 0
|
92 |
+
|
93 |
+
try:
|
94 |
+
# make a POST request to the API endpoint using the requests.post method, passing in stream=True
|
95 |
+
response = requests.post(API_URL, headers=headers, json=payload, stream=True)
|
96 |
+
response_code = f"{response}"
|
97 |
+
#if response_code.strip() != "<Response [200]>":
|
98 |
+
# #print(f"response code - {response}")
|
99 |
+
# raise Exception(f"Sorry, hitting rate limit. Please try again later. {response}")
|
100 |
+
|
101 |
+
for chunk in response.iter_lines():
|
102 |
+
print (chunk)
|
103 |
+
sys.stdout.flush()
|
104 |
+
#Skipping first chunk
|
105 |
+
if counter == 0:
|
106 |
+
counter += 1
|
107 |
+
continue
|
108 |
+
#counter+=1
|
109 |
+
# check whether each line is non-empty
|
110 |
+
if chunk.decode() :
|
111 |
+
chunk = chunk.decode()
|
112 |
+
# decode each line as response data is in bytes
|
113 |
+
if len(chunk) > 12 and "content" in json.loads(chunk[6:])['choices'][0]['delta']:
|
114 |
+
partial_words = partial_words + json.loads(chunk[6:])['choices'][0]["delta"]["content"]
|
115 |
+
if token_counter == 0:
|
116 |
+
history.append(" " + partial_words)
|
117 |
+
else:
|
118 |
+
history[-1] = partial_words
|
119 |
+
token_counter += 1
|
120 |
+
yield [(parse_codeblock(history[i]), parse_codeblock(history[i + 1])) for i in range(0, len(history) - 1, 2) ], history, chat_counter, response, gr.update(interactive=False), gr.update(interactive=False) # resembles {chatbot: chat, state: history}
|
121 |
+
except Exception as e:
|
122 |
+
print (f'error found: {e}')
|
123 |
+
yield [(parse_codeblock(history[i]), parse_codeblock(history[i + 1])) for i in range(0, len(history) - 1, 2) ], history, chat_counter, response, gr.update(interactive=True), gr.update(interactive=True)
|
124 |
+
print(json.dumps({"chat_counter": chat_counter, "payload": payload, "partial_words": partial_words, "token_counter": token_counter, "counter": counter}))
|
125 |
+
|
126 |
+
|
127 |
+
def reset_textbox():
|
128 |
+
return gr.update(value='', interactive=False), gr.update(interactive=False)
|
129 |
+
|
130 |
+
title = """<h1 align="center">OpenAI-O1-Mini: Research Preview (Short-Term Availability)</h1>"""
|
131 |
+
if DISABLED:
|
132 |
+
title = """<h1 align="center" style="color:red">This app has reached OpenAI's usage limit. Please check back tomorrow.</h1>"""
|
133 |
+
description = """Language models can be conditioned to act like dialogue agents through a conversational prompt that typically takes the form:
|
134 |
+
```
|
135 |
+
User: <utterance>
|
136 |
+
Assistant: <utterance>
|
137 |
+
User: <utterance>
|
138 |
+
Assistant: <utterance>
|
139 |
+
...
|
140 |
+
```
|
141 |
+
In this app, you can explore the outputs of a gpt-4 turbo LLM.
|
142 |
+
"""
|
143 |
+
|
144 |
+
theme = gr.themes.Default(primary_hue="green")
|
145 |
+
|
146 |
+
with gr.Blocks(css = """#col_container { margin-left: auto; margin-right: auto;}
|
147 |
+
#chatbot {height: 520px; overflow: auto;}""",
|
148 |
+
theme=theme) as demo:
|
149 |
+
gr.HTML(title)
|
150 |
+
gr.HTML("""<h3 align="center" style="color: red;">If this app doesn't respond, consider trying our GPT-4o app:<br/><a href="https://huggingface.co/spaces/yuntian-deng/ChatGPT4">https://huggingface.co/spaces/yuntian-deng/ChatGPT4</a></h3>""")
|
151 |
+
|
152 |
+
#gr.HTML('''<center><a href="https://huggingface.co/spaces/ysharma/ChatGPT4?duplicate=true"><img src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a>Duplicate the Space and run securely with your OpenAI API Key</center>''')
|
153 |
+
with gr.Column(elem_id = "col_container", visible=False) as main_block:
|
154 |
+
#GPT4 API Key is provided by Huggingface
|
155 |
+
#openai_api_key = gr.Textbox(type='password', label="Enter only your GPT4 OpenAI API key here")
|
156 |
+
chatbot = gr.Chatbot(elem_id='chatbot') #c
|
157 |
+
inputs = gr.Textbox(placeholder= "Hi there!", label= "Type an input and press Enter") #t
|
158 |
+
state = gr.State([]) #s
|
159 |
+
with gr.Row():
|
160 |
+
with gr.Column(scale=7):
|
161 |
+
b1 = gr.Button(visible=not DISABLED) #.style(full_width=True)
|
162 |
+
with gr.Column(scale=3):
|
163 |
+
server_status_code = gr.Textbox(label="Status code from OpenAI server", )
|
164 |
+
|
165 |
+
#inputs, top_p, temperature, top_k, repetition_penalty
|
166 |
+
with gr.Accordion("Parameters", open=False):
|
167 |
+
top_p = gr.Slider( minimum=-0, maximum=1.0, value=1.0, step=0.05, interactive=True, label="Top-p (nucleus sampling)",)
|
168 |
+
temperature = gr.Slider( minimum=-0, maximum=5.0, value=1.0, step=0.1, interactive=True, label="Temperature",)
|
169 |
+
#top_k = gr.Slider( minimum=1, maximum=50, value=4, step=1, interactive=True, label="Top-k",)
|
170 |
+
#repetition_penalty = gr.Slider( minimum=0.1, maximum=3.0, value=1.03, step=0.01, interactive=True, label="Repetition Penalty", )
|
171 |
+
chat_counter = gr.Number(value=0, visible=False, precision=0)
|
172 |
+
|
173 |
+
with gr.Column(elem_id = "user_consent_container") as user_consent_block:
|
174 |
+
# Get user consent
|
175 |
+
accept_checkbox = gr.Checkbox(visible=False)
|
176 |
+
js = "(x) => confirm('By clicking \"OK\", I agree that my data may be published or shared.')"
|
177 |
+
with gr.Accordion("User Consent for Data Collection, Use, and Sharing", open=True):
|
178 |
+
gr.HTML("""
|
179 |
+
<div>
|
180 |
+
<p>By using our app, which is powered by OpenAI's API, you acknowledge and agree to the following terms regarding the data you provide:</p>
|
181 |
+
<ol>
|
182 |
+
<li><strong>Collection:</strong> We may collect information, including the inputs you type into our app, the outputs generated by OpenAI's API, and certain technical details about your device and connection (such as browser type, operating system, and IP address) provided by your device's request headers.</li>
|
183 |
+
<li><strong>Use:</strong> We may use the collected data for research purposes, to improve our services, and to develop new products or services, including commercial applications, and for security purposes, such as protecting against unauthorized access and attacks.</li>
|
184 |
+
<li><strong>Sharing and Publication:</strong> Your data, including the technical details collected from your device's request headers, may be published, shared with third parties, or used for analysis and reporting purposes.</li>
|
185 |
+
<li><strong>Data Retention:</strong> We may retain your data, including the technical details collected from your device's request headers, for as long as necessary.</li>
|
186 |
+
</ol>
|
187 |
+
<p>By continuing to use our app, you provide your explicit consent to the collection, use, and potential sharing of your data as described above. If you do not agree with our data collection, use, and sharing practices, please do not use our app.</p>
|
188 |
+
</div>
|
189 |
+
""")
|
190 |
+
accept_button = gr.Button("I Agree")
|
191 |
+
|
192 |
+
def enable_inputs():
|
193 |
+
return gr.update(visible=False), gr.update(visible=True)
|
194 |
+
|
195 |
+
accept_button.click(None, None, accept_checkbox, js=js, queue=False)
|
196 |
+
accept_checkbox.change(fn=enable_inputs, inputs=[], outputs=[user_consent_block, main_block], queue=False)
|
197 |
+
|
198 |
+
inputs.submit(reset_textbox, [], [inputs, b1], queue=False)
|
199 |
+
inputs.submit(predict, [inputs, top_p, temperature, chat_counter, chatbot, state], [chatbot, state, chat_counter, server_status_code, inputs, b1],) #openai_api_key
|
200 |
+
b1.click(reset_textbox, [], [inputs, b1], queue=False)
|
201 |
+
b1.click(predict, [inputs, top_p, temperature, chat_counter, chatbot, state], [chatbot, state, chat_counter, server_status_code, inputs, b1],) #openai_api_key
|
202 |
+
|
203 |
+
demo.queue(max_size=10, default_concurrency_limit=NUM_THREADS, api_open=False).launch(share=False)
|