zhe.yang
commited on
Commit
•
ab5ffbd
1
Parent(s):
1e26205
add new
Browse files- conversation.py +32 -0
conversation.py
CHANGED
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import openai
|
2 |
+
import os
|
3 |
+
|
4 |
+
openai.api_key = os.environ.get("OPENAI_API_KEY")
|
5 |
+
|
6 |
+
class Conversation:
|
7 |
+
def __init__(self, prompt, num_of_round):
|
8 |
+
self.prompt = prompt
|
9 |
+
self.num_of_round = num_of_round
|
10 |
+
self.messages = []
|
11 |
+
self.messages.append({"role": "system", "content": self.prompt})
|
12 |
+
|
13 |
+
def ask(self, question):
|
14 |
+
try:
|
15 |
+
self.messages.append({"role": "user", "content": question})
|
16 |
+
response = openai.ChatCompletion.create(
|
17 |
+
model="gpt-3.5-turbo",
|
18 |
+
messages=self.messages,
|
19 |
+
temperature=0.5,
|
20 |
+
max_tokens=2048,
|
21 |
+
top_p=1,
|
22 |
+
)
|
23 |
+
except Exception as e:
|
24 |
+
print(e)
|
25 |
+
return e
|
26 |
+
|
27 |
+
message = response["choices"][0]["message"]["content"]
|
28 |
+
self.messages.append({"role": "assistant", "content": message})
|
29 |
+
|
30 |
+
if len(self.messages) > self.num_of_round*2 + 1:
|
31 |
+
del self.messages[1:3] //Remove the first round conversation left.
|
32 |
+
return message
|