File size: 28,600 Bytes
899e654
3655a2f
 
 
f6874c9
bcfa1bb
3a9a095
f6874c9
bf38597
1f46917
bf38597
1f46917
b9c4863
 
bf38597
b9c4863
f6874c9
4d70c71
1f46917
bf38597
 
 
 
f6874c9
34275fb
f6874c9
81ff87e
27ed3be
 
bf38597
0f106cc
a3d9c23
 
0f106cc
 
 
 
ed0e073
4d70c71
ed0e073
4d70c71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed0e073
f41b9ef
ed0e073
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bf38597
 
 
f6874c9
 
 
 
 
 
 
 
 
 
5799683
f6874c9
 
 
 
 
 
 
 
 
 
 
 
 
5799683
f6874c9
 
 
 
 
 
3655a2f
f6874c9
 
 
 
5799683
f6874c9
 
 
27ed3be
f6874c9
 
 
 
27ed3be
3655a2f
f6874c9
 
 
 
 
 
 
 
 
 
 
 
 
3655a2f
5799683
 
 
 
 
 
 
 
 
 
 
4d70c71
5799683
 
 
 
 
4d70c71
5799683
 
 
 
4d70c71
 
 
 
 
 
 
 
 
 
 
5799683
5135341
 
27ed3be
5135341
27ed3be
 
 
 
 
 
 
5799683
3655a2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5135341
3655a2f
 
 
 
 
 
f6874c9
 
 
 
 
 
5135341
f6874c9
 
 
 
 
 
 
 
 
 
5852d5d
 
f6874c9
5852d5d
 
 
 
3655a2f
bf38597
bffdc7a
4b342a9
 
 
 
 
 
bffdc7a
 
48303e3
d89748a
 
f6874c9
d89748a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f6874c9
 
 
 
 
 
 
 
 
 
 
 
 
 
d89748a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bcfa1bb
ed0e073
 
 
 
 
 
 
 
b9c4863
 
 
bcfa1bb
bf38597
a28bf8c
bf38597
a28bf8c
 
bf38597
a28bf8c
 
 
bf38597
2a276f1
a28bf8c
bf38597
3655a2f
a28bf8c
 
 
3655a2f
 
bf38597
a28bf8c
bf38597
 
a28bf8c
3a9a095
 
 
 
 
 
 
 
 
 
 
81ff87e
3a9a095
 
 
 
 
 
 
 
 
bf38597
009769a
bf38597
3655a2f
 
 
 
 
 
 
 
bf38597
bcfa1bb
3655a2f
 
 
 
bcfa1bb
b9c4863
bcfa1bb
 
 
b9c4863
f6874c9
4d70c71
ed0e073
9451027
bcfa1bb
1e0c08a
4d70c71
 
ed0e073
 
5799683
 
 
 
bcfa1bb
 
3655a2f
 
 
 
 
 
 
 
bcfa1bb
4d70c71
 
 
 
81ff87e
27ed3be
 
 
 
 
 
 
 
 
 
 
3655a2f
bbb69f6
4d70c71
ed0e073
4d70c71
06d209a
4d70c71
81ff87e
27ed3be
 
 
 
 
 
 
 
 
 
 
4d70c71
 
 
bbb69f6
ed0e073
4d70c71
 
 
 
 
 
27ed3be
ed0e073
f41b9ef
27ed3be
f41b9ef
 
 
 
 
 
 
 
 
ed0e073
27ed3be
4d70c71
ed0e073
4d70c71
 
 
 
 
 
 
 
 
 
bbb69f6
4d70c71
 
bf38597
 
 
 
 
 
 
 
4d70c71
 
 
bcfa1bb
5799683
bbb69f6
bcfa1bb
 
1d8e2d0
9451027
bf38597
bcfa1bb
5799683
b974d61
bf38597
 
5799683
b9c4863
bf38597
4d70c71
9451027
5799683
bcfa1bb
27ed3be
a48c771
bcfa1bb
 
b9c4863
 
a48c771
 
899e654
 
 
 
 
 
 
 
 
 
 
9451027
bf38597
 
 
 
b9c4863
bcfa1bb
1f46917
 
 
 
bed08e5
 
1f46917
 
 
 
bcfa1bb
1f46917
 
 
 
