nova-api/api/helpers/chat.py

66 lines
1.3 KiB
Python
Raw Normal View History

2023-08-05 02:30:42 +02:00
import json
2023-08-04 17:29:49 +02:00
import string
import random
import asyncio
from rich import print
class CompletionStart:
"""Beinning of a chat"""
class CompletionStop:
"""End of a chat"""
async def create_chat_id() -> str:
2023-08-12 17:49:31 +02:00
"""Generates a random chat ID"""
2023-08-04 17:29:49 +02:00
chars = string.ascii_letters + string.digits
chat_id = ''.join(random.choices(chars, k=32))
return f'chatcmpl-{chat_id}'
2023-08-06 21:42:07 +02:00
async def create_chat_chunk(chat_id: str, model: str, content=None) -> dict:
2023-08-12 17:49:31 +02:00
"""Creates a new chat chunk"""
2023-08-04 17:29:49 +02:00
content = content or {}
delta = {}
if content:
delta = {
'content': content
}
2023-08-05 02:30:42 +02:00
if content == CompletionStart:
2023-08-04 17:29:49 +02:00
delta = {
'role': 'assistant'
}
2023-08-05 02:30:42 +02:00
if content == CompletionStop:
delta = {}
2023-08-04 17:29:49 +02:00
chunk = {
'id': chat_id,
'object': 'chat.completion.chunk',
'created': 0,
'model': model,
'choices': [
{
'delta': delta,
'index': 0,
2023-08-05 02:30:42 +02:00
'finish_reason': 'stop' if content == CompletionStop else None
2023-08-04 17:29:49 +02:00
}
],
}
2023-08-05 02:30:42 +02:00
return f'data: {json.dumps(chunk)}\n\n'
2023-08-04 17:29:49 +02:00
if __name__ == '__main__':
demo_chat_id = asyncio.run(create_chat_id())
print(demo_chat_id)
print(asyncio.run(create_chat_chunk(
model='gpt-4',
content='Hello',
chat_id=demo_chat_id,
)))