2023-08-03 01:46:49 +02:00
|
|
|
import os
|
2023-08-03 03:50:04 +02:00
|
|
|
import time
|
2023-08-03 01:46:49 +02:00
|
|
|
|
|
|
|
from dotenv import load_dotenv
|
|
|
|
from motor.motor_asyncio import AsyncIOMotorClient
|
|
|
|
|
2023-08-04 03:30:56 +02:00
|
|
|
from helpers import network
|
|
|
|
|
2023-08-03 01:46:49 +02:00
|
|
|
load_dotenv()
|
|
|
|
|
|
|
|
def _get_mongo(collection_name: str):
|
|
|
|
return AsyncIOMotorClient(os.getenv('MONGO_URI'))['nova-core'][collection_name]
|
|
|
|
|
2023-08-04 03:30:56 +02:00
|
|
|
async def log_api_request(user: dict, incoming_request, target_url: str):
|
|
|
|
payload = await incoming_request.json()
|
2023-08-03 01:46:49 +02:00
|
|
|
|
|
|
|
last_prompt = None
|
|
|
|
if 'messages' in payload:
|
|
|
|
last_prompt = payload['messages'][-1]['content']
|
|
|
|
|
2023-08-04 03:30:56 +02:00
|
|
|
model = payload.get('model')
|
2023-08-04 17:29:49 +02:00
|
|
|
ip_address = await network.get_ip(incoming_request)
|
2023-08-03 01:46:49 +02:00
|
|
|
|
|
|
|
new_log_item = {
|
2023-08-03 03:50:04 +02:00
|
|
|
'timestamp': time.time(),
|
2023-08-04 03:30:56 +02:00
|
|
|
'method': incoming_request.method,
|
|
|
|
'path': incoming_request.url.path,
|
2023-08-03 01:46:49 +02:00
|
|
|
'user_id': user['_id'],
|
|
|
|
'security': {
|
2023-08-04 17:29:49 +02:00
|
|
|
'ip': ip_address,
|
2023-08-04 03:30:56 +02:00
|
|
|
'useragent': incoming_request.headers.get('User-Agent')
|
2023-08-03 01:46:49 +02:00
|
|
|
},
|
|
|
|
'details': {
|
|
|
|
'model': model,
|
|
|
|
'last_prompt': last_prompt,
|
|
|
|
'target_url': target_url
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
inserted = await _get_mongo('logs').insert_one(new_log_item)
|
|
|
|
log_item = await _get_mongo('logs').find_one({'_id': inserted.inserted_id})
|
|
|
|
return log_item
|
|
|
|
|
|
|
|
async def by_id(log_id: str):
|
|
|
|
return await _get_mongo('logs').find_one({'_id': log_id})
|
|
|
|
|
|
|
|
async def by_user_id(user_id: str):
|
|
|
|
return await _get_mongo('logs').find({'user_id': user_id})
|
|
|
|
|
|
|
|
async def delete_by_id(log_id: str):
|
|
|
|
return await _get_mongo('logs').delete_one({'_id': log_id})
|
|
|
|
|
|
|
|
async def delete_by_user_id(user_id: str):
|
|
|
|
return await _get_mongo('logs').delete_many({'user_id': user_id})
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
pass
|