f6874c9
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
from starlette.responses import JSONResponse, FileResponse, HTMLResponse
from gradio.data_classes import FileData, GradioModel
from sse_starlette.sse import EventSourceResponse
from typing import (List, Tuple, Optional)
from fastapi import FastAPI, Request
import gradio as gr
import mimetypes
import threading
import requests
import argparse
import aiohttp
import uvicorn
import random
import string
import base64
import json
import time
import math
import sys
import os

# --- === CONFIG === ---

ENV_HANDLE = "env"#or "url on env"
IMAGE_HANDLE = "url"# or "base64"
API_BASE = "env"# or "openai"
GRADIO_URL_PATH = "https://quardo-gpt-4o-mini.hf.space/"
api_key = os.environ['API_API_KEY']
oai_api_key = os.environ['OPENAI_API_KEY']
base_url = os.environ.get('OPENAI_BASE_URL', "https://api.openai.com/v1")

# Will not add O1-mini, and O1-preview into the default, as it requeires TIER-5 sub on OpenAI's API.
# But if you wanna add O1 just remove this comment line and comment the other
# 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", "o1-mini", "o1-mini-2024-09-12", "o1-preview", "o1-preview-2024-09-12"]'
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"]'

vision_models = {"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"}
calcPrompt = """[System: You have ability to calculate math problems (formated on python), via tools provided to you by system.
To call a tool you need to write a json in a empty line; like writing it at the end of message.
To use calculator; you need to follow this example JSON:
{"tool": "calc", "isCall": true, "prompt": "math.pi * 5"}
> 'tool' variable is used to define which tool you are calling
> 'isCall' used to confirm that you are calling that function and not showing it for example
> 'prompt' the math that will be done via python.

Here's few more example so you can under stand better
To show as an example>
    {"tool": "calc", "isCall": false, "prompt": "math.sqrt(16)"}
    {"tool": "calc", "isCall": false, "prompt": "math.pow(2, 3)"}
    {"tool": "calc", "isCall": false, "prompt": "math.sin(math.pi / 2)"}
To actually use the tool>
    {"tool": "calc", "isCall": true, "prompt": "math.factorial(5)"}
    {"tool": "calc", "isCall": true, "prompt": "math.log(100, 10)"}
    {"tool": "calc", "isCall": true, "prompt": "math.cos(0)"}
In chat use examples:
1. 
Please, wait while I calculate 2+2...
{"tool": "calc", "isCall": false, "prompt": "2+2"}
2. 
Plase, wait while I calculate the square root of 25...
{"tool": "calc", "isCall": true, "prompt": "math.sqrt(25)"}
3. 
This is how I perform calculations:
{"tool": "calc", "isCall": false, "prompt": "math.pow(3, 2)"}
4. (Do not do this, this would block the user from seeing the result.)
Alright! Here's the result of a complex calculation involving trigonometry and logarithms. ```
{"tool": "calc", "isCall": true, "prompt": "math.sin(math.pi / 4) + math.log(10, 10)"}
]""";
searchPrompt = """[System: You have ability to search queries on a search engine, via tools provided to you by system.
(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.)
To call a tool you need to write a json in a empty line; like writing it at the end of message.
To look up queries; you need to follow this example JSON:
{"tool": "search", "isCall": true, "prompt": "What is the latest news on climate change?"}
> 'tool' variable is used to define which tool you are calling
> 'isCall' used to confirm that you are calling that function and not showing it for example
> 'prompt' the query that will be searched.

Here's a few more examples so you can understand better
To show as an example>
    {"tool": "search", "isCall": false, "prompt": "How to bake a chocolate cake?"}
    {"tool": "search", "isCall": false, "prompt": "What are the symptoms of the flu?"}
    {"tool": "search", "isCall": false, "prompt": "Best practices for remote work"}
To actually use the tool>
    {"tool": "search", "isCall": true, "prompt": "How to invest in stocks?"}
    {"tool": "search", "isCall": true, "prompt": "What is the current status of the Mars rover?"}
    {"tool": "search", "isCall": true, "prompt": "Latest advancements in AI technology"}
In chat use examples:
1. 
Please, wait while I search for the latest trends in technology...
{"tool": "search", "isCall": false, "prompt": "Latest trends in technology"}
2. 
Please, wait while I search for the best ways to improve mental health...
{"tool": "search", "isCall": true, "prompt": "Best ways to improve mental health"}
3. 
This is how I perform searches:
{"tool": "search", "isCall": false, "prompt": "How to start a garden?"}
4. (Do not do this, this would block the user from seeing the result.)
Alright! Here's the result of a search on the impact of social media on teenagers. ```
{"tool": "search", "isCall": true, "prompt": "Impact of social media on teenagers"}
]""";

