-
Notifications
You must be signed in to change notification settings - Fork 2
/
starchat_interface.py
executable file
·72 lines (62 loc) · 2.38 KB
/
starchat_interface.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
64
65
66
67
68
69
70
71
72
from urllib3 import PoolManager, Timeout
import json
import time
class ApiCallException(Exception):
"""
Generic exception used to report problems
"""
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class NoContentApiCallException(Exception):
"""
Exception used to report problems no content
"""
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class Starchat:
def __init__(self):
self.starchat_url = "http://localhost:8888"
self.post_headers = {'Content-Type': 'application/json'}
self.get_headers = self.post_headers
@staticmethod
def call_api_function(url, method, body=None, headers={'Content-Type': 'application/json'}):
"""
call an API's function and return response
exception: raise an exception if any error occur
:param url: the url
:param method: POST or GET, DELETE
:param body: the body of the request if any
:return: the data structure or None
"""
try:
with PoolManager(retries=5, timeout=Timeout(total=5.0)) as http:
r = http.urlopen(method, url, headers=headers, body=body)
ret_data = (r.status, r.data)
r.close()
except Exception as exc:
e_message = "error getting response from url: " + url
raise ApiCallException(e_message)
else:
if ret_data:
if ret_data[0] == 204:
raise NoContentApiCallException("No content for the call")
try:
structured_res = (ret_data[0], json.loads(ret_data[1].decode("utf-8")))
except ValueError as exc:
e_message = "error parsing response from url: " + url + " : res(" + str(ret_data) + ")"
raise ApiCallException(e_message)
else:
structured_res = None
return structured_res
def get_next_response(self, body):
url = self.starchat_url + "/get_next_response"
headers = self.post_headers
body = body
res = self.call_api_function(url=url, method="POST", body=json.dumps(body), headers=headers)
if res[0] > 299 or res[0] < 200:
print("Error: getting a response:", res)
return res