An error occurred while communicating with OpenAI? how do I fix this? Am using a Personal API Key, not using a Project Key. It was working fine, randomly this error is showing.
import os
import discord
import openai
import aiohttp
import json
import asyncio
TOKEN = os.getenv(‘TOKEN’)
OPENAI_API_KEY = os.getenv(‘GPT’)
intents = discord.Intents.all()
client = discord.Client(intents=intents)
session = None
original_queries = {}
response_messages = {}
async def ask_chatgpt(question, chat_model=“gpt-4”):
global session
try:
async with session.post(
“https://api.openai.com/v1/chat/completions”,
headers={
“Authorization”: f"Bearer {OPENAI_API_KEY}“,
“Content-Type”: “application/json”
},
data=json.dumps({
“model”:
chat_model,
“messages”: [{
“role”:
“system”,
“content”:
“You are a specialized assistant”
}, {
“role”: “user”,
“content”: question
}]
})) as response:
if response.status == 200:
data = await response.json()
return data[‘choices’][0][‘message’][‘content’].strip()
else:
return “An error occurred while communicating with OpenAI.”
except Exception as e:
return f"An error occurred: {str(e)}”