# --- === CONFIG === ---

def loadENV():
    def worker():
        while True:
            if ENV_HANDLE == "url on env":
                try:
                    response = requests.get(os.environ["ENV_URL"])
                    response.raise_for_status()
                    env_data = response.json()
                    for key, value in env_data.items():
                        os.environ[key] = value
                    handleApiKeys()
                    checkModels()
                    loadModels()
                except Exception as e:
                    print(f"Error loading environment variables: {e}")
            time.sleep(180)
    
    if ENV_HANDLE == "url on env":
        try:
            response = requests.get(os.environ["ENV_URL"])
            response.raise_for_status()
            env_data = response.json()
            for key, value in env_data.items():
                os.environ[key] = value
            handleApiKeys()
            checkModels()
            loadModels()
        except Exception as e:
            print(f"Error loading environment variables: {e}")
    
    threading.Thread(target=worker, daemon=True).start()

def checkModels():
    global base_url
    if API_BASE == "env":
        try:
            response = requests.get(f"{base_url}/models", headers={"Authorization": f"Bearer {get_api_key()}"})
            response.raise_for_status()
            if not ('data' in response.json()):
                base_url = "https://api.openai.com/v1"
                api_key = oai_api_key
        except Exception as e:
            print(f"Error testing API endpoint: {e}")
    else:
        base_url = "https://api.openai.com/v1"
        api_key = oai_api_key

def loadModels():
    global models, modelList
    try:
        models = json.loads(os.environ.get('OPENAI_API_MODELS', def_models))
    except json.JSONDecodeError:
        models = json.loads(def_models)
    
    models = sorted(models)
    
    modelList = {
        "object": "list",
        "data": [{"id": v, "object": "model", "created": 0, "owned_by": "system"} for v in models]
    }

def handleApiKeys():
    global api_key
    if ',' in api_key:
        output = []
        for key in api_key.split(','):
            try:
                response = requests.get(f"{base_url}/models", headers={"Authorization": f"Bearer {key}"})
                response.raise_for_status()
                if ('data' in response.json()):
                    output.append(key)
            except Exception as e:
                print((F"API key {key} is not valid or an actuall error happend {e}"))
        if len(output)==1:
            raise RuntimeError("No API key is working")
        api_key = ",".join(output)
    else:
        try:
            response = requests.get(f"{base_url}/models", headers={"Authorization": f"Bearer {api_key}"})
            response.raise_for_status()
            if not ('data' in response.json()):
                raise RuntimeError("Current API key is not valid")
        except Exception as e:
            raise RuntimeError(f"Current API key is not valid or an actual error happened: {e}")

def safe_eval(expression):
    print(expression)
    allowed_names = {name: obj for name, obj in math.__dict__.items() if not name.startswith("__")}
    allowed_names['math'] = math
    code = compile(expression, "<string>", "eval")
    for name in code.co_names:
        if name not in allowed_names and name != 'math':
            raise NameError(f"Use of {name} is not allowed")
    return eval(code, {"__builtins__": {}}, allowed_names)

def get_api_key(call='api_key'):
    if call == 'api_key':
        key = api_key
    elif call == 'oai_api_key':
        key = oai_api_key
    else:
        key = api_key

    if ',' in key:
        return random.choice(key.split(','))
    return key

def encodeChat(messages):
    output = []
    for message in messages:
        role = message['role']
        name = f" [{message['name']}]" if 'name' in message else ''
        content = message['content']
        formatted_message = f"<|im_start|>{role}{name}\n{content}<|end_of_text|>"
        output.append(formatted_message)
    return "\n".join(output)

