Hi,
I have created a bot to work with Discord but I am having some issues with not receiving any responses from the Assistant API after usually 1-2 questions, what can it be? Appreciate all the help,
I have attached the parts of the files from Terminal and also the code:
import os
import discord
from discord.ext import commands
import openai
import asyncio
from flask import Flask
from threading import Thread
import json
from prompts import assistant_instructions
import time # Import the time module
# Flask server setup to keep Replit active
app = Flask('')
@app.route('/')
def home():
return "The bot is running"
def run():
app.run(host='0.0.0.0', port=8080)
def keep_alive():
t = Thread(target=run)
t.start()
# Load your API keys from environment variables
openai.api_key = os.getenv('OPENAI_API_KEY')
discord_bot_token = os.getenv('DISCORD_BOT_TOKEN')
# Initialize the OpenAI client
client = openai.OpenAI()
# Define the needed Discord intents for the bot to function properly
intents = discord.Intents.default()
intents.messages = True # Enables receiving messages
intents.message_content = True # Enables receiving message content
intents.guilds = True # Enables guild-related events, necessary for the bot to function in servers
# Initialize the Discord bot with the specified intents
bot = commands.Bot(command_prefix="!", intents=intents)
# Global variable for the OpenAI assistant instance
assistant_instance = None
# Dictionary to store thread IDs for each Discord user or channel
thread_ids = {}
# Function to create or load the OpenAI assistant
def create_or_load_assistant():
assistant_file_path = 'assistant.json'
if os.path.exists(assistant_file_path):
with open(assistant_file_path, 'r') as file:
assistant_data = json.load(file)
return assistant_data['assistant_id']
else:
file_names = [
"SEO1.pdf", "SEO2.pdf", "SEO3.pdf", "SEO4.pdf", "SEO5.pdf", "SEO6.pdf",
"SEO7.pdf", "SEO8.pdf", "SEO9.pdf", "SEO10.pdf"
] # Add your file names here
file_ids = []
for file_name in file_names:
with open(file_name, "rb") as file:
uploaded_file = client.files.create(file=file, purpose='assistants')
file_ids.append(uploaded_file.id)
assistant = client.beta.assistants.create(
name="SEO Tutor",
instructions=assistant_instructions,
model="gpt-4-1106-preview",
tools=[{
"type": "retrieval"
}],
file_ids=file_ids)
with open(assistant_file_path, 'w') as file:
json.dump({'assistant_id': assistant.id}, file)
return assistant.id
# Get the OpenAI assistant instance
def get_assistant():
global assistant_instance
if assistant_instance is None:
assistant_instance = create_or_load_assistant()
return assistant_instance
@bot.event
async def on_ready():
print(f'{bot.user} has connected to Discord!')
@bot.command(name='SEO')
async def assist(ctx, *, question: str):
try:
print(f"[Log] Processing question: {question}")
user_id = ctx.author.id
if user_id not in thread_ids:
print("[Log] Creating new thread for user")
thread = openai.beta.threads.create()
thread_ids[user_id] = {'thread_id': thread.id, 'last_msg_id': None}
print(f"[Log] New thread created with ID: {thread.id}")
thread_info = thread_ids[user_id]
thread_id = thread_info['thread_id']
print(f"[Log] Sending question to thread {thread_id}")
message = openai.beta.threads.messages.create(thread_id=thread_id, role="user", content=question)
print(f"[Log] Message sent: {message.id}")
assistant_id = get_assistant()
print(f"[Log] Using assistant ID: {assistant_id}, initiating run")
run = openai.beta.threads.runs.create(thread_id=thread_id, assistant_id=assistant_id)
print(f"[Log] Run initiated with ID: {run.id}")
print("[Log] Waiting for assistant's response")
start_time = time.time()
while time.time() - start_time < 30: # 30 seconds timeout
run_status = openai.beta.threads.runs.retrieve(thread_id=thread_id, run_id=run.id)
print(f"[Log] Run status: {run_status.status}")
if run_status.status == 'completed':
break
await asyncio.sleep(1)
if run_status.status != 'completed':
print("[Log] Run did not complete in time.")
await ctx.send("Response is taking longer than expected. Please try again later.")
return
print("[Log] Fetching messages")
messages = openai.beta.threads.messages.list(thread_id=thread_id)
new_messages = [msg for msg in messages.data if msg.role == 'assistant' and (thread_info['last_msg_id'] is None or msg.id > thread_info['last_msg_id'])]
if not new_messages:
print("[Log] No new messages received from the assistant")
await ctx.send("No response received. Please try again.")
return
for msg in new_messages:
content = msg.content[0].text.value
thread_info['last_msg_id'] = msg.id # Update the last message ID
if not content:
content = "I'm sorry, but I don't have enough information to answer that right now."
print(f"[Log] Sending response to Discord: {content[:50]}...")
chunks = [content[i:i + 2000] for i in range(0, len(content), 2000)]
for chunk in chunks:
await ctx.send(chunk)
except Exception as e:
print(f"[Error] An error occurred: {e}")
await ctx.send(f'An error occurred: {e}')
# Call the function to keep the server alive
keep_alive()
# Run the bot
bot.run(discord_bot_token)
Terminal response:
Log] Processing question: what is 1+1?
[Log] Creating new thread for user
[Log] New thread created with ID: thread_KEqJ4ceGfYjsXW5brM9NMWRh
[Log] Sending question to thread thread_KEqJ4ceGfYjsXW5brM9NMWRh
[Log] Message sent: msg_MK0PvZVAa5rCzSG1pcT1sSqw
[Log] Using assistant ID: asst_(delete from me), initiating run
[Log] Run initiated with ID: run_gY1ebsxXUfz3RsX495Qbj8OH
[Log] Waiting for assistant’s response
[Log] Run status: in_progress
[Log] Run status: in_progress
[Log] Run status: completed
[Log] Fetching messages
[Log] Sending response to Discord: 1+1 equals 2. If you have any SEO related question…
[Log] Processing question: what is 22+44?
[Log] Sending question to thread thread_KEqJ4ceGfYjsXW5brM9NMWRh
[Log] Message sent: msg_oV0TDOnRrTaE2A60nZ9FbcYC
[Log] Using assistant ID: asst_(delete from me), initiating run
[Log] Run initiated with ID: run_wH7EMGaGUEmJMbeQGGaACc9N
[Log] Waiting for assistant’s response
[Log] Run status: in_progress
[Log] Run status: in_progress
[Log] Run status: in_progress
[Log] Run status: completed
[Log] Fetching messages
[Log] Sending response to Discord: 22 + 44 equals 66. If you’re looking for SEO tips …
[Log] Processing question: what is 67+88?
[Log] Sending question to thread thread_KEqJ4ceGfYjsXW5brM9NMWRh
[Log] Message sent: msg_DgdthfeGcp85139zkQO3sR7i
[Log] Using assistant ID: asst_(delete from me), initiating run
[Log] Run initiated with ID: run_SJsiX4HEdZWZVObsIGfMwBVT
[Log] Waiting for assistant’s response
[Log] Run status: in_progress
[Log] Run status: in_progress
[Log] Run status: in_progress
[Log] Run status: in_progress
[Log] Run status: completed
[Log] Fetching messages
[Log] No new messages received from the assistant
can anyone please help? I am kinda lost!