I’m struggling to understand what I’m doing wrong here. The only difference between my code, that I see, and the example is where I am storing the messages. I have a separate file called ‘conversations.json’ that is being kept for persistence.
import os, json, pytz
from dotenv import load_dotenv
from openai import OpenAI
import flask_socketio
from datetime import datetime
load_dotenv()
OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')
client = OpenAI(api_key=OPENAI_API_KEY)
model = "gpt-4o"
### File Handling ###
#####################
# Files
CONVERSATION_FILE = "config/conversation.json"
TOOLS_FILE = "config/tools.json"
### CONVERSATIONS
# Load Conversation
with open(CONVERSATION_FILE, 'r') as file:
conversation = json.load(file)
# Saves Conversation
def save_conversation():
with open(CONVERSATION_FILE, 'w') as file:
json.dump(conversation, file)
### TOOLS
# Current Datetime
def get_datetime(timezone='America/New_York'):
timestamp = datetime.now(pytz.timezone(timezone))
return timestamp.strftime('%A, %B %d, %Y %I:%M:%S %p %Z')
# Load Tools
with open(TOOLS_FILE, 'r') as file:
tools = json.load(file)
### MEMORIES
# Load JSONs
def load_json(input):
try:
with open(input, "r") as file:
data = json.load(file)
return data
except FileNotFoundError:
return []
# Formats the Messages into the required array format for the Chat Completions Model
def message_array(input, role):
conversation.append({'role': role, 'content': input})
save_conversation()
return conversation
### OpenAI API Handling ###
def get_response(data):
user_message = data['message']
message_array(user_message, 'user')
response = client.chat.completions.create(
model=model,
messages=conversation[-5:],
tools=tools,
tool_choice="auto"
)
response_message = response.choices[0].message
response_content = response_message.content
tool_calls = response_message.tool_calls
if response_content:
message_array(response_content, 'assistant')
if tool_calls:
conversation.append(tool_calls)
for tool in tool_calls:
toolbox(tool)
print(conversation[-1:])
second_response = client.chat.completions.create(
model=model,
messages=conversation[-5:],
)
second_response_content = second_response.choices[0].message.content
if second_response_content:
message_array(second_response_content, 'assistant')
flask_socketio.emit('receive_chat', {'message': second_response_content})
return None
else:
flask_socketio.emit('receive_chat', {'message': response_content})
return None
def toolbox(tool):
id = tool.id
function = tool.function
args = function.arguments
name = function.name
if name == "get_datetime":
time = get_datetime()
print(time)
conversation.append(
{
'role': 'tool',
'tool_call_id': id,
'name': name,
'content': time
}
)
save_conversation()
return None