Error from OpenAI: Status code 404

Hello, I’m a beginner in programming and I planned to add an assistant to my Telegram bot. I tried adding ChatGPT without any issues, but when attempting to add the assistant (specifying its parameters including the model beforehand), I constantly encounter the same error. I double-checked all the parameters, generated a new API key, and also obtained a new assistant ID. Here’s my code for verification, thank you in advance.

import logging
from aiogram import Bot, Dispatcher, executor, types
import json
import aiohttp
from sqlalchemy import create_engine, Column, Integer, String, Text
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm import declarative_base

Load configuration

with open(‘config.json’) as config_file:
config = json.load(config_file)

Configure logging

logging.basicConfig(level=logging.INFO)

Initialize bot and dispatcher

bot = Bot(token=config[“=BOT_TOKEN”])
dp = Dispatcher(bot)

Connect to the database

engine = create_engine(‘sqlite:///users.db’)
Base = declarative_base()

class User(Base):
tablename = ‘users’
id = Column(Integer, primary_key=True)
user_id = Column(Integer, unique=True)
messages = Column(Text)

Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
db_session = Session()

async def send_openai_request(path: str, method: str = ‘POST’, json: dict = None):
“”“Sends a request to OpenAI.”“”
url = f’/api.openai.com/v1{path}‘’
headers = {
‘Content-Type’: ‘application/json’,
‘Authorization’: f’Bearer {config[“OPENAI_API_KEY”]}',
‘OpenAI-Beta’: ‘assistants=v1’
}
async with aiohttp.ClientSession() as session:
async with session.request(method, url, headers=headers, json=json) as resp:
if resp.status == 200:
return await resp.json()
else:
logging.error(f"Error from OpenAI: Status code {resp.status}, Response: {await resp.text()}")
return None

async def get_assistant_response(prompt, user_id):
response = await send_openai_request(
path=f"/assistants/{config[‘ASSISTANT_ID’]}/messages",
json={“input”: {“type”: “text”, “data”: prompt}, “assistant_id”: config[‘ASSISTANT_ID’]}
)
if response:
# Assumes that the API returns the response text in a suitable format
return response.get(‘choices’, [{}])[0].get(‘message’, ‘Sorry, I cannot process the request.’)
return “Sorry, I cannot process your request right now.”

@dp.message_handler(commands=[‘start’, ‘help’])
async def send_welcome(message: types.Message):
await message.reply(“Hello! I’m your assistant. How can I help you today?”)

@dp.message_handler()
async def handle_message(message: types.Message):
await bot.send_chat_action(message.chat.id, types.ChatActions.TYPING)
user_input = message.text
response = await get_assistant_response(user_input, message.from_user.id)
await message.answer(response)

if name == ‘main’:
executor.start_polling(dp, skip_updates=True)

UPD: I also checked the assistants available to me - everything is in order.

You picked the wrong day to mess with assistants - it was basically down for 10 hours (but not throwing 404s)

If you edit your post and enclose your code in “```python” (using backticks) and then close it with ```, we might be able to read it…

Life will also be easier with the openai python module. It doesn’t mess up URLs.

Try this…

import logging
from aiogram import Bot, Dispatcher, executor, types
import json
import aiohttp
from sqlalchemy import create_engine, Column, Integer, String, Text
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

# Load configuration
with open('config.json') as config_file:
    config = json.load(config_file)

# Configure logging
logging.basicConfig(level=logging.INFO)

# Initialize bot and dispatcher
bot = Bot(token=config["BOT_TOKEN"])
dp = Dispatcher(bot)

# Connect to the database
engine = create_engine('sqlite:///users.db')
Base = declarative_base()

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    user_id = Column(Integer, unique=True)
    messages = Column(Text)

Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
db_session = Session()

async def send_openai_request(path: str, method: str = 'POST', json: dict = None):
    """Sends a request to OpenAI."""
    url = f'https://api.openai.com/v1{path}'
    headers = {
        'Content-Type': 'application/json',
        'Authorization': f'Bearer {config["OPENAI_API_KEY"]}',
        'OpenAI-Beta': 'assistants=v1'
    }
    async with aiohttp.ClientSession() as session:
        async with session.request(method, url, headers=headers, json=json) as resp:
            if resp.status == 200:
                return await resp.json()
            else:
                logging.error(f"Error from OpenAI: Status code {resp.status}, Response: {await resp.text()}")
                return None

if __name__ == '__main__':
    executor.start_polling(dp, skip_updates=True)