-
Notifications
You must be signed in to change notification settings - Fork 8
/
chatgpt.py
66 lines (55 loc) · 2.11 KB
/
chatgpt.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
import openai
import re
import json
import requests
OPENAI_API_KEY = "API_KEY"
class GPT:
def __init__(self, id):
self.id = id
self.file_name = f"{str(self.id)}.json"
self.session = {
"start": True,
"data": "Hi there! My name is RajGPT, and I'm here to help you with anything , you can ask me any question",
"log": [
{
"role": "system",
"content": "You are a helpful assistant",
},
{
"role": "assistant",
"content": "Hi there! My name is RajGPT, and I'm here to help you with anything , you can ask me any question",
},
],
}
try:
with open(self.file_name) as outfile:
data = json.load(outfile)
outfile.close()
self.session = data
except Exception:
with open(self.file_name, "w") as outfile:
json.dump(self.session, outfile)
outfile.close()
def bot(self, input_query):
if self.session["start"]:
self.session["start"] = False
with open(self.file_name, "w") as outfile:
json.dump(self.session, outfile)
outfile.close()
return "Hi there! My name is RajGPT, and I'm here to help you with anything , you can ask me any question"
openai.api_key = OPENAI_API_KEY
self.session["log"].append({"role": "user", "content": input_query})
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=self.session["log"],
temperature=0.8,
max_tokens=800,
top_p=1,
)
res = response["choices"][0]["message"]["content"]
self.session["log"].append({"role": "assistant", "content": res})
self.session["data"] += res + " \n "
with open(self.file_name, "w") as jsonFile:
json.dump(self.session, jsonFile)
jsonFile.close()
return res