def moderate(messages):
    try:
        response = requests.post(
            f"{base_url}/moderations",
            headers={
                "Content-Type": "application/json",
                "Authorization": f"Bearer {get_api_key(call='api_key')}"
            },
            json={"input": encodeChat(messages)}
        )
        response.raise_for_status()
        moderation_result = response.json()
    except requests.exceptions.RequestException as e:
        print(f"Error during moderation request to {base_url}: {e}")
        try:
            response = requests.post(
                "https://api.openai.com/v1/moderations",
                headers={
                    "Content-Type": "application/json",
                    "Authorization": f"Bearer {get_api_key(call='oai_api_key')}"
                },
                json={"input": encodeChat(messages)}
            )
            response.raise_for_status()
            moderation_result = response.json()
        except requests.exceptions.RequestException as e:
            print(f"Error during moderation request to fallback URL: {e}")
            return False

    try:
        if any(result["flagged"] for result in moderation_result["results"]):
            return moderation_result
    except KeyError:
        if moderation_result["flagged"]:
            return moderation_result
    
    return False

async def streamChat(params):
    if params.get("model") in ["o1-mini", "o1-mini-2024-09-12", "o1-preview", "o1-preview-2024-09-12"]:
        if "temperature" in params:
            del params["temperature"]
        if "top_p" in params:
            del params["top_p"]
        if "max_tokens" in params:
            params["max_completion_tokens"] = params.pop("max_tokens")
        for message in params.get("messages", []):
            if message["role"] == "system":
                params["messages"].remove(message)
        params["stream"] = False;
        async with aiohttp.ClientSession() as session:
            try:
                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:
                    r.raise_for_status()
                    response_data = await r.json()
                    yield {"choices": [{"delta": {"content": response_data["choices"][0]["message"]["content"]}}]}
            except aiohttp.ClientError:
                try:
                    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:
                        r.raise_for_status()
                        response_data = await r.json()
                        yield {"choices": [{"delta": {"content": response_data["choices"][0]["message"]["content"]}}]}
                except aiohttp.ClientError:
                    return
    else:
        async with aiohttp.ClientSession() as session:
            try:
                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:
                    r.raise_for_status()
                    async for line in r.content:
                        if line:
                            line_str = line.decode('utf-8')
                            if line_str.startswith("data: "):
                                line_str = line_str[6:].strip()
                            if line_str == "[DONE]":
                                continue
                            try:
                                message = json.loads(line_str)
                                yield message
                            except json.JSONDecodeError:
                                continue
            except aiohttp.ClientError:
                try:
                    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:
                        r.raise_for_status()
                        async for line in r.content:
                            if line:
                                line_str = line.decode('utf-8')
                                if line_str.startswith("data: "):
                                    line_str = line_str[6:].strip()
                                if line_str == "[DONE]":
                                    continue
                                try:
                                    message = json.loads(line_str)
                                    yield message
                                except json.JSONDecodeError:
                                    continue
                except aiohttp.ClientError:
                    return

def searchEngine(query):
    ### This /search endpoint is custom made, OpenAI does not have it.
	### If you dupelicate this space, please either try to find another API or make one yourself.
    response = requests.get(f"{base_url}/search?query={requests.utils.quote(query)}")
    response.raise_for_status()
    response_data = response.json()
    return response_data.get("choices", [{}])[0].get("message", {}).get("content", "")

def rnd(length=8):
    letters = string.ascii_letters + string.digits
    return ''.join(random.choice(letters) for i in range(length))

