2023-06-30 02:49:56 +02:00
|
|
|
"""Module for transferring requests to ClosedAI API"""
|
|
|
|
|
2023-06-28 15:21:14 +02:00
|
|
|
import os
|
2023-07-19 23:51:28 +02:00
|
|
|
import json
|
2023-08-04 03:30:56 +02:00
|
|
|
import yaml
|
2023-07-25 02:42:53 +02:00
|
|
|
import logging
|
2023-08-06 21:42:07 +02:00
|
|
|
import fastapi
|
2023-07-25 02:42:53 +02:00
|
|
|
import starlette
|
2023-06-30 02:49:56 +02:00
|
|
|
|
2023-06-28 15:21:14 +02:00
|
|
|
from dotenv import load_dotenv
|
2023-08-03 01:46:49 +02:00
|
|
|
|
2023-08-04 03:30:56 +02:00
|
|
|
import streaming
|
2023-08-06 21:42:07 +02:00
|
|
|
import moderation
|
2023-08-03 01:46:49 +02:00
|
|
|
|
|
|
|
from db import logs, users
|
|
|
|
from helpers import tokens, errors, exceptions
|
2023-06-28 15:21:14 +02:00
|
|
|
|
|
|
|
load_dotenv()
|
|
|
|
|
2023-07-19 23:51:28 +02:00
|
|
|
# log to "api.log" file
|
|
|
|
logging.basicConfig(
|
|
|
|
filename='api.log',
|
|
|
|
level=logging.DEBUG,
|
|
|
|
format='%(asctime)s %(levelname)s %(name)s %(message)s'
|
|
|
|
)
|
|
|
|
|
2023-08-04 03:30:56 +02:00
|
|
|
with open('config/credits.yml', encoding='utf8') as f:
|
|
|
|
credits_config = yaml.safe_load(f)
|
|
|
|
|
2023-08-03 01:46:49 +02:00
|
|
|
async def handle(incoming_request):
|
2023-06-30 02:49:56 +02:00
|
|
|
"""Transfer a streaming response from the incoming request to the target endpoint"""
|
2023-07-25 02:42:53 +02:00
|
|
|
|
2023-08-03 01:46:49 +02:00
|
|
|
path = incoming_request.url.path
|
2023-06-30 02:49:56 +02:00
|
|
|
|
2023-08-04 03:30:56 +02:00
|
|
|
# METHOD
|
2023-08-01 20:19:00 +02:00
|
|
|
if incoming_request.method not in ['GET', 'POST', 'PUT', 'DELETE', 'PATCH']:
|
2023-08-06 21:42:07 +02:00
|
|
|
error = await errors.error(405, f'Method "{incoming_request.method}" is not allowed.', 'Change the request method to the correct one.')
|
|
|
|
return error
|
2023-07-19 23:51:28 +02:00
|
|
|
|
2023-08-04 03:30:56 +02:00
|
|
|
# PAYLOAD
|
2023-07-19 23:51:28 +02:00
|
|
|
try:
|
2023-07-25 02:42:53 +02:00
|
|
|
payload = await incoming_request.json()
|
2023-07-19 23:51:28 +02:00
|
|
|
except json.decoder.JSONDecodeError:
|
2023-07-25 02:42:53 +02:00
|
|
|
payload = {}
|
|
|
|
|
2023-08-04 03:30:56 +02:00
|
|
|
# TOKENS
|
2023-08-01 20:19:00 +02:00
|
|
|
try:
|
2023-08-06 21:42:07 +02:00
|
|
|
input_tokens = await tokens.count_for_messages(payload['messages'])
|
2023-08-03 01:46:49 +02:00
|
|
|
except (KeyError, TypeError):
|
2023-08-01 20:19:00 +02:00
|
|
|
input_tokens = 0
|
|
|
|
|
2023-08-04 03:30:56 +02:00
|
|
|
# AUTH
|
|
|
|
received_key = incoming_request.headers.get('Authorization')
|
2023-08-01 20:19:00 +02:00
|
|
|
|
2023-08-04 03:30:56 +02:00
|
|
|
if not received_key:
|
2023-08-06 21:42:07 +02:00
|
|
|
error = await errors.error(401, 'No NovaAI API key given!', 'Add "Authorization: Bearer nv-..." to your request headers.')
|
|
|
|
return error
|
2023-08-01 20:19:00 +02:00
|
|
|
|
2023-08-04 03:30:56 +02:00
|
|
|
if received_key.startswith('Bearer '):
|
|
|
|
received_key = received_key.split('Bearer ')[1]
|
2023-08-01 20:19:00 +02:00
|
|
|
|
2023-08-04 03:30:56 +02:00
|
|
|
# USER
|
|
|
|
user = await users.by_api_key(received_key.strip())
|
2023-08-01 20:19:00 +02:00
|
|
|
|
|
|
|
if not user:
|
2023-08-06 21:42:07 +02:00
|
|
|
error = await errors.error(401, 'Invalid NovaAI API key!', 'Create a new NovaOSS API key.')
|
|
|
|
return error
|
2023-08-03 01:46:49 +02:00
|
|
|
|
|
|
|
ban_reason = user['status']['ban_reason']
|
|
|
|
if ban_reason:
|
2023-08-06 21:42:07 +02:00
|
|
|
error = await errors.error(403, f'Your NovaAI account has been banned. Reason: "{ban_reason}".', 'Contact the staff for an appeal.')
|
|
|
|
return error
|
2023-08-03 01:46:49 +02:00
|
|
|
|
|
|
|
if not user['status']['active']:
|
2023-08-06 21:42:07 +02:00
|
|
|
error = await errors.error(418, 'Your NovaAI account is not active (paused).', 'Simply re-activate your account using a Discord command or the web panel.')
|
|
|
|
return error
|
2023-08-03 01:46:49 +02:00
|
|
|
|
2023-08-04 03:30:56 +02:00
|
|
|
# COST
|
|
|
|
costs = credits_config['costs']
|
|
|
|
cost = costs['other']
|
2023-08-03 01:46:49 +02:00
|
|
|
|
2023-08-06 21:42:07 +02:00
|
|
|
is_safe = True
|
|
|
|
|
2023-08-04 03:30:56 +02:00
|
|
|
if 'chat/completions' in path:
|
|
|
|
for model_name, model_cost in costs['chat-models'].items():
|
|
|
|
if model_name in payload['model']:
|
|
|
|
cost = model_cost
|
2023-08-03 01:46:49 +02:00
|
|
|
|
2023-08-06 21:42:07 +02:00
|
|
|
is_safe = await moderation.is_safe(payload['messages'])
|
|
|
|
|
|
|
|
else:
|
|
|
|
inp = payload.get('input', payload.get('prompt'))
|
|
|
|
|
|
|
|
if inp and not '/moderations' in path:
|
|
|
|
is_safe = await moderation.is_safe(inp)
|
|
|
|
|
|
|
|
if not is_safe:
|
|
|
|
error = await errors.error(400, 'The request contains content which violates this model\'s policies.', 'We currently don\'t support any NSFW models.')
|
|
|
|
return error
|
|
|
|
|
|
|
|
return
|
|
|
|
|
2023-08-04 03:30:56 +02:00
|
|
|
role_cost_multiplier = credits_config['bonuses'].get(user['role'], 1)
|
|
|
|
cost = round(cost * role_cost_multiplier)
|
2023-08-03 01:46:49 +02:00
|
|
|
|
|
|
|
if user['credits'] < cost:
|
2023-08-06 21:42:07 +02:00
|
|
|
error = await errors.error(429, 'Not enough credits.', 'Wait or earn more credits. Learn more on our website or Discord server.')
|
|
|
|
return error
|
2023-08-01 20:19:00 +02:00
|
|
|
|
2023-08-04 03:30:56 +02:00
|
|
|
# READY
|
2023-06-28 15:21:14 +02:00
|
|
|
|
2023-08-06 21:42:07 +02:00
|
|
|
# payload['user'] = str(user['_id'])
|
2023-07-25 19:45:21 +02:00
|
|
|
|
2023-08-06 00:43:36 +02:00
|
|
|
if 'chat/completions' in path and not payload.get('stream') is True:
|
2023-08-04 03:30:56 +02:00
|
|
|
payload['stream'] = False
|
2023-08-03 03:50:04 +02:00
|
|
|
|
2023-08-06 21:42:07 +02:00
|
|
|
media_type = 'text/event-stream' if payload.get('stream', False) else 'application/json'
|
|
|
|
|
|
|
|
return fastapi.responses.StreamingResponse(
|
2023-08-04 03:30:56 +02:00
|
|
|
content=streaming.stream(
|
|
|
|
user=user,
|
|
|
|
path=path,
|
|
|
|
payload=payload,
|
|
|
|
credits_cost=cost,
|
|
|
|
input_tokens=input_tokens,
|
|
|
|
incoming_request=incoming_request,
|
|
|
|
),
|
2023-08-06 21:42:07 +02:00
|
|
|
media_type=media_type
|
2023-08-04 03:30:56 +02:00
|
|
|
)
|