-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathopenai_helper.py
61 lines (55 loc) · 1.85 KB
/
openai_helper.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
import requests
import json
class OpenAIHelper:
def __init__(self, api_key, api_base="api.openai.one"):
self.api_key = api_key
self.api_base = api_base
def ask_openai_common(self, prompt):
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {self.api_key}"
}
data = {
"model": "gpt-4-turbo",
"messages": [
{
"role": "user",
"content": prompt
}
]
}
response = requests.post(f'https://{self.api_base}/v1/chat/completions', headers=headers, json=data)
try:
response_json = response.json()
except Exception as e:
return ''
if 'choices' not in response_json:
return ''
return response_json['choices'][0]['message']['content']
def ask_openai_for_json(self, prompt):
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {self.api_key}"
}
data = {
"model": "gpt-4-turbo",
"response_format": { "type": "json_object" },
"messages": [
{
"role": "system",
"content": "You are a helpful assistant designed to output JSON."
},
{
"role": "user",
"content": prompt
}
]
}
response = requests.post(f'https://{self.api_base}/v1/chat/completions', headers=headers, json=data)
try:
response_json = response.json()
except json.JSONDecodeError:
return ''
if 'choices' not in response_json:
return ''
return response_json['choices'][0]['message']['content']