Django RuntimeError: Event loop is closed with OpenAI

Generated but ran through my builder AI it analyzed with no errors.
There are a couple of potential issues or improvements that can be noted in your code:

  1. Missing return statement: The function create_completion_message should return the response or processed data. Currently, there is no return statement.

    return response_message
    
  2. Ensure client initialization: Ensure that cls.__client.chat.completions.create is initialized and available. If __client is not initialized properly before calling this method, it will raise an AttributeError.

  3. Correct usage of *history: The *history syntax should only be used if history is a list or iterable. Ensure that history is a list of messages (dictionaries) and not some other data structure.

  4. Handling errors: It’s a good practice to handle possible errors like network issues, timeouts, or invalid responses.

  5. Async Function Error Handling: Since the function is async, it’s beneficial to use a try/except block to catch and handle exceptions such as aiohttp.ClientError or any custom errors that might arise when making async API calls.

Here is a revised version that addresses these potential issues:

@classmethod
async def create_completion_message(cls, history):
    try:
        response = await cls.__client.chat.completions.create(
            model='gpt-4o-mini',
            messages=[
               *history,
            ]
        )
        response_message = response.choices[0].message.content
        return response_message
    except Exception as e:
        # Log or handle error
        print(f"An error occurred: {e}")
        return None

This version adds error handling, ensures the response is returned, and prints any exceptions if something goes wrong.