def handleMultimodalData(model, role, data):
    if isinstance(data, dict) and 'files' in data and len(data['files']) > 0:
        result, handler, hasFoundFile = [], ["[System: This message contains files; the system will be splitting it.]"], False
        for file in data['files']:
            if file['mime_type'].startswith("image/") and model in vision_models:
                if IMAGE_HANDLE == "base64":
                    with open(file['path'], "rb") as image_file:
                        encoded_image = base64.b64encode(image_file.read()).decode('utf-8')
                        result.append({"type": "image_url", "image_url": {"url": "data:" + file['mime_type'] + ";base64," + encoded_image}})
                else:
                    result.append({"type": "image_url", "image_url": {"url": GRADIO_URL_PATH + "file=" + requests.utils.quote(str(file['path']))}})
            if file['mime_type'].startswith("text/") or file['mime_type'].startswith("application/"):
                hasFoundFile = True
                try:
                    with open(file['path'], "rb") as data_file:
                        file_content = data_file.read().decode('utf-8')
                        handler.append("<|file_start|>" + file['orig_name'] + "\n" + file_content + "<|file_end|>")
                except UnicodeDecodeError:
                    continue
        if hasFoundFile:
            handler.append(data.get('text', ''))
            return {"role": role, "content": [{"type": "text", "text": "\n\n".join(handler)}] + result}
        else:
            return {"role": role, "content": [{"type": "text", "text": data.get('text', '')}] + result}
    elif isinstance(data, Tuple):
        file_path = data[0]
        mime_type, _ = mimetypes.guess_type(file_path)
        content = getattr(data, 'text', str(data))
        
        if mime_type and mime_type.startswith("image/") and model in vision_models:
            if IMAGE_HANDLE == "base64":
                with open(file_path, "rb") as image_file:
                    encoded_image = base64.b64encode(image_file.read()).decode('utf-8')
                    return {"role": role, "content": [{"type": "image_url", "image_url": {"url": "data:" + mime_type + ";base64," + encoded_image}}]}
            else:
                return {"role": role, "content": [{"type": "image_url", "image_url": {"url": GRADIO_URL_PATH + "file=" + requests.utils.quote(file_path)}}]}
        elif mime_type and (mime_type.startswith("text/") or mime_type.startswith("application/")):
            try:
                with open(file_path, "rb") as data_file:
                    file_content = data_file.read().decode('utf-8')
                    return {"role": role, "content": [{"type": "text", "text": "<|file_start|>" + os.path.basename(file_path) + "\n" + file_content + "<|file_end|>"}]}
            except UnicodeDecodeError:
                return {"role": role, "content": [{"type": "text", "text": content}]}
        else:
            return {"role": role, "content": content}
    else:
        return {"role": role, "content": getattr(data, 'text', str(data))}

class FileMessage(GradioModel):
    file: FileData
    alt_text: Optional[str] = None

class MultimodalMessage(GradioModel):
    text: Optional[str] = None
    files: Optional[List[FileMessage]]

async def respond(
    message,
    history: List[Tuple[
        Optional[MultimodalMessage],
        Optional[MultimodalMessage],
    ]],
    system_message,
    model_name,
    max_tokens,
    temperature,
    top_p,
    seed,
    random_seed,
    calcBeta,
    searchBeta,
	betterSystemPrompt
):
    messages = [];
    if calcBeta:
        messages.append({"role": "system", "content": calcPrompt});
    if searchBeta:
        messages.append({"role": "system", "content": searchPrompt});
    if betterSystemPrompt:
        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."});
    else:
        messages.append({"role": "system", "content": system_message});

    for val in history:
        if val[0] is not None:
            user_message = handleMultimodalData(model_name, "user", val[0])
            if user_message:
                messages.append(user_message)
        if val[1] is not None:
            assistant_message = handleMultimodalData(model_name, "assistant", val[1])
            if assistant_message:
                messages.append(assistant_message)

    if message:
        user_message = handleMultimodalData(model_name, "user", message)
        if user_message:
            messages.append(user_message)
            mode = moderate(messages)
            if mode:
                reasons = []
                categories = mode[0].get('categories', {}) if isinstance(mode, list) else mode.get('categories', {})
                for category, flagged in categories.items():
                    if flagged:
                        reasons.append(category)
                if reasons:
                    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```"
                else:
                    yield "[MODERATION] I'm sorry, but I can't assist with that."
                return
    
    async def handleResponse(completion, prefix="", didSearchedAlready=False):
        response = ""
        isRequeryNeeded = False
        async for token in completion:
            response += token['choices'][0]['delta'].get("content", token['choices'][0]['delta'].get("refusal", ""))
            yield f"{prefix}{response}"
        mode = moderate(messages + [{"role": "assistant", "content": response}])
        if mode:
            reasons = []
            categories = mode[0].get('categories', {}) if isinstance(mode, list) else mode.get('categories', {})
            for category, flagged in categories.items():
                if flagged:
                    reasons.append(category)
            if reasons:
                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```"
            else:
                yield "[MODERATION] I'm sorry, but I can't assist with that."
            return
        for line in response.split('\n'):
            try:
                data = json.loads(line)
                if isinstance(data, dict) and data.get("tool") == "calc" and data.get("isCall") and "prompt" in data:
                    isRequeryNeeded = True
                    try:
                        result = safe_eval(data["prompt"])
                        response = response.replace(line, f'[System: `{data["prompt"]}` === `{result}`]')
                    except Exception as e:
                        response = response.replace(line, f'[System: Error in calculation; `{e}`]')
                    yield f"{prefix}{response}"
                elif isinstance(data, dict) and data.get("tool") == "search" and data.get("isCall") and "prompt" in data:
                    isRequeryNeeded = True
                    if didSearchedAlready:
                        response = response.replace(line, f'[System: One search per response is allowed; due to how long and resource it takes; query: `{data["prompt"]}]`]')
                    else:
                        try:
                            result = searchEngine(data["prompt"])
                            result_escaped = result.replace('`', '\\`')
                            response = response.replace(line, f'[System: `{data["prompt"]}` ===\n```\n{result_escaped}\n```\n]')
                            didSearchedAlready = True
                        except Exception as e:
                            response = response.replace(line, f'[System: Error in search function; `{e}`]')
                        yield f"{prefix}{response}"
                    yield f"{prefix}{response}"
            except (json.JSONDecodeError, AttributeError, Exception):
                continue
            if isRequeryNeeded:
                messages.append({"role": "assistant", "content": response})
                async for res in handleResponse(streamChat({
                    "model": model_name,
                    "messages": messages,
                    "max_tokens": max_tokens,
                    "temperature": temperature,
                    "top_p": top_p,
                    "seed": (random.randint(0, 2**32) if random_seed else seed),
                    "user": rnd(),
                    "stream": True
                }), f"{prefix}{response}\n\n", didSearchedAlready):
                    yield res
    async for res in handleResponse(streamChat({
        "model": model_name,
        "messages": messages,
        "max_tokens": max_tokens,
        "temperature": temperature,
        "top_p": top_p,
        "seed": (random.randint(0, 2**32) if random_seed else seed),
        "user": rnd(),
        "stream": True
    })):
        yield res
        

