TomatoFull commited on
Commit
d86c93b
1 Parent(s): 194c606

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +441 -37
app.py CHANGED
@@ -1,23 +1,165 @@
1
- from starlette.responses import HTMLResponse
 
 
 
2
  from fastapi import FastAPI, Request
3
- from typing import List
4
  import gradio as gr
 
5
  import requests
6
  import argparse
7
  import aiohttp
8
  import uvicorn
9
  import random
10
  import string
 
11
  import json
 
12
  import math
13
  import sys
14
  import os
15
 
16
- API_BASE = "env"
17
- api_key = os.environ['API_KEY']
 
 
 
 
18
  oai_api_key = os.environ['OPENAI_API_KEY']
19
  base_url = os.environ.get('OPENAI_BASE_URL', "https://api.openai.com/v1")
20
- def_models = '["gpt-4", "gpt-4-0125-preview", "gpt-4-0613", "gpt-4-1106-preview", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-turbo-preview", "chatgpt-4o-latest", "gpt-4o", "gpt-4o-2024-05-13", "gpt-4o-2024-08-06", "gpt-4o-mini", "gpt-4o-mini-2024-07-18"]'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
  def checkModels():
23
  global base_url
@@ -36,9 +178,13 @@ def checkModels():
36
 
37
  def loadModels():
38
  global models, modelList
39
- models = json.loads(def_models)
 
 
 
 
40
  models = sorted(models)
