-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgpt.py
67 lines (49 loc) · 1.73 KB
/
gpt.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
import os
import openai
from flask import jsonify
import tiktoken
encoding = tiktoken.encoding_for_model("gpt-4")
# Awaiting access and full fledged development roadmap
openai.api_key = os.environ["openai_key"]
#start = "Your are a AI Search Engine, answer the following query with a witty answer and include validated facts only."
conversation_history = []
def reset_history_if_needed():
global conversation_history
total_tokens = 0
for message in conversation_history:
try:
tokens = encoding.encode(message["content"])
total_tokens += len(tokens)
except tiktoken.TokenizerException:
pass
if total_tokens > 4000:
conversation_history.clear()
conversation_history.append(system_message)
print("Cleared Conversation History Just Now")
print("Token = " + str(total_tokens))
# Primer prompts
system_message = {
"role":
"system",
"content":
"You are the most accurate and factual search engine on the internet. You are witty and will not answer any harmful or pornographic questions."
}
conversation_history.extend([
system_message
])
def generate(prompt):
global conversation_history
conversation_history.append({"role": "user", "content": prompt})
completions = openai.ChatCompletion.create(
model="gpt-4",
messages=conversation_history,
temperature=0,
top_p=0,
frequency_penalty=0.7,
presence_penalty=0.5)
#stop_sequence = ["\\n"]
#stream = False,
message = completions.choices[0]['message']['content'].strip()
conversation_history.append({"role": "assistant", "content": message})
reset_history_if_needed()
return message