from flask import Flask, request, jsonify, render_template
from openai import OpenAI
import os
import logging
client = OpenAI(api_key=os.getenv('OPENAI_API_KEY'))
# Initialize the OpenAI client
# Set up logging
logging.basicConfig(level=logging.DEBUG)
app = Flask(__name__)
# Function to read the knowledge.txt file
def read_knowledge_file():
try:
with open('knowledge.txt', 'r') as file:
knowledge = file.read()
return knowledge
except Exception as e:
logging.error(f"Error reading knowledge file: {e}")
return "Default system message: No knowledge available."
# Generate the initial system message based on knowledge.txt
def generate_initial_system_message():
knowledge_content = read_knowledge_file()
return {
"role": "system",
"content": knowledge_content
}
@app.route('/')
def home():
return render_template('index.html')
@app.route('/chat', methods=['POST'])
def chat():
user_message = request.json.get('message')
# Build the message history
messages = [generate_initial_system_message()]
# User's message
messages.append({"role": "user", "content": user_message})
# Log the messages for debugging
logging.debug(f"Messages: {messages}")
try:
# Call OpenAI API
response = client.chat.completions.create(model="gpt-4o",
messages=messages,
temperature=0.7,
max_tokens=150)
response_message = response.choices[0].message.content
return jsonify({'message': response_message})
except Exception as e:
logging.error(f"Error during OpenAI API call: {e}")
return jsonify({'message': "An error occurred. Please try again later."})
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080)
Hey Welcome to Community.
Do you have any specific question or issue you’re facing? I don’t think anyone would fix your code for you. If you have any specific request or query, do let us know.
Yes. I am originally a music artist so I apologize in advance for my lack of knowledge. I am building an interactive game of sorts to promote my next album using assistants api on replit through a flask app.
The issue I am running into is the fact that the bot never remembers where it is in the conversation. I think I need to do one of two things: create a thread to log the messages between the user and bot or retrieve the working assistant from my playground.
I am completely clueless on how to fix the code I have to make it do one of those two things. Would really appreciate it if someone was willing to help me with this, as I have spent a week fumbling around forums and consulting chat gpt in order to build this.
I am little confused. So you’re already using an Assistant APIs, so I will presume you’ve already created Assistant, Thread, messages, run and having conversation with it. for your question,
Where’s what in the conversation? Are you looking for the messages that go back and forth between you and assistant?