-
Notifications
You must be signed in to change notification settings - Fork 0
/
api_functions.py
63 lines (50 loc) · 1.94 KB
/
api_functions.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
from config import HOST, URI, URI_STREAM
from file_import import requests, websockets, json, re
def extract_name(text, standard_name):
match = re.search(r"Name: (.*?)\n", text)
if match:
name = match.group(1).strip() # .strip() to remove any leading/trailing white spaces
if name == "Unknown" or name == standard_name:
return standard_name
else:
return name
else:
return standard_name
def remove_prefix(text, prefix="Dear "):
text = text.strip()
if text.startswith(prefix):
remaining_text = text[text.index(",") + 1:].lstrip()
return remaining_text if remaining_text else None
else:
return text
# Function to get the token count of a given text
async def get_token_count(text):
token_count_uri = f'http://{HOST}/api/v1/token-count'
request_token = {'prompt': text}
response = requests.post(token_count_uri, json=request_token)
if response.status_code == 200:
return response.json()['results'][0]['tokens']
else:
print(f"Error {response.status_code}: {response.text}")
return None
# Function to make HTTP API call
async def complete(prompt, request):
request['prompt'] = prompt
response = requests.post(URI, json=request)
if response.status_code == 200:
result = response.json()['results'][0]['text']
else:
print("answer not properly returned")
return result
async def stream_complete(prompt, request):
#print(prompt)
request['prompt'] = prompt
async with websockets.connect(URI_STREAM, ping_interval=None) as websocket:
await websocket.send(json.dumps(request))
while True:
incoming_data = await websocket.recv()
incoming_data = json.loads(incoming_data)
if incoming_data['event'] == 'text_stream':
yield incoming_data['text']
elif incoming_data['event'] == 'stream_end':
return