nova-api/checks/client.py

167 lines
4.5 KiB
Python
Raw Normal View History

2023-06-23 02:18:28 +02:00
"""Tests the API."""
2023-07-19 23:51:28 +02:00
import os
2023-08-20 12:46:20 +02:00
import time
import httpx
import openai
import asyncio
import traceback
2023-06-23 02:18:28 +02:00
2023-08-17 16:47:54 +02:00
from rich import print
2023-07-19 23:51:28 +02:00
from typing import List
from dotenv import load_dotenv
load_dotenv()
2023-06-23 02:18:28 +02:00
MODEL = 'gpt-3.5-turbo'
2023-06-23 02:18:28 +02:00
MESSAGES = [
{
'role': 'user',
'content': '1+1=',
}
2023-06-23 02:18:28 +02:00
]
2023-07-19 23:51:28 +02:00
2023-08-24 14:57:36 +02:00
api_endpoint = os.getenv('CHECKS_ENDPOINT', 'http://localhost:2332/v1')
2023-06-23 02:18:28 +02:00
async def test_server():
2023-07-19 23:51:28 +02:00
"""Tests if the API server is running."""
2023-06-23 02:18:28 +02:00
try:
request_start = time.perf_counter()
async with httpx.AsyncClient() as client:
response = await client.get(
url=f'{api_endpoint.replace("/v1", "")}',
timeout=3
)
response.raise_for_status()
assert response.json()['ping'] == 'pong', 'The API did not return a correct response.'
2023-06-23 02:18:28 +02:00
except httpx.ConnectError as exc:
2023-07-19 23:51:28 +02:00
raise ConnectionError(f'API is not running on port {api_endpoint}.') from exc
2023-06-23 02:18:28 +02:00
else:
return time.perf_counter() - request_start
async def test_chat(model: str=MODEL, messages: List[dict]=None) -> dict:
2023-07-19 23:51:28 +02:00
"""Tests an API api_endpoint."""
2023-06-23 02:18:28 +02:00
json_data = {
'model': model,
'messages': messages or MESSAGES,
'stream': False
2023-06-23 02:18:28 +02:00
}
request_start = time.perf_counter()
async with httpx.AsyncClient() as client:
response = await client.post(
url=f'{api_endpoint}/chat/completions',
headers=HEADERS,
json=json_data,
timeout=10,
)
response.raise_for_status()
2023-06-23 02:18:28 +02:00
assert '2' in response.json()['choices'][0]['message']['content'], 'The API did not return a correct response.'
return time.perf_counter() - request_start
2023-06-23 02:18:28 +02:00
async def test_sdxl():
"""Tests the image generation endpoint with the SDXL model."""
json_data = {
'prompt': 'a nice sunset with a samurai standing in the middle',
'n': 1,
'size': '1024x1024'
}
2023-06-23 02:18:28 +02:00
request_start = time.perf_counter()
2023-06-23 02:18:28 +02:00
async with httpx.AsyncClient() as client:
response = await client.post(
url=f'{api_endpoint}/images/generations',
headers=HEADERS,
json=json_data,
timeout=10,
)
response.raise_for_status()
assert '://' in response.json()['data'][0]['url']
return time.perf_counter() - request_start
async def test_models():
"""Tests the models endpoint."""
2023-06-23 02:18:28 +02:00
request_start = time.perf_counter()
async with httpx.AsyncClient() as client:
response = await client.get(
url=f'{api_endpoint}/models',
headers=HEADERS,
timeout=3
)
response.raise_for_status()
res = response.json()
all_models = [model['id'] for model in res['data']]
assert 'gpt-3.5-turbo' in all_models, 'The model gpt-3.5-turbo is not present in the models endpoint.'
return time.perf_counter() - request_start
async def test_api_moderation() -> dict:
"""Tests the moderation endpoint."""
2023-08-15 13:55:12 +02:00
request_start = time.perf_counter()
async with httpx.AsyncClient() as client:
response = await client.post(
url=f'{api_endpoint}/moderations',
headers=HEADERS,
timeout=5,
json={'input': 'fuck you, die'}
)
2023-08-15 13:55:12 +02:00
assert response.json()['results'][0]['flagged'] == True, 'Profanity not detected'
return time.perf_counter() - request_start
2023-08-15 13:55:12 +02:00
# ==========================================================================================
async def demo():
2023-06-23 02:18:28 +02:00
"""Runs all tests."""
try:
for _ in range(30):
if await test_server():
break
2023-06-23 02:18:28 +02:00
print('Waiting until API Server is started up...')
time.sleep(1)
else:
raise ConnectionError('API Server is not running.')
print('[lightblue]Checking if the API works...')
print(await test_chat())
# print('[lightblue]Checking if SDXL image generation works...')
# print(await test_sdxl())
print('[lightblue]Checking if the moderation endpoint works...')
print(await test_api_moderation())
print('[lightblue]Checking the models endpoint...')
print(await test_models())
except Exception as exc:
print('[red]Error: ' + str(exc))
traceback.print_exc()
exit(500)
2023-08-05 02:30:42 +02:00
openai.api_base = api_endpoint
openai.api_key = os.environ['NOVA_KEY']
2023-08-05 02:30:42 +02:00
HEADERS = {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + openai.api_key
}
if __name__ == '__main__':
asyncio.run(demo())