41
-
42
  modelList = {
43
  "object": "list",
44
  "data": [{"id": v, "object": "model", "created": 0, "owned_by": "system"} for v in models]
@@ -68,15 +214,15 @@ def handleApiKeys():
68
  except Exception as e:
69
  raise RuntimeError(f"Current API key is not valid or an actual error happened: {e}")
70
 
71
- def encodeChat(messages):
72
- output = []
73
- for message in messages:
74
- role = message['role']
75
- name = f" [{message['name']}]" if 'name' in message else ''
76
- content = message['content']
77
- formatted_message = f"<|im_start|>{role}{name}\n{content}<|end_of_text|>"
78
- output.append(formatted_message)
79
- return "\n".join(output)
80
 
81
  def get_api_key(call='api_key'):
82
  if call == 'api_key':
@@ -90,6 +236,16 @@ def get_api_key(call='api_key'):
90
  return random.choice(key.split(','))
91
  return key
92
 
 
 
 
 
 
 
 
 
 
 
93
  def moderate(messages):
94
  try:
95
  response = requests.post(
@@ -125,10 +281,36 @@ def moderate(messages):
125
  except KeyError:
126
  if moderation_result["flagged"]:
127
  return moderation_result
128
-
129
  return False
130
 
131
  async def streamChat(params):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
  async with aiohttp.ClientSession() as session:
133
  try:
134
  async with session.post(f"{base_url}/chat/completions", headers={"Authorization": f"Bearer {get_api_key(call='api_key')}", "Content-Type": "application/json"}, json=params) as r:
@@ -164,31 +346,187 @@ async def streamChat(params):
164
  except aiohttp.ClientError:
165
  return
166
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
167
  def rnd(length=8):
168
  letters = string.ascii_letters + string.digits
169
  return ''.join(random.choice(letters) for i in range(length))
170
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
171
 
172
  async def respond(
173
  message,
174
- history: list[tuple[str, str]],
 
 
 
 
175
  model_name,
176
  max_tokens,
177
  temperature,
178
  top_p,
 
 
 
 
 
 
179
  ):
180
  messages = [];
 
 
 
 
 
 
 
 
 
 
181
 
182
  for val in history:
183
- if val[0]:
184
- messages.append({"role": "user", "content": val[0]})
185
- if val[1]:
186
- messages.append({"role": "assistant", "content": val[1]})
187
-
188
- messages.append({"role": "user", "content": message})
 
 
189
 
190
  if message:
191
- mode = moderate(messages)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
192
  if mode:
193
  reasons = []
194
  categories = mode[0].get('categories', {}) if isinstance(mode, list) else mode.get('categories', {})
@@ -200,31 +538,95 @@ async def respond(
200
  else:
201
  yield "[MODERATION] I'm sorry, but I can't assist with that."
202
  return
203
-
204
- response = ""
205
- async for token in streamChat({
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
206
  "model": model_name,
207
  "messages": messages,
208
  "max_tokens": max_tokens,
209
  "temperature": temperature,
210
  "top_p": top_p,
 
211
  "user": rnd(),
212
  "stream": True
213
- }):
214
- response += token['choices'][0]['delta'].get("content", token['choices'][0]['delta'].get("refusal", ""))
215
- yield response
216
-
217
 
218
- handleApiKeys();loadModels();checkModels();
 
219
  demo = gr.ChatInterface(
220
  respond,
221
  title="gpt-4o-mini",
222
- description=f"This is the smaller version of quardo/gpt-4o-mini space. Mainly exists when the main space is down. (Status: the main space is offline cause it is stuck on 'Building' stage)",
 
223
  additional_inputs=[
 
224
  gr.Dropdown(choices=models, value="gpt-4o-mini", label="Model"),
225
  gr.Slider(minimum=1, maximum=4096, value=4096, step=1, label="Max new tokens"),
226
  gr.Slider(minimum=0.1, maximum=2.0, value=0.7, step=0.05, label="Temperature"),
227
  gr.Slider(minimum=0.05, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)"),
 
 
 
 
 
 
228
  ],
229
  css="footer{display:none !important}",
230
  head="""<script>if(!confirm("By using our application, which integrates with OpenAI's API, you acknowledge and agree to the following terms regarding the data you provide:\\n\\n1. Data Collection: This application may log the following data through the Gradio endpoint or the API endpoint: message requests (including messages, responses, model settings, and images sent along with the messages), images that were generated (including only the prompt and the image), search tool calls (including query, search results, summaries, and output responses), and moderation checks (including input and output).\\n2. Data Retention and Removal: Data is retained until further notice or until a specific request for removal is made.\\n3. Data Usage: The collected data may be used for various purposes, including but not limited to, administrative review of logs, AI training, and publication as a dataset.\\n4. Privacy: Please avoid sharing any personal information.\\n\\nBy continuing to use our application, you explicitly consent to the collection, use, and potential sharing of your data as described above. If you disagree with our data collection, usage, and sharing practices, we advise you not to use our application."))location.href="/declined";</script>"""
@@ -246,6 +648,10 @@ def test():
246
  </html>
247
  """)
248
 
 
 
 
 
249
  app = gr.mount_gradio_app(app, demo, path="/")
250
 
251
  class ArgParser(argparse.ArgumentParser):
@@ -263,6 +669,4 @@ if __name__ == "__main__":
263
  if args.dev:
264
  uvicorn.run("__main__:app", host=args.server, port=args.port, reload=True)
265
  else:
266
- uvicorn.run("__main__:app", host=args.server, port=args.port, reload=False)
267
-
268
-
 
1
+ from starlette.responses import JSONResponse, FileResponse, HTMLResponse
2
+ from gradio.data_classes import FileData, GradioModel
3
+ from sse_starlette.sse import EventSourceResponse
4
+ from typing import (List, Tuple, Optional)
5
  from fastapi import FastAPI, Request
 
6
  import gradio as gr
7
+ import threading
8
  import requests
9
  import argparse
10
  import aiohttp
11
  import uvicorn
12
  import random
13
  import string
14
+ import base64
15
  import json
16
+ import time
17
  import math
18
  import sys
19
  import os
20
 
21
+ # --- === CONFIG === ---
22
+
23
+ ENV_HANDLE = "env"#or "url on env"
24
+ IMAGE_HANDLE = "url"# or "base64"
25
+ API_BASE = "env"# or "openai"
26
+ api_key = os.environ['API_API_KEY']
27
  oai_api_key = os.environ['OPENAI_API_KEY']
28
  base_url = os.environ.get('OPENAI_BASE_URL', "https://api.openai.com/v1")
29
+ # Will not add O1-mini, and O1-preview into the default, as it requeires TIER-5 sub on OpenAI's API.
30
+ # But if you wanna add O1 just remove this comment line and comment the other
31
+ def_models = '["gpt-4", "gpt-4-0125-preview", "gpt-4-0314", "gpt-4-0613", "gpt-4-1106-preview", "gpt-4-1106-vision-preview", "gpt-4-32k-0314", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-turbo-preview", "gpt-4-vision-preview", "chatgpt-4o-latest", "gpt-4o", "gpt-4o-2024-05-13", "gpt-4o-2024-08-06", "gpt-4o-mini", "gpt-4o-mini-2024-07-18", "o1-mini", "o1-mini-2024-09-12", "o1-preview", "o1-preview-2024-09-12"]'
32
+ # def_models = '["gpt-4", "gpt-4-0125-preview", "gpt-4-0314", "gpt-4-0613", "gpt-4-1106-preview", "gpt-4-1106-vision-preview", "gpt-4-32k-0314", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-turbo-preview", "gpt-4-vision-preview", "chatgpt-4o-latest", "gpt-4o", "gpt-4o-2024-05-13", "gpt-4o-2024-08-06", "gpt-4o-mini", "gpt-4o-mini-2024-07-18"]'
33
+ fakeToolPrompt = """[System: You have ability to generate images, via tools provided to you by system.
34
+ To call a tool you need to write a json in a empty line; like writing it at the end of message.
35
+ To generate a image; you need to follow this example JSON:
36
+ {"tool": "imagine", "isCall": true, "prompt": "golden retriever sitting comfortably on a luxurious, modern couch. The retriever should look relaxed and content, with fluffy fur and a friendly expression. The couch should be stylish, possibly with elegant details like cushions and a soft texture that complements the dog's golden coat"}
37
+ > 'tool' variable is used to define which tool you are calling
38
+ > 'isCall' used to confirm that you are calling that function and not showing it for example
39
+ > 'prompt' the image prompt that will be given to image generation model.
40
+
41
+ Here's few more example so you can under stand better
42
+ To show as an example>
43
+ {"tool": "imagine", "isCall": false, "prompt": "futuristic robot playing chess against a human, with the robot confidently strategizing its next move while the human looks thoughtful and slightly perplexed"}
44
+ {"tool": "imagine", "isCall": false, "prompt": "colorful parrot perched on a wooden fence, pecking at a vibrant tropical fruit. The parrot's feathers should be bright and varied, with greens, blues, and reds. The background should feature a lush, green jungle with scattered rays of sunlight"}
45
+ {"tool": "imagine", "isCall": false, "prompt": "fluffy white cat lounging on a sunlit windowsill, with a gentle breeze blowing through the curtains"}
46
+ To actually use the tool>
47
+ {"tool": "imagine", "isCall": true, "prompt": "golden retriever puppy happily playing with a red ball in a sunny park. The park should have green grass, a few trees in the background, and a clear blue sky"}
48
+ {"tool": "imagine", "isCall": true, "prompt": "red panda balancing on a tightrope, with a city skyline in the background"}
49
+ {"tool": "imagine", "isCall": true, "prompt": "corgi puppy wearing sunglasses and a red bandana, sitting on a beach chair under a colorful beach umbrella, with a surfboard leaning against the chair and the ocean waves in the background"}
50
+ In chat use examples:
51
+ 1.
52
+ Alright, here's an image of an hedgehog riding a skateboard:
53
+ {"tool": "imagine", "isCall": true, "prompt": "A hedgehog riding a skateboard in a suburban park"}
54
+ 2.
55
+ Okay, here's the image you requested:
56
+ {"tool": "imagine", "isCall": true, "prompt": "Persian cat lounging on a plush velvet sofa in a cozy, sunlit living room. The cat is elegantly poised, with a calm and regal demeanor, its fur meticulously groomed and slightly fluffed up as it rests comfortably"}
57
+ 3.
58
+ This is how i generate images:
59
+ {"tool": "imagine", "isCall": false, "prompt": "image prompt"}
60
+ 4. (Do not do this, this would block the user from seeing the image.)
61
+ Alright! Here's an image of a whimsical scene featuring a cat wearing a wizard hat, casting a spell with sparkling magic in a mystical forest.] ```
62
+ {"tool": "imagine", "isCall": true, "prompt": "A playful cat wearing a colorful wizard hat, surrounded by magical sparkles and glowing orbs in a mystical forest. The cat looks curious and mischievous, with its tail swishing as it focuses on casting a spell. The forest is lush and enchanting, with vibrant flowers and soft, dappled sunlight filtering through the trees."}
63
+ 5. (if in any case the user asks for the prompt)
64
+ Sure here's the prompt i wrote to generate the image below: `A colorful bird soaring through a bustling city skyline. The bird should have vibrant feathers, contrasting against the modern buildings and blue sky. Below, the city is alive with activity, featuring tall skyscrapers, busy streets, and small parks, creating a dynamic urban scene.`
65
+ ]""";
66
+ calcPrompt = """[System: You have ability to calculate math problems (formated on python), via tools provided to you by system.
67
+ To call a tool you need to write a json in a empty line; like writing it at the end of message.
68
+ To use calculator; you need to follow this example JSON:
69
+ {"tool": "calc", "isCall": true, "prompt": "math.pi * 5"}
70
+ > 'tool' variable is used to define which tool you are calling
71
+ > 'isCall' used to confirm that you are calling that function and not showing it for example
72
+ > 'prompt' the math that will be done via python.
73
+
74
+ Here's few more example so you can under stand better
75
+ To show as an example>
76
+ {"tool": "calc", "isCall": false, "prompt": "math.sqrt(16)"}
77
+ {"tool": "calc", "isCall": false, "prompt": "math.pow(2, 3)"}
78
+ {"tool": "calc", "isCall": false, "prompt": "math.sin(math.pi / 2)"}
79
+ To actually use the tool>
80
+ {"tool": "calc", "isCall": true, "prompt": "math.factorial(5)"}
81
+ {"tool": "calc", "isCall": true, "prompt": "math.log(100, 10)"}
82
+ {"tool": "calc", "isCall": true, "prompt": "math.cos(0)"}
83
+ In chat use examples:
84
+ 1.
85
+ Please, wait while I calculate 2+2...
86
+ {"tool": "calc", "isCall": false, "prompt": "2+2"}
87
+ 2.
88
+ Plase, wait while I calculate the square root of 25...
89
+ {"tool": "calc", "isCall": true, "prompt": "math.sqrt(25)"}
90
+ 3.
91
+ This is how I perform calculations:
92
+ {"tool": "calc", "isCall": false, "prompt": "math.pow(3, 2)"}
93
+ 4. (Do not do this, this would block the user from seeing the result.)
94
+ Alright! Here's the result of a complex calculation involving trigonometry and logarithms. ```
95
+ {"tool": "calc", "isCall": true, "prompt": "math.sin(math.pi / 4) + math.log(10, 10)"}
96
+ ]""";
97
+ searchPrompt = """[System: You have ability to search queries on a search engine, via tools provided to you by system.
98
+ (Warning: Each search call can take up to 30 or more seconds. Only one search function can be called per round. If a response has already been received, the system will answer based on that response. If the query needs to be searched again, the system will ask the user if they want to requery.)
99
+ To call a tool you need to write a json in a empty line; like writing it at the end of message.
100
+ To look up queries; you need to follow this example JSON:
101
+ {"tool": "search", "isCall": true, "prompt": "What is the latest news on climate change?"}
102
+ > 'tool' variable is used to define which tool you are calling
103
+ > 'isCall' used to confirm that you are calling that function and not showing it for example
104
+ > 'prompt' the query that will be searched.
105
+
106
+ Here's a few more examples so you can understand better
107
+ To show as an example>
108
+ {"tool": "search", "isCall": false, "prompt": "How to bake a chocolate cake?"}
109
+ {"tool": "search", "isCall": false, "prompt": "What are the symptoms of the flu?"}
110
+ {"tool": "search", "isCall": false, "prompt": "Best practices for remote work"}
111
+ To actually use the tool>
112
+ {"tool": "search", "isCall": true, "prompt": "How to invest in stocks?"}
113
+ {"tool": "search", "isCall": true, "prompt": "What is the current status of the Mars rover?"}
114
+ {"tool": "search", "isCall": true, "prompt": "Latest advancements in AI technology"}
115
+ In chat use examples:
116
+ 1.
117
+ Please, wait while I search for the latest trends in technology...
118
+ {"tool": "search", "isCall": false, "prompt": "Latest trends in technology"}
119
+ 2.
120
+ Please, wait while I search for the best ways to improve mental health...
121
+ {"tool": "search", "isCall": true, "prompt": "Best ways to improve mental health"}
122
+ 3.
123
+ This is how I perform searches:
124
+ {"tool": "search", "isCall": false, "prompt": "How to start a garden?"}
125
+ 4. (Do not do this, this would block the user from seeing the result.)
126
+ Alright! Here's the result of a search on the impact of social media on teenagers. ```
127
+ {"tool": "search", "isCall": true, "prompt": "Impact of social media on teenagers"}
128
+ ]""";
129
+
130
+ # --- === CONFIG === ---
131
+
132
+ def loadENV():
133
+ def worker():
134
+ while True:
135
+ if ENV_HANDLE == "url on env":
136
+ try:
137
+ response = requests.get(os.environ["ENV_URL"])
138
+ response.raise_for_status()
139
+ env_data = response.json()
140
+ for key, value in env_data.items():
141
+ os.environ[key] = value
142
+ handleApiKeys()
143
+ checkModels()
144
+ loadModels()
145
+ except Exception as e:
146
+ print(f"Error loading environment variables: {e}")
147
+ time.sleep(180)
148
+
149
+ if ENV_HANDLE == "url on env":
150
+ try:
151
+ response = requests.get(os.environ["ENV_URL"])
152
+ response.raise_for_status()
153
+ env_data = response.json()
154
+ for key, value in env_data.items():
155
+ os.environ[key] = value
156
+ handleApiKeys()
157
+ checkModels()
158
+ loadModels()
159
+ except Exception as e:
160
+ print(f"Error loading environment variables: {e}")
161
+
162
+ threading.Thread(target=worker, daemon=True).start()
163
 
164
  def checkModels():
165
  global base_url
 
178
 
179
  def loadModels():
180
  global models, modelList
181
+ try:
182
+ models = json.loads(os.environ.get('OPENAI_API_MODELS', def_models))
183
+ except json.JSONDecodeError:
184
+ models = json.loads(def_models)
185
+
186
  models = sorted(models)
187
+
188
  modelList = {
189
  "object": "list",
190
  "data": [{"id": v, "object": "model", "created": 0, "owned_by": "system"} for v in models]
 
214
  except Exception as e:
215
  raise RuntimeError(f"Current API key is not valid or an actual error happened: {e}")
216
 
217
+ def safe_eval(expression):
218
+ print(expression)
219
+ allowed_names = {name: obj for name, obj in math.__dict__.items() if not name.startswith("__")}
220
+ allowed_names['math'] = math
221
+ code = compile(expression, "<string>", "eval")
222
+ for name in code.co_names:
223
+ if name not in allowed_names and name != 'math':
224
+ raise NameError(f"Use of {name} is not allowed")
225
+ return eval(code, {"__builtins__": {}}, allowed_names)
226
 
227
  def get_api_key(call='api_key'):
228
  if call == 'api_key':
 
236
  return random.choice(key.split(','))
237
  return key
238
 
239
+ def encodeChat(messages):
240
+ output = []
241
+ for message in messages:
242
+ role = message['role']
243
+ name = f" [{message['name']}]" if 'name' in message else ''
244
+ content = message['content']
245
+ formatted_message = f"<|im_start|>{role}{name}\n{content}<|end_of_text|>"
246
+ output.append(formatted_message)
247
+ return "\n".join(output)
248
+
249
  def moderate(messages):
250
  try:
251
  response = requests.post(
 
281
  except KeyError:
282
  if moderation_result["flagged"]:
283
  return moderation_result
284
+
285
  return False
286
 
287
  async def streamChat(params):
288
+ if params.get("model") in ["o1-mini", "o1-mini-2024-09-12", "o1-preview", "o1-preview-2024-09-12"]:
289
+ if "temperature" in params:
290
+ del params["temperature"]
291
+ if "top_p" in params:
292
+ del params["top_p"]
293
+ if "max_tokens" in params:
294
+ params["max_completion_tokens"] = params.pop("max_tokens")
295
+ for message in params.get("messages", []):
296
+ if message["role"] == "system":
297
+ params["messages"].remove(message)
298
+ params["stream"] = False;
299
+ async with aiohttp.ClientSession() as session:
300
+ try:
301
+ async with session.post(f"{base_url}/chat/completions", headers={"Authorization": f"Bearer {get_api_key(call='api_key')}", "Content-Type": "application/json"}, json=params) as r:
302
+ r.raise_for_status()
303
+ response_data = await r.json()
304
+ yield {"choices": [{"delta": {"content": response_data["choices"][0]["message"]["content"]}}]}
305
+ except aiohttp.ClientError:
306
+ try:
307
+ async with session.post("https://api.openai.com/v1/chat/completions", headers={"Authorization": f"Bearer {get_api_key(call='oai_api_key')}", "Content-Type": "application/json"}, json=params) as r:
308
+ r.raise_for_status()
309
+ response_data = await r.json()
310
+ yield {"choices": [{"delta": {"content": response_data["choices"][0]["message"]["content"]}}]}
311
+ except aiohttp.ClientError:
312
+ return
313
+ else:
314
  async with aiohttp.ClientSession() as session:
315
  try:
316
  async with session.post(f"{base_url}/chat/completions", headers={"Authorization": f"Bearer {get_api_key(call='api_key')}", "Content-Type": "application/json"}, json=params) as r:
 
346
  except aiohttp.ClientError:
347
  return
348
 
349
+ def imagine(prompt):
350
+ try:
351
+ response = requests.post(
352
+ f"{base_url}/images/generations",
353
+ headers={
354
+ "Content-Type": "application/json",
355
+ "Authorization": f"Bearer {get_api_key(call='api_key')}"
356
+ },
357
+ json={
358
+ "model": "dall-e-3",
359
+ "prompt": prompt,
360
+ "quality": "hd",
361
+ }
362
+ )
363
+ response.raise_for_status()
364
+ result = response.json()
365
+ except requests.exceptions.RequestException as e:
366
+ print(f"Error during moderation request to {base_url}: {e}")
367
+ try:
368
+ response = requests.post(
369
+ "https://api.openai.com/v1/images/generations",
370
+ headers={
371
+ "Content-Type": "application/json",
372
+ "Authorization": f"Bearer {get_api_key(call='oai_api_key')}"
373
+ },
374
+ json={
375
+ "model": "dall-e-3",
376
+ "prompt": prompt,
377
+ "quality": "hd",
378
+ }
379
+ )
380
+ response.raise_for_status()
381
+ result = response.json()
382
+ except requests.exceptions.RequestException as e:
383
+ print(f"Error during moderation request to fallback URL: {e}")
384
+ return False
385
+
386
+ return result.get('data', [{}])[0].get('url')
387
+
388
+ def searchEngine(query):
389
+ ### This /search endpoint is custom made, OpenAI does not have it.
390
+ ### If you dupelicate this space, please either try to find another API or make one yourself.
391
+ response = requests.get(f"{base_url}/search?query={requests.utils.quote(query)}")
392
+ response.raise_for_status()
393
+ response_data = response.json()
394
+ return response_data.get("choices", [{}])[0].get("message", {}).get("content", "")
395
+
396
  def rnd(length=8):
397
  letters = string.ascii_letters + string.digits
398
  return ''.join(random.choice(letters) for i in range(length))
399
 
400
+ def handleMultimodalData(model, role, data):
401
+ if isinstance(data, tuple):
402
+ data = data[0]
403
+
404
+ if isinstance(data, FileData):
405
+ if data.mime_type.startswith("image/"):
406
+ if IMAGE_HANDLE == "base64":
407
+ with open(data.path, "rb") as image_file:
408
+ b64image = base64.b64encode(image_file.read()).decode('utf-8')
409
+ image_file.close()
410
+ return {"role": role, "content": [{"type": "image_url", "image_url": {"url": "data:" + data.mime_type + ";base64," + b64image}}]}
411
+ else:
412
+ return {"role": role, "content": [{"type": "image_url", "image_url": {"url": data.url}}]}
413
+ elif data.mime_type.startswith("text/") or data.mime_type.startswith("application/"):
414
+ try:
415
+ with open(data.path, "rb") as data_file:
416
+ return {"role": role, "content": "[System: This message contains file.]\n\n<|file_start|>" + data.orig_name + "\n" + data_file.read().decode('utf-8') + "<|file_end|>"}
417
+ except UnicodeDecodeError:
418
+ pass
419
+ elif isinstance(data, str):
420
+ return {"role": role, "content": data}
421
+ elif hasattr(data, 'files') and data.files and len(data.files) > 0 and model in {"gpt-4-1106-vision-preview", "gpt-4-vision-preview", "gpt-4-turbo", "chatgpt-4o-latest", "gpt-4o", "gpt-4o-2024-05-13", "gpt-4o-2024-08-06", "gpt-4o-mini", "gpt-4o-mini-2024-07-18"}:
422
+ result, handler, hasFoundFile = [], ["[System: This message contains files; the system will be splitting it.]"], False
423
+ for file in data.files:
424
+ if file.mime_type.startswith("image/"):
425
+ if IMAGE_HANDLE == "base64":
426
+ with open(file.path, "rb") as image_file:
427
+ result.append({"type": "image_url", "image_url": {"url": "data:" + file.mime_type + ";base64," + base64.b64encode(image_file.read()).decode('utf-8')}})
428
+ image_file.close()
429
+ else:
430
+ result.append({"type": "image_url", "image_url": {"url": file.url}})
431
+ if file.mime_type.startswith("text/") or file.mime_type.startswith("application/"):
432
+ hasFoundFile = True
433
+ try:
434
+ with open(file.path, "rb") as data_file:
435
+ handler.append("<|file_start|>" + file.orig_name + "\n" + data_file.read().decode('utf-8') + "<|file_end|>")
436
+ except UnicodeDecodeError:
437
+ continue
438
+ if hasFoundFile:
439
+ handler.append(data.text)
440
+ return {"role": role, "content": [{"type": "text", "text": "\n\n".join(handler)}] + result}
441
+ else:
442
+ return {"role": role, "content": [{"type": "text", "text": data.text}] + result}
443
+ elif hasattr(data, 'files') and data.files and len(data.files) > 0 and not (model in {"gpt-4-1106-vision-preview", "gpt-4-vision-preview", "gpt-4-turbo", "chatgpt-4o-latest", "gpt-4o", "gpt-4o-2024-05-13", "gpt-4o-2024-08-06", "gpt-4o-mini", "gpt-4o-mini-2024-07-18"}):
444
+ handler, hasFoundFile = ["[System: This message contains files; the system will be splitting it.]"], False
445
+ for file in data.files:
446
+ if file.mime_type.startswith("text/") or file.mime_type.startswith("application/"):
447
+ hasFoundFile = True
448
+ try:
449
+ with open(file.path, "rb") as data_file:
450
+ return {"role": role, "content": "<|file_start|>" + file.orig_name + "\n" + data_file.read().decode('utf-8') + "<|file_end|>"}
451
+ except UnicodeDecodeError:
452
+ continue
453
+ else:
454
+ if isinstance(data, tuple):
455
+ return {"role": role, "content": str(data)}
456
+ return {"role": role, "content": getattr(data, 'text', str(data))}
457
+
458
+ class FileMessage(GradioModel):
459
+ file: FileData
460
+ alt_text: Optional[str] = None
461
+
462
+ class MultimodalMessage(GradioModel):
463
+ text: Optional[str] = None
464
+ files: Optional[List[FileMessage]]
465
 
466
  async def respond(
467
  message,
468
+ history: List[Tuple[
469
+ Optional[MultimodalMessage],
470
+ Optional[MultimodalMessage],
471
+ ]],
472
+ system_message,
473
  model_name,
474
  max_tokens,
475
  temperature,
476
  top_p,
477
+ seed,
478
+ random_seed,
479
+ fakeTool,
480
+ calcBeta,
481
+ searchBeta,
482
+ betterSystemPrompt
483
  ):
484
  messages = [];
485
+ if fakeTool:
486
+ messages.append({"role": "system", "content": fakeToolPrompt});
487
+ if calcBeta:
488
+ messages.append({"role": "system", "content": calcPrompt});
489
+ if searchBeta:
490
+ messages.append({"role": "system", "content": searchPrompt});
491
+ if betterSystemPrompt:
492
+ messages.append({"role": "system", "content": f"You are a helpful assistant. You are an OpenAI GPT model named {model_name}. The current time is {time.strftime('%Y-%m-%d %H:%M:%S')}. Please adhere to OpenAI's usage policies and guidelines. Ensure your responses are accurate, respectful, and within the scope of OpenAI's rules."});
493
+ else:
494
+ messages.append({"role": "system", "content": system_message});
495
 
496
  for val in history:
497
+ if val[0] is not None:
498
+ user_message = handleMultimodalData(model_name, "user", val[0])
499
+ if user_message:
500
+ messages.append(user_message)
501
+ if val[1] is not None:
502
+ assistant_message = handleMultimodalData(model_name, "assistant", val[1])
503
+ if assistant_message:
504
+ messages.append(assistant_message)
505
 
506
  if message:
507
+ user_message = handleMultimodalData(model_name, "user", message)
508
+ if user_message:
509
+ messages.append(user_message)
510
+ mode = moderate([user_message])
511
+ if mode:
512
+ reasons = []
513
+ categories = mode[0].get('categories', {}) if isinstance(mode, list) else mode.get('categories', {})
514
+ for category, flagged in categories.items():
515
+ if flagged:
516
+ reasons.append(category)
517
+ if reasons:
518
+ yield "[MODERATION] I'm sorry, but I can't assist with that.\n\nReasons:\n```\n" + "\n".join([f"{i+1}. {reason}" for i, reason in enumerate(reasons)]) + "\n```"
519
+ else:
520
+ yield "[MODERATION] I'm sorry, but I can't assist with that."
521
+ return
522
+
523
+ async def handleResponse(completion, prefix="", image_count=0, didSearchedAlready=False):
524
+ response = ""
525
+ isRequeryNeeded = False
526
+ async for token in completion:
527
+ response += token['choices'][0]['delta'].get("content", token['choices'][0]['delta'].get("refusal", ""))
528
+ yield f"{prefix}{response}"
529
+ mode = moderate([handleMultimodalData(model_name, "user", message),{"role": "assistant", "content": response}])
530
  if mode:
531
  reasons = []
532
  categories = mode[0].get('categories', {}) if isinstance(mode, list) else mode.get('categories', {})
 
538
  else:
539
  yield "[MODERATION] I'm sorry, but I can't assist with that."
540
  return
541
+ for line in response.split('\n'):
542
+ try:
543
+ data = json.loads(line)
544
+ if isinstance(data, dict) and data.get("tool") == "imagine" and data.get("isCall") and "prompt" in data:
545
+ if image_count < 4:
546
+ image_count += 1
547
+ def fetch_image_url(prompt, line):
548
+ image_url = imagine(prompt)
549
+ return line, f'<img src="{image_url}" alt="{prompt}" width="512"/>'
550
+
551
+ def replace_line_in_response(line, replacement):
552
+ nonlocal response
553
+ response = response.replace(line, replacement)
554
+
555
+ thread = threading.Thread(target=lambda: replace_line_in_response(*fetch_image_url(data["prompt"], line)))
556
+ thread.start()
557
+ thread.join()
558
+ else:
559
+ response = response.replace(line, f'[System: 4 image per message limit; prompt asked: `{data["prompt"]}]`')
560
+ yield f"{prefix}{response}"
561
+ elif isinstance(data, dict) and data.get("tool") == "calc" and data.get("isCall") and "prompt" in data:
562
+ isRequeryNeeded = True
563
+ try:
564
+ result = safe_eval(data["prompt"])
565
+ response = response.replace(line, f'[System: `{data["prompt"]}` === `{result}`]')
566
+ except Exception as e:
567
+ response = response.replace(line, f'[System: Error in calculation; `{e}`]')
568
+ yield f"{prefix}{response}"
569
+ elif isinstance(data, dict) and data.get("tool") == "search" and data.get("isCall") and "prompt" in data:
570
+ isRequeryNeeded = True
571
+ if didSearchedAlready:
572
+ response = response.replace(line, f'[System: One search per response is allowed; due to how long and resource it takes; query: `{data["prompt"]}]`]')
573
+ else:
574
+ try:
575
+ result = searchEngine(data["prompt"])
576
+ result_escaped = result.replace('`', '\\`')
577
+ response = response.replace(line, f'[System: `{data["prompt"]}` ===\n```\n{result_escaped}\n```\n]')
578
+ didSearchedAlready = True
579
+ except Exception as e:
580
+ response = response.replace(line, f'[System: Error in search function; `{e}`]')
581
+ yield f"{prefix}{response}"
582
+ yield f"{prefix}{response}"
583
+ except (json.JSONDecodeError, AttributeError, Exception):
584
+ continue
585
+ if isRequeryNeeded:
586
+ messages.append({"role": "assistant", "content": response})
587
+ async for res in handleResponse(streamChat({
588
+ "model": model_name,
589
+ "messages": messages,
590
+ "max_tokens": max_tokens,
591
+ "temperature": temperature,
592
+ "top_p": top_p,
593
+ "seed": (random.randint(0, 2**32) if random_seed else seed),
594
+ "user": rnd(),
595
+ "stream": True
596
+ }), f"{prefix}{response}\n\n", image_count, didSearchedAlready):
597
+ yield res
598
+ async for res in handleResponse(streamChat({
599
  "model": model_name,
600
  "messages": messages,
601
  "max_tokens": max_tokens,
602
  "temperature": temperature,
603
  "top_p": top_p,
604
+ "seed": (random.randint(0, 2**32) if random_seed else seed),
605
  "user": rnd(),
606
  "stream": True
607
+ })):
608
+ yield res
609
+
 
610
 
611
+ handleApiKeys();loadModels();checkModels();loadENV();
612
+ lastUpdateMessage = "Rolledback the support on O1 model, due to lack of support on params/streaming/etc."
613
  demo = gr.ChatInterface(
614
  respond,
615
  title="gpt-4o-mini",
616
+ description=f"A OpenAI API proxy!<br/>View API docs [here](/api/v1/docs) <strong>[Yes you can use this as an API in a simpler manner]</strong>.<br/><strong>[Last update: {lastUpdateMessage}]</strong> Also you can only submit images to vision models; txt/code/etc. to all models.",
617
+ multimodal=True,
618
  additional_inputs=[
619
+ gr.Textbox(value="You are a helpful assistant. You are an OpenAI GPT model. Please adhere to OpenAI's usage policies and guidelines. Ensure your responses are accurate, respectful, and within the scope of OpenAI's rules.", label="System message"),
620
  gr.Dropdown(choices=models, value="gpt-4o-mini", label="Model"),
621
  gr.Slider(minimum=1, maximum=4096, value=4096, step=1, label="Max new tokens"),
622
  gr.Slider(minimum=0.1, maximum=2.0, value=0.7, step=0.05, label="Temperature"),
623
  gr.Slider(minimum=0.05, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)"),
624
+ gr.Slider(minimum=0, maximum=2**32, value=0, step=1, label="Seed"),
625
+ gr.Checkbox(label="Randomize Seed", value=True),
626
+ gr.Checkbox(label="FakeTool [Image generation beta]", value=True),
627
+ gr.Checkbox(label="FakeTool [Calculator beta]", value=True),
628
+ gr.Checkbox(label="FakeTool [Search engine beta (Warning; each query takes up to 30 seconds)]", value=True),
629
+ gr.Checkbox(label="Better system prompt (ignores the system prompt set by user.)", value=True),
630
  ],
631
  css="footer{display:none !important}",
632
  head="""<script>if(!confirm("By using our application, which integrates with OpenAI's API, you acknowledge and agree to the following terms regarding the data you provide:\\n\\n1. Data Collection: This application may log the following data through the Gradio endpoint or the API endpoint: message requests (including messages, responses, model settings, and images sent along with the messages), images that were generated (including only the prompt and the image), search tool calls (including query, search results, summaries, and output responses), and moderation checks (including input and output).\\n2. Data Retention and Removal: Data is retained until further notice or until a specific request for removal is made.\\n3. Data Usage: The collected data may be used for various purposes, including but not limited to, administrative review of logs, AI training, and publication as a dataset.\\n4. Privacy: Please avoid sharing any personal information.\\n\\nBy continuing to use our application, you explicitly consent to the collection, use, and potential sharing of your data as described above. If you disagree with our data collection, usage, and sharing practices, we advise you not to use our application."))location.href="/declined";</script>"""
 
648
  </html>
649
  """)
650
 
651
+ @app.get("/api/v1/docs")
652
+ def html():
653
+ return FileResponse("index.html")
654
+
655
  app = gr.mount_gradio_app(app, demo, path="/")
656
 
657
  class ArgParser(argparse.ArgumentParser):
 
669
  if args.dev:
670
  uvicorn.run("__main__:app", host=args.server, port=args.port, reload=True)
671
  else:
672
+ uvicorn.run("__main__:app", host=args.server, port=args.port, reload=False)