Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,160 +1,169 @@
|
|
| 1 |
-
from flask import Flask, request, jsonify, Response
|
| 2 |
-
from functools import wraps
|
| 3 |
-
import uuid
|
| 4 |
-
import json
|
| 5 |
-
from typing import List, Optional
|
| 6 |
-
from pydantic import BaseModel, ValidationError
|
| 7 |
-
|
| 8 |
-
from
|
| 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 |
-
"meta-llama/Meta-Llama-3.1-405B-Instruct-Turbo"
|
| 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 |
app.run(host="0.0.0.0", port=8000)
|
|
|
|
| 1 |
+
from flask import Flask, request, jsonify, Response
|
| 2 |
+
from functools import wraps
|
| 3 |
+
import uuid
|
| 4 |
+
import json
|
| 5 |
+
from typing import List, Optional
|
| 6 |
+
from pydantic import BaseModel, ValidationError
|
| 7 |
+
import logging
|
| 8 |
+
from API_provider import API_Inference
|
| 9 |
+
from core_logic import (
|
| 10 |
+
check_api_key_validity,
|
| 11 |
+
update_request_count,
|
| 12 |
+
get_rate_limit_status,
|
| 13 |
+
get_subscription_status,
|
| 14 |
+
get_available_models,
|
| 15 |
+
get_model_info,
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
app = Flask(__name__)
|
| 19 |
+
logging.basicConfig(level=logging.DEBUG)
|
| 20 |
+
|
| 21 |
+
class Message(BaseModel):
|
| 22 |
+
role: str
|
| 23 |
+
content: str
|
| 24 |
+
|
| 25 |
+
class ChatCompletionRequest(BaseModel):
|
| 26 |
+
model: str
|
| 27 |
+
messages: List[Message]
|
| 28 |
+
stream: Optional[bool] = False
|
| 29 |
+
max_tokens: Optional[int] = 4000
|
| 30 |
+
temperature: Optional[float] = 0.5
|
| 31 |
+
top_p: Optional[float] = 0.95
|
| 32 |
+
|
| 33 |
+
def get_api_key():
|
| 34 |
+
auth_header = request.headers.get('Authorization')
|
| 35 |
+
if not auth_header or not auth_header.startswith('Bearer '):
|
| 36 |
+
return None
|
| 37 |
+
return auth_header.split(' ')[1]
|
| 38 |
+
|
| 39 |
+
def requires_api_key(func):
|
| 40 |
+
@wraps(func)
|
| 41 |
+
def decorated(*args, **kwargs):
|
| 42 |
+
api_key = get_api_key()
|
| 43 |
+
if not api_key:
|
| 44 |
+
return jsonify({'detail': 'Not authenticated'}), 401
|
| 45 |
+
kwargs['api_key'] = api_key
|
| 46 |
+
return func(*args, **kwargs)
|
| 47 |
+
return decorated
|
| 48 |
+
|
| 49 |
+
@app.route('/')
|
| 50 |
+
def index():
|
| 51 |
+
return 'Hello, World!'
|
| 52 |
+
|
| 53 |
+
@app.route('/v1/chat/completions', methods=['POST'])
|
| 54 |
+
@requires_api_key
|
| 55 |
+
def chat_completions(api_key):
|
| 56 |
+
logging.info("Received request for chat completions")
|
| 57 |
+
print("requess received")
|
| 58 |
+
try:
|
| 59 |
+
logging.info("Received request for chat completions")
|
| 60 |
+
# Parse and validate request data
|
| 61 |
+
try:
|
| 62 |
+
data = request.get_json()
|
| 63 |
+
chat_request = ChatCompletionRequest(**data)
|
| 64 |
+
except ValidationError as e:
|
| 65 |
+
return jsonify({'detail': e.errors()}), 400
|
| 66 |
+
|
| 67 |
+
# Check API key validity and rate limit
|
| 68 |
+
is_valid, error_message = check_api_key_validity(api_key)
|
| 69 |
+
if not is_valid:
|
| 70 |
+
return jsonify({'detail': error_message}), 401
|
| 71 |
+
|
| 72 |
+
messages = [{"role": msg.role, "content": msg.content} for msg in chat_request.messages]
|
| 73 |
+
|
| 74 |
+
# Get model info
|
| 75 |
+
model_info = get_model_info(chat_request.model)
|
| 76 |
+
if not model_info:
|
| 77 |
+
return jsonify({'detail': 'Invalid model specified'}), 400
|
| 78 |
+
|
| 79 |
+
# Model mapping
|
| 80 |
+
model_mapping = {
|
| 81 |
+
"meta-llama-405b-turbo": "meta-llama/Meta-Llama-3.1-405B-Instruct-Turbo",
|
| 82 |
+
"claude-3.5-sonnet": "claude-3-sonnet-20240229",
|
| 83 |
+
}
|
| 84 |
+
model_name = model_mapping.get(chat_request.model, chat_request.model)
|
| 85 |
+
credits_reduction = {
|
| 86 |
+
"gpt-4o": 1,
|
| 87 |
+
"claude-3-sonnet-20240229": 1,
|
| 88 |
+
"gemini-1.5-pro": 1,
|
| 89 |
+
"gemini-1-5-flash": 1,
|
| 90 |
+
"meta-llama/Meta-Llama-3.1-405B-Instruct-Turbo": 1,
|
| 91 |
+
"o1-mini": 2,
|
| 92 |
+
"o1-preview": 3,
|
| 93 |
+
}.get(model_name, 0)
|
| 94 |
+
|
| 95 |
+
if chat_request.stream:
|
| 96 |
+
def generate():
|
| 97 |
+
try:
|
| 98 |
+
for chunk in API_Inference(messages, model=model_name, stream=True,
|
| 99 |
+
max_tokens=chat_request.max_tokens,
|
| 100 |
+
temperature=chat_request.temperature,
|
| 101 |
+
top_p=chat_request.top_p):
|
| 102 |
+
data = json.dumps({'choices': [{'delta': {'content': chunk}}]})
|
| 103 |
+
yield f"data: {data}\n\n"
|
| 104 |
+
yield f"data: [DONE]\n\nCredits used: {credits_reduction}\n\n"
|
| 105 |
+
update_request_count(api_key, credits_reduction)
|
| 106 |
+
except Exception as e:
|
| 107 |
+
yield f"data: [ERROR] {str(e)}\n\n"
|
| 108 |
+
|
| 109 |
+
return Response(generate(), mimetype='text/event-stream')
|
| 110 |
+
else:
|
| 111 |
+
response = API_Inference(messages, model=model_name, stream=False,
|
| 112 |
+
max_tokens=chat_request.max_tokens,
|
| 113 |
+
temperature=chat_request.temperature,
|
| 114 |
+
top_p=chat_request.top_p)
|
| 115 |
+
update_request_count(api_key, credits_reduction)
|
| 116 |
+
prompt_tokens = sum(len(msg['content'].split()) for msg in messages)
|
| 117 |
+
completion_tokens = len(response.split())
|
| 118 |
+
total_tokens = prompt_tokens + completion_tokens
|
| 119 |
+
return jsonify({
|
| 120 |
+
"id": f"chatcmpl-{str(uuid.uuid4())}",
|
| 121 |
+
"object": "chat.completion",
|
| 122 |
+
"created": int(uuid.uuid1().time // 1e7),
|
| 123 |
+
"model": model_name,
|
| 124 |
+
"choices": [
|
| 125 |
+
{
|
| 126 |
+
"index": 0,
|
| 127 |
+
"message": {
|
| 128 |
+
"role": "assistant",
|
| 129 |
+
"content": response
|
| 130 |
+
},
|
| 131 |
+
"finish_reason": "stop"
|
| 132 |
+
}
|
| 133 |
+
],
|
| 134 |
+
"usage": {
|
| 135 |
+
"prompt_tokens": prompt_tokens,
|
| 136 |
+
"completion_tokens": completion_tokens,
|
| 137 |
+
"total_tokens": total_tokens
|
| 138 |
+
},
|
| 139 |
+
"credits_used": credits_reduction
|
| 140 |
+
})
|
| 141 |
+
except Exception as e:
|
| 142 |
+
return jsonify({'detail': str(e)}), 500
|
| 143 |
+
|
| 144 |
+
@app.route('/rate_limit/status', methods=['GET'])
|
| 145 |
+
@requires_api_key
|
| 146 |
+
def get_rate_limit_status_endpoint(api_key):
|
| 147 |
+
is_valid, error_message = check_api_key_validity(api_key, check_rate_limit=False)
|
| 148 |
+
if not is_valid:
|
| 149 |
+
return jsonify({'detail': error_message}), 401
|
| 150 |
+
return jsonify(get_rate_limit_status(api_key))
|
| 151 |
+
|
| 152 |
+
@app.route('/subscription/status', methods=['GET'])
|
| 153 |
+
@requires_api_key
|
| 154 |
+
def get_subscription_status_endpoint(api_key):
|
| 155 |
+
is_valid, error_message = check_api_key_validity(api_key, check_rate_limit=False)
|
| 156 |
+
if not is_valid:
|
| 157 |
+
return jsonify({'detail': error_message}), 401
|
| 158 |
+
return jsonify(get_subscription_status(api_key))
|
| 159 |
+
|
| 160 |
+
@app.route('/models', methods=['GET'])
|
| 161 |
+
@requires_api_key
|
| 162 |
+
def get_available_models_endpoint(api_key):
|
| 163 |
+
is_valid, error_message = check_api_key_validity(api_key, check_rate_limit=False)
|
| 164 |
+
if not is_valid:
|
| 165 |
+
return jsonify({'detail': error_message}), 401
|
| 166 |
+
return jsonify({"data": [{"id": model} for model in get_available_models().values()]})
|
| 167 |
+
|
| 168 |
+
if __name__ == "__main__":
|
| 169 |
app.run(host="0.0.0.0", port=8000)
|