forked from www-Ye/ChatDocuFlow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
openai_operater.py
77 lines (62 loc) · 2.32 KB
/
openai_operater.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
73
74
75
76
77
import openai
import os
import time
class Openai_Operater:
def __init__(self, openai_key, proxy=""):
# Connect to the OpenAI API.
if proxy != "":
os.environ["http_proxy"] = proxy
os.environ["https_proxy"] = proxy
openai.api_key = openai_key
def conversation(self, messages):
while True:
try:
completion = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=messages
)
break
except Exception as e:
print("An error occurred:", e.__class__.__name__)
time.sleep(3)
answer = completion["choices"][0]["message"]["content"]
return answer
def get_gpt_res(self, prompt):
while True:
try:
completion = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": prompt}]
)
break
except Exception as e:
print("An error occurred:", e.__class__.__name__)
time.sleep(3)
res = completion["choices"][0]["message"]["content"]
# print(summary)
return res
def summary_para(self, text, language='Chinese'):
# Summarize the document.
while True:
try:
completion = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": "{}\nSummarize this paragraph in {}:".format(text, language)}]
)
break
except Exception as e:
print("An error occurred:", e.__class__.__name__)
time.sleep(3)
summary = completion["choices"][0]["message"]["content"]
# print(summary)
return summary
def get_embedding(self, text, model="text-embedding-ada-002"):
text = text.replace("\n", " ")
while True:
try:
emb = openai.Embedding.create(input = [text], model=model)['data'][0]['embedding']
break
except Exception as e:
print("An error occurred:", e.__class__.__name__)
time.sleep(3)
return emb