Update main.py
Browse files
main.py
CHANGED
|
@@ -18,8 +18,21 @@ parser.add_argument("--port", type=int, help="Set the port.(default: 7860)", def
|
|
| 18 |
args = parser.parse_args()
|
| 19 |
|
| 20 |
base_url = os.getenv('MODEL_BASE_URL')
|
|
|
|
| 21 |
print(base_url)
|
| 22 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
@app.route('/api/v1/models', methods=["GET", "POST"])
|
| 24 |
@app.route('/v1/models', methods=["GET", "POST"])
|
| 25 |
def model_list():
|
|
@@ -27,18 +40,8 @@ def model_list():
|
|
| 27 |
model_list = {
|
| 28 |
"object": "list",
|
| 29 |
"data": [
|
| 30 |
-
{
|
| 31 |
-
|
| 32 |
-
"object": "model",
|
| 33 |
-
"created": time_now,
|
| 34 |
-
"owned_by": "tastypear"
|
| 35 |
-
},
|
| 36 |
-
{
|
| 37 |
-
"id": "gpt-3.5-turbo",
|
| 38 |
-
"object": "model",
|
| 39 |
-
"created": time_now,
|
| 40 |
-
"owned_by": "tastypear"
|
| 41 |
-
}
|
| 42 |
]
|
| 43 |
}
|
| 44 |
return jsonify(model_list)
|
|
@@ -56,16 +59,9 @@ def index():
|
|
| 56 |
@app.route("/v1/chat/completions", methods=["POST", "OPTIONS"])
|
| 57 |
def chat_completions():
|
| 58 |
if request.method == "OPTIONS":
|
| 59 |
-
return Response(
|
| 60 |
-
|
| 61 |
-
"Access-Control-Allow-Origin": "*",
|
| 62 |
-
"Access-Control-Allow-Headers": "*",
|
| 63 |
-
}
|
| 64 |
-
)
|
| 65 |
-
|
| 66 |
data = request.get_json()
|
| 67 |
-
|
| 68 |
-
# Set a default system prompt.
|
| 69 |
system = "You are a helpful assistant who responds in English."
|
| 70 |
chat_history = []
|
| 71 |
prompt = ""
|
|
@@ -73,8 +69,6 @@ def chat_completions():
|
|
| 73 |
if "messages" in data:
|
| 74 |
messages = data["messages"]
|
| 75 |
message_size = len(messages)
|
| 76 |
-
|
| 77 |
-
# Get the last message's content as the main prompt.
|
| 78 |
prompt = messages[-1].get("content")
|
| 79 |
|
| 80 |
for i in range(message_size - 1):
|
|
@@ -83,45 +77,32 @@ def chat_completions():
|
|
| 83 |
if role_this == "system":
|
| 84 |
system = messages[i].get("content")
|
| 85 |
elif role_this == "user":
|
| 86 |
-
if role_next == "assistant"
|
| 87 |
-
chat_history.append([messages[i].get("content"), messages[i + 1].get("content")])
|
| 88 |
-
else:
|
| 89 |
-
chat_history.append([messages[i].get("content"), " "])
|
| 90 |
|
| 91 |
-
# Combine system prompt with the user's prompt.
|
| 92 |
if system:
|
| 93 |
prompt = system + "\n" + prompt
|
| 94 |
|
| 95 |
fn_index = 3
|
| 96 |
-
|
| 97 |
-
# Generate a random 10-character hash.
|
| 98 |
-
chars = string.ascii_lowercase + string.digits
|
| 99 |
-
session_hash = "".join(random.choice(chars) for _ in range(10))
|
| 100 |
|
| 101 |
single_prompt_data = {
|
| 102 |
-
'data': [
|
| 103 |
-
prompt,
|
| 104 |
-
[],
|
| 105 |
-
],
|
| 106 |
'event_data': None,
|
| 107 |
'fn_index': 1,
|
| 108 |
'trigger_id': 5,
|
| 109 |
'session_hash': session_hash,
|
| 110 |
}
|
| 111 |
-
|
| 112 |
|
| 113 |
context_data = {
|
| 114 |
-
'data': [
|
| 115 |
-
None,
|
| 116 |
-
chat_history + [[prompt, None]]
|
| 117 |
-
],
|
| 118 |
'event_data': None,
|
| 119 |
'fn_index': fn_index,
|
| 120 |
'trigger_id': 5,
|
| 121 |
'session_hash': session_hash,
|
| 122 |
}
|
| 123 |
-
|
| 124 |
-
|
| 125 |
def generate():
|
| 126 |
url = f"{base_url}/gradio_api/queue/data?session_hash={session_hash}"
|
| 127 |
data = requests.get(url, stream=True)
|
|
@@ -132,22 +113,13 @@ def chat_completions():
|
|
| 132 |
decoded_line = line.decode("utf-8")
|
| 133 |
json_line = json.loads(decoded_line[6:])
|
| 134 |
if json_line["msg"] == "process_starts":
|
| 135 |
-
|
| 136 |
-
yield f"data: {json.dumps(res_data)}\n\n"
|
| 137 |
elif json_line["msg"] == "process_generating":
|
| 138 |
-
|
| 139 |
-
yield f"data: {json.dumps(res_data)}\n\n"
|
| 140 |
elif json_line["msg"] == "process_completed":
|
| 141 |
yield "data: [DONE]"
|
| 142 |
|
| 143 |
-
return Response(
|
| 144 |
-
generate(),
|
| 145 |
-
mimetype="text/event-stream",
|
| 146 |
-
headers={
|
| 147 |
-
"Access-Control-Allow-Origin": "*",
|
| 148 |
-
"Access-Control-Allow-Headers": "*",
|
| 149 |
-
},
|
| 150 |
-
)
|
| 151 |
|
| 152 |
def gen_res_data(data, time_now=0, start=False):
|
| 153 |
res_data = {
|
|
@@ -160,8 +132,8 @@ def gen_res_data(data, time_now=0, start=False):
|
|
| 160 |
if start:
|
| 161 |
res_data["choices"][0]["delta"] = {"role": "assistant", "content": ""}
|
| 162 |
else:
|
| 163 |
-
chat_pair = data
|
| 164 |
-
if chat_pair
|
| 165 |
res_data["choices"][0]["finish_reason"] = "stop"
|
| 166 |
else:
|
| 167 |
res_data["choices"][0]["delta"] = {"content": chat_pair[-1][-1]}
|
|
|
|
| 18 |
args = parser.parse_args()
|
| 19 |
|
| 20 |
base_url = os.getenv('MODEL_BASE_URL')
|
| 21 |
+
API_KEY = os.getenv("API_KEY") # Load API key from environment variable
|
| 22 |
print(base_url)
|
| 23 |
|
| 24 |
+
def verify_api_key():
|
| 25 |
+
"""Check if the API key is valid."""
|
| 26 |
+
api_key = request.headers.get("Authorization")
|
| 27 |
+
if not api_key or api_key != f"Bearer {API_KEY}":
|
| 28 |
+
return jsonify({"error": "Unauthorized"}), 401
|
| 29 |
+
|
| 30 |
+
@app.before_request
|
| 31 |
+
def before_request():
|
| 32 |
+
"""Apply API key validation to all routes except index."""
|
| 33 |
+
if request.endpoint not in ['index']:
|
| 34 |
+
return verify_api_key()
|
| 35 |
+
|
| 36 |
@app.route('/api/v1/models', methods=["GET", "POST"])
|
| 37 |
@app.route('/v1/models', methods=["GET", "POST"])
|
| 38 |
def model_list():
|
|
|
|
| 40 |
model_list = {
|
| 41 |
"object": "list",
|
| 42 |
"data": [
|
| 43 |
+
{"id": "hunyuan-turbo", "object": "model", "created": time_now, "owned_by": "tastypear"},
|
| 44 |
+
{"id": "gpt-3.5-turbo", "object": "model", "created": time_now, "owned_by": "tastypear"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
]
|
| 46 |
}
|
| 47 |
return jsonify(model_list)
|
|
|
|
| 59 |
@app.route("/v1/chat/completions", methods=["POST", "OPTIONS"])
|
| 60 |
def chat_completions():
|
| 61 |
if request.method == "OPTIONS":
|
| 62 |
+
return Response(headers={"Access-Control-Allow-Origin": "*", "Access-Control-Allow-Headers": "*"})
|
| 63 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
data = request.get_json()
|
|
|
|
|
|
|
| 65 |
system = "You are a helpful assistant who responds in English."
|
| 66 |
chat_history = []
|
| 67 |
prompt = ""
|
|
|
|
| 69 |
if "messages" in data:
|
| 70 |
messages = data["messages"]
|
| 71 |
message_size = len(messages)
|
|
|
|
|
|
|
| 72 |
prompt = messages[-1].get("content")
|
| 73 |
|
| 74 |
for i in range(message_size - 1):
|
|
|
|
| 77 |
if role_this == "system":
|
| 78 |
system = messages[i].get("content")
|
| 79 |
elif role_this == "user":
|
| 80 |
+
chat_history.append([messages[i].get("content"), messages[i + 1].get("content") if role_next == "assistant" else " "])
|
|
|
|
|
|
|
|
|
|
| 81 |
|
|
|
|
| 82 |
if system:
|
| 83 |
prompt = system + "\n" + prompt
|
| 84 |
|
| 85 |
fn_index = 3
|
| 86 |
+
session_hash = "".join(random.choice(string.ascii_lowercase + string.digits) for _ in range(10))
|
|
|
|
|
|
|
|
|
|
| 87 |
|
| 88 |
single_prompt_data = {
|
| 89 |
+
'data': [prompt, []],
|
|
|
|
|
|
|
|
|
|
| 90 |
'event_data': None,
|
| 91 |
'fn_index': 1,
|
| 92 |
'trigger_id': 5,
|
| 93 |
'session_hash': session_hash,
|
| 94 |
}
|
| 95 |
+
requests.post(f'{base_url}/gradio_api/run/predict', json=single_prompt_data)
|
| 96 |
|
| 97 |
context_data = {
|
| 98 |
+
'data': [None, chat_history + [[prompt, None]]],
|
|
|
|
|
|
|
|
|
|
| 99 |
'event_data': None,
|
| 100 |
'fn_index': fn_index,
|
| 101 |
'trigger_id': 5,
|
| 102 |
'session_hash': session_hash,
|
| 103 |
}
|
| 104 |
+
requests.post(f"{base_url}/gradio_api/queue/join", json=context_data)
|
| 105 |
+
|
| 106 |
def generate():
|
| 107 |
url = f"{base_url}/gradio_api/queue/data?session_hash={session_hash}"
|
| 108 |
data = requests.get(url, stream=True)
|
|
|
|
| 113 |
decoded_line = line.decode("utf-8")
|
| 114 |
json_line = json.loads(decoded_line[6:])
|
| 115 |
if json_line["msg"] == "process_starts":
|
| 116 |
+
yield f"data: {json.dumps(gen_res_data({}, time_now, start=True))}\n\n"
|
|
|
|
| 117 |
elif json_line["msg"] == "process_generating":
|
| 118 |
+
yield f"data: {json.dumps(gen_res_data(json_line, time_now))}\n\n"
|
|
|
|
| 119 |
elif json_line["msg"] == "process_completed":
|
| 120 |
yield "data: [DONE]"
|
| 121 |
|
| 122 |
+
return Response(generate(), mimetype="text/event-stream", headers={"Access-Control-Allow-Origin": "*", "Access-Control-Allow-Headers": "*"})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
|
| 124 |
def gen_res_data(data, time_now=0, start=False):
|
| 125 |
res_data = {
|
|
|
|
| 132 |
if start:
|
| 133 |
res_data["choices"][0]["delta"] = {"role": "assistant", "content": ""}
|
| 134 |
else:
|
| 135 |
+
chat_pair = data.get("output", {}).get("data", [])[0]
|
| 136 |
+
if not chat_pair:
|
| 137 |
res_data["choices"][0]["finish_reason"] = "stop"
|
| 138 |
else:
|
| 139 |
res_data["choices"][0]["delta"] = {"content": chat_pair[-1][-1]}
|