-
Notifications
You must be signed in to change notification settings - Fork 0
/
02_chathistory.py
64 lines (45 loc) · 1.57 KB
/
02_chathistory.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
from dotenv import load_dotenv
import os
from openai import OpenAI
load_dotenv()
OPENAI_ORG_ID = os.environ["OPENAI_ORG_ID"]
OPENAI_PROJECT_ID = os.environ["OPENAI_PROJECT_ID"]
OPENAI_API_KEY = os.environ["OPENAI_API_KEY"]
MODEL = "gpt-3.5-turbo"
TEMPERATURE = 0.1
client = OpenAI(
organization=OPENAI_ORG_ID,
project=OPENAI_PROJECT_ID,
api_key=OPENAI_API_KEY
)
class MessageHistory:
def __init__(self, system_message: str, n: int) -> None:
self.history = [{"role": "system", "content": system_message}]
self.n = n
def add_message(self, message_type, message_text):
self.history.append({"role": message_type, "content": message_text})
if len(self.history) > self.n:
self.history.pop(1)
def add_user_message(self, message):
self.add_message("user", message)
def add_ai_message(self, message):
self.add_message("assistant", message)
def get_messages(self) -> list[dict]:
return self.history
message_history = MessageHistory(
system_message="You are a helpful assistant.", n=5)
def call_ai(message):
message_history.add_user_message(message=message)
response = client.chat.completions.create(
model=MODEL,
messages=message_history.get_messages(),
temperature=TEMPERATURE)
ai_message = response.choices[0].message.content
message_history.add_ai_message(ai_message)
return ai_message
while True:
user_message = input("You: ")
if user_message == "quit":
break
ai_message = call_ai(user_message)
print("AI :", ai_message)