Hello, fairly new to chatGPT API, I have been working on chatGPT to have an authentic NPC conversation in my game. The code is in Python and is supposed to remember what we talked about before.
It works… until the total token count hits 800~, then if I don’t remove the previous messages, AI resets fully, and doesn’t remember anything. Which is like 2~3 messages.
The function block looks like this, around the last lines, if I don’t set “max_tokens_limit” to 800. the conversation keeps resetting.
The “gpt-3.5-turbo-16k” is supposed to have a ‘16385’ token limit, however, the conversation is resetting every 2~3 prompts, around where it reaches 800~ tokens used.
Does anyone know what I am doing wrong??
client = OpenAI(api_key="sk--------------")
messages = [
{"role": "system", "content": systemRoleMssg},
{"role": "user", "content": userInitilizingMssg}
]
max_tokens_limit = 16385
def sendMssgToChatGPT(text_MSG):##insert prompt here
# Initialize messages list if it doesn't exist
if "messages" not in globals():
global messages
messages = []
# Append user message
messages.append({"role": "user", "content": text_MSG})
# Generate completion
completion = client.chat.completions.create(
model="gpt-3.5-turbo-16k",
messages=messages,
max_tokens=300
)
# Get model response
model_response = completion.choices[0].message.content
# NPC or chatGPT is saying this:
print(model_response)
# Append assistant response
messages.append({"role": "assistant", "content": model_response})
# Calculate total tokens
total_tokens = sum(len(message["content"].split()) if "content" in message else 0 for message in messages)
# Remove older messages if the token limit is reached
while total_tokens > (max_tokens_limit): ##If I don't change max_tokens_limit = 800, chatGPT refreshes after hitting 800, although tokens keep increasing
removed_message = messages.pop(1)
total_tokens -= len(removed_message["content"].split()) if "content" in removed_message else 0