nova-api/api/transfer.py

55 lines
1.5 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
2023-07-25 02:42:53 +02:00
import logging
import starlette
2023-07-25 19:45:21 +02:00
import netclient
2023-06-28 15:21:14 +02:00
from dotenv import load_dotenv
2023-08-01 02:38:55 +02:00
from helpers import requesting
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-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')
2023-07-25 19:45:21 +02:00
target_url = f'{target_endpoint}{incoming_request.url.path}'
2023-07-25 02:42:53 +02:00
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 = {}
if 'temperature' in payload or 'functions' in payload:
target_provider = 'closed'
2023-06-28 15:21:14 +02:00
2023-08-01 02:38:55 +02:00
request = requesting.Request(
2023-07-25 19:45:21 +02:00
url=target_url,
payload=payload,
method=incoming_request.method,
)
return starlette.responses.StreamingResponse(
content=netclient.stream_closedai_request(request)
)