gpt-4o-mini / app.py
Quardo's picture
Updated space
5799683
raw
history blame
No virus
26.9 kB
from starlette.responses import JSONResponse, FileResponse
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 threading
import requests
import argparse
import aiohttp
import uvicorn
import random
import string
import base64
import json
import time
import sys
import os
# --- === CONFIG === ---
ENV_HANDLE = "env"#or "url on env"
IMAGE_HANDLE = "url"# or "base64"
API_BASE = "env"# or "openai"
api_key = os.environ['OPENAI_API_KEY']
base_url = os.environ.get('OPENAI_BASE_URL', "https://api.openai.com/v1")
def_models = '["gpt-3.5-turbo", "gpt-3.5-turbo-0125", "gpt-3.5-turbo-1106", "gpt-3.5-turbo-16k", "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", "gpt-4o", "gpt-4o-2024-05-13", "gpt-4o-mini", "gpt-4o-mini-2024-07-18"]'
# --- === 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"
except Exception as e:
print(f"Error testing API endpoint: {e}")
else:
base_url = "https://api.openai.com/v1"
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(("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 {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("Current API key is not valid or an actuall error happend {" + e + "}")
def get_api_key():
if ',' in api_key:
return random.choice(api_key.split(','))
return api_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()}"
},
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()}"
},
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):
async with aiohttp.ClientSession() as session:
try:
async with session.post(f"{base_url}/chat/completions", headers={"Authorization": f"Bearer {get_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()}", "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 imagine(prompt):
try:
response = requests.post(
f"{base_url}/images/generations",
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {get_api_key()}"
},
json={
"model": "dall-e-3",
"prompt": prompt,
"quality": "hd",
}
)
response.raise_for_status()
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/images/generations",
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {get_api_key()}"
},
json={
"model": "dall-e-3",
"prompt": prompt,
"quality": "hd",
}
)
response.raise_for_status()
result = response.json()
except requests.exceptions.RequestException as e:
print(f"Error during moderation request to fallback URL: {e}")
return False
return result.get('data', [{}])[0].get('url')
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, tuple):
data = data[0]
if isinstance(data, FileData):
if data.mime_type.startswith("image/"):
if IMAGE_HANDLE == "base64":
with open(data.path, "rb") as image_file:
b64image = base64.b64encode(image_file.read()).decode('utf-8')
image_file.close()
return {"role": role, "content": [{"type": "image_url", "image_url": {"url": "data:" + data.mime_type + ";base64," + b64image}}]}
else:
return {"role": role, "content": [{"type": "image_url", "image_url": {"url": data.url}}]}
elif data.mime_type.startswith("text/") or data.mime_type.startswith("application/"):
try:
with open(data.path, "rb") as data_file:
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|>"}
except UnicodeDecodeError:
pass
elif isinstance(data, str):
return {"role": role, "content": data}
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", "gpt-4o", "gpt-4o-2024-05-13", "gpt-4o-mini", "gpt-4o-mini-2024-07-18"}:
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/"):
if IMAGE_HANDLE == "base64":
with open(file.path, "rb") as image_file:
result.append({"type": "image_url", "image_url": {"url": "data:" + file.mime_type + ";base64," + base64.b64encode(image_file.read()).decode('utf-8')}})
image_file.close()
else:
result.append({"type": "image_url", "image_url": {"url": file.url}})
if file.mime_type.startswith("text/") or file.mime_type.startswith("application/"):
hasFoundFile = True
try:
with open(file.path, "rb") as data_file:
handler.append("<|file_start|>" + file.orig_name + "\n" + data_file.read().decode('utf-8') + "<|file_end|>")
except UnicodeDecodeError:
continue
if hasFoundFile:
handler.append(data.text)
return {"role": role, "content": [{"type": "text", "text": "\n\n".join(handler)}] + result}
else:
return {"role": role, "content": [{"type": "text", "text": data.text}] + result}
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", "gpt-4o", "gpt-4o-2024-05-13", "gpt-4o-mini", "gpt-4o-mini-2024-07-18"}):
handler, hasFoundFile = ["[System: This message contains files; the system will be splitting it.]"], False
for file in data.files:
if file.mime_type.startswith("text/") or file.mime_type.startswith("application/"):
hasFoundFile = True
try:
with open(file.path, "rb") as data_file:
return {"role": role, "content": "<|file_start|>" + file.orig_name + "\n" + data_file.read().decode('utf-8') + "<|file_end|>"}
except UnicodeDecodeError:
continue
else:
if isinstance(data, tuple):
return {"role": role, "content": str(data)}
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,
fakeTool,
betterSystemPrompt,
consent
):
if not consent:
yield """[CONSENT] You must agree to the terms to use this application.
```
By using our application, which integrates with OpenAI's API, you acknowledge and agree to the following terms regarding the data you provide:
1. Data Collection: This application may collect data shared through the Gradio endpoint or the API endpoint.
2. Privacy: Please avoid sharing any personal information.
3. Data Retention and Removal: Data files are deleted every 30 days, and the API is restarted to ensure data clearance.
4. Scope of Data Collected: The data collected includes model settings, chat history, and responses from the model. This applies only to 'chat' endpoints (Gradio and API) and excludes moderation checks.
5. Data Usage: The collected data is periodically reviewed, and if any concerning activity is detected, the code is updated accordingly.
By 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.
```
To agree to user consent, please do the followings:
1. Scroll down to find the section labeled 'Additional Inputs' below this page.
2. Find and click the check box that says 'User Consent [I agree to the terms and conditions. (can't make a button for it)]'.
3. After agreeing, click either the `🗑️ Clear` button, the `↩️ Undo` button, or the `🔄 Retry` button located above the message input area."""
return
messages = [];
if fakeTool:
messages.append({"role": "system", "content": """[System: You have ability to generate images, 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 generate a image; you need to follow this example JSON:
{"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"}
> '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 image prompt that will be given to image generation model.
Here's few more example so you can under stand better
To show as an example>
{"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"}
{"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"}
{"tool": "imagine", "isCall": false, "prompt": "fluffy white cat lounging on a sunlit windowsill, with a gentle breeze blowing through the curtains"}
To actually use the tool>
{"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"}
{"tool": "imagine", "isCall": true, "prompt": "red panda balancing on a tightrope, with a city skyline in the background"}
{"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"}
In chat use examples:
1. ```
Alright, here's an image of an hedgehog riding a skateboard:
{"tool": "imagine", "isCall": true, "prompt": "A hedgehog riding a skateboard in a suburban park"}
```
2. ```
Okay, here's the image you requested:
{"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"}
```]
3. ```
This is how i generate images:
{"tool": "imagine", "isCall": false, "prompt": "image prompt"}
```
4. (Do not do this, this would block the user from seeing the image.) ```
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.] \`\`\`
{"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."}
\`\`\`
```
5. (if in any case the user asks for the prompt)```
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.`
```]"""})
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)
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
response = ""
completion = 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
})
async for token in completion:
response += token['choices'][0]['delta'].get("content", "")
yield response
for line in response.split('\n'):
try:
data = json.loads(line)
if "tool" in data and "isCall" in data and data["tool"] == "imagine" and data["isCall"] == True and "prompt" in data:
image_url = imagine(data["prompt"])
response = response.replace(line, f'<img src="{image_url}" alt="{data["prompt"]}" width="512"/>')
yield response
except json.JSONDecodeError:
continue
handleApiKeys();loadModels();checkModels();loadENV();
lastUpdateMessage = "Added image generation via DALL-E-3."
demo = gr.ChatInterface(
respond,
title="GPT-4O-mini",
description=f"A simple proxy to OpenAI!<br/>You can use this space as a proxy! click [here](/api/v1/docs) to view the documents. <strong>[last update: {lastUpdateMessage}]</strong><br/>Also you can only submit images to vision/4o models but can submit txt/code/etc. files 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-2024-07-18", 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 [Image generation beta]", value=True),
gr.Checkbox(label="Better system prompt (ignores the system prompt set by user.)", value=True),
gr.Checkbox(label="User Consent [I agree to the terms and conditions. (can't make a button for it)]", value=False)
],
)
app = FastAPI()
@app.get("/api/v1/docs")
def html():
return FileResponse("index.html")
@app.get("/api/v1/models")
async def test_endpoint():
return JSONResponse(content=modelList)
@app.post("/api/v1/chat/completions")
async def chat_completion(request: Request):
try:
body = await request.json()
if not body.get("messages") or not body.get("model"):
return JSONResponse(content={"error": { "code": "MISSING_VALUE", "message": "Both 'messages' and 'model' are required fields."}}, status_code=400)
if not body.get("model") in models:
return JSONResponse(content={"error": { "code": "INVALID_MODEL", "message": "The model name provided in the request does not exists in predefined list of models."}}, status_code=400)
params = {
key: value for key, value in {
"model": body.get("model"),
"messages": body.get("messages"),
"max_tokens": body.get("max_tokens"),
"temperature": body.get("temperature"),
"top_p": body.get("top_p"),
"frequency_penalty": body.get("frequency_penalty"),
"logit_bias": body.get("logit_bias"),
"logprobs": body.get("logprobs"),
"top_logprobs": body.get("top_logprobs"),
"n": body.get("n"),
"presence_penalty": body.get("presence_penalty"),
"response_format": body.get("response_format"),
"seed": body.get("seed"),
"service_tier": body.get("service_tier"),
"stop": body.get("stop"),
"stream": body.get("stream"),
"stream_options": body.get("stream_options"),
"tools": body.get("tools"),
"tool_choice": body.get("tool_choice"),
"parallel_tool_calls": body.get("parallel_tool_calls"),
"user": rnd(),
}.items() if value is not None
}
if body.get("stream"):
async def event_generator():
async for event in streamChat(params):
yield json.dumps(event)
return EventSourceResponse(event_generator())
else:
try:
response = requests.post(f"{base_url}/chat/completions", headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}, json=params)
response.raise_for_status()
except requests.exceptions.RequestException:
try:
response = requests.post("https://api.openai.com/v1/chat/completions", headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}, json=params)
response.raise_for_status()
except requests.exceptions.RequestException as e:
return JSONResponse(content={"error": { "code": "SERVER_ERROR", "message": str(e)}}, status_code=400)
completion = response.json()
return JSONResponse(content=completion)
except Exception as e:
return JSONResponse(content={"error": { "code": "SERVER_ERROR", "message": str(e)}}, status_code=400)
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)