forked from santhosh-tg/jugalbandi-api
-
Notifications
You must be signed in to change notification settings - Fork 4
/
query_with_gptindex.py
49 lines (45 loc) · 2.02 KB
/
query_with_gptindex.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
import openai
from gpt_index import GPTSimpleVectorIndex, SimpleDirectoryReader
from cloud_storage import *
def querying_with_gptindex(uuid_number, query):
files_count = read_given_file(uuid_number, "index.json")
if files_count:
index = GPTSimpleVectorIndex.load_from_disk("index.json")
try:
response = index.query(query)
source_node = response.source_nodes
source_text = ""
if len(source_node):
source_text = source_node[0].source_text
os.remove("index.json")
return str(response).strip(), source_text.strip(), None, 200
except openai.error.RateLimitError as e:
error_message = f"OpenAI API request exceeded rate limit: {e}"
status_code = 500
except (openai.error.APIError, openai.error.ServiceUnavailableError):
error_message = "Server is overloaded or unable to answer your request at the moment. Please try again later"
status_code = 503
except Exception as e:
error_message = str(e.__context__) + " and " + e.__str__()
status_code = 500
else:
error_message = "The UUID number is incorrect"
status_code = 422
return None, None, error_message, status_code
def gpt_indexing(uuid_number):
try:
documents = SimpleDirectoryReader(uuid_number).load_data()
index = GPTSimpleVectorIndex(documents)
index.save_to_disk("index.json")
error_message = None
status_code = 200
except openai.error.RateLimitError as e:
error_message = f"OpenAI API request exceeded rate limit: {e}"
status_code = 500
except (openai.error.APIError, openai.error.ServiceUnavailableError):
error_message = "Server is overloaded or unable to answer your request at the moment. Please try again later"
status_code = 503
except Exception as e:
error_message = str(e.__context__) + " and " + e.__str__()
status_code = 500
return error_message, status_code