nova-api/api/transfer.py

61 lines
1.6 KiB
Python
Raw Normal View History

"""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
import aiohttp
2023-07-25 02:42:53 +02:00
import logging
import starlette
import netclient
import proxies
2023-06-28 15:21:14 +02:00
from dotenv import load_dotenv
2023-07-25 02:42:53 +02:00
from starlette.background import StreamingResponse
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'
)
logging.info('API started')
2023-06-28 15:21:14 +02:00
EXCLUDED_HEADERS = [
'content-encoding',
'content-length',
'transfer-encoding',
'connection'
]
2023-07-25 02:42:53 +02:00
async def handle_api_request(incoming_request, target_endpoint: str=''):
"""Transfer a streaming response from the incoming request to the target endpoint"""
2023-07-25 02:42:53 +02:00
if not target_endpoint:
target_endpoint = os.getenv('CLOSEDAI_ENDPOINT')
target_url = f'{target_endpoint}{incoming_request.url.path}'.replace('/v1/v1', '/v1')
logging.info('TRANSFER %s -> %s', incoming_request.url.path, target_url)
if target_url.endswith('/v1'):
return starlette.responses.Response(status_code=200, content='200. /v1 is the API endpoint root path.')
2023-07-19 23:51:28 +02:00
if incoming_request.headers.get('Authorization') != f'Bearer {os.getenv("DEMO_AUTH")}':
2023-07-25 02:42:53 +02:00
return starlette.responses.Response(status_code=403, content='Invalid API key')
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 = {}
target_provider = 'moe'
if 'temperature' in payload or 'functions' in payload:
target_provider = 'closed'
2023-06-28 15:21:14 +02:00
return StreamingResponse(
2023-07-25 02:42:53 +02:00
content=netclient.receive_target_stream()
)