handleApiKeys();loadModels();checkModels();loadENV();
lastUpdateMessage = "Back online yet again. Removed support for image generation."
demo = gr.ChatInterface(
    respond,
    title="gpt-4o-mini",
    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.",
    multimodal=True,
    additional_inputs=[
        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"),
        gr.Dropdown(choices=models, value="gpt-4o-mini", label="Model"),
        gr.Slider(minimum=1, maximum=4096, value=4096, step=1, label="Max new tokens"),
        gr.Slider(minimum=0.1, maximum=2.0, value=0.7, step=0.05, label="Temperature"),
        gr.Slider(minimum=0.05, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)"),
        gr.Slider(minimum=0, maximum=2**32, value=0, step=1, label="Seed"),
        gr.Checkbox(label="Randomize Seed", value=True),
        gr.Checkbox(label="FakeTool [Calculator beta]", value=True),
        gr.Checkbox(label="FakeTool [Search engine beta (Warning; each query takes up to 30 seconds)]", value=True),
        gr.Checkbox(label="Better system prompt (ignores the system prompt set by user.)", value=True),
    ],
    css="footer{display:none !important}",
    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>"""
)

app = FastAPI()

@app.get("/declined")
def test():
    return HTMLResponse(content="""
        <html>
            <head>
                <title>Declined</title>
            </head>
            <body>
                <p>Ok, you can go back to Hugging Face. I just didn't have any idea how to handle decline so you are redirected here.</p><br/>
                <a href="/">Go back</button>
            </body>
        </html>
    """)

@app.get("/api/v1/docs")
def html():
    return FileResponse("index.html")

app = gr.mount_gradio_app(app, demo, path="/")

class ArgParser(argparse.ArgumentParser):
    def __init__(self, *args, **kwargs):
        super(ArgParser, self).__init__(*args, **kwargs)

        self.add_argument("-s", "--server", type=str, default="0.0.0.0")
        self.add_argument("-p", "--port", type=int, default=7860)
        self.add_argument("-d", "--dev", default=False, action="store_true")

        self.args = self.parse_args(sys.argv[1:])

if __name__ == "__main__":
    args = ArgParser().args
    if args.dev:
        uvicorn.run("__main__:app", host=args.server, port=args.port, reload=True)
    else:
        uvicorn.run("__main__:app", host=args.server, port=args.port, reload=False)