How to Resolve 500 Internal Server Error in Flask App Using OpenAI API?

Hi everyone,

I’m encountering a 500 Internal Server Error when making requests to the OpenAI API in my Flask application. Here are the details:

  1. Error Details:
  • Console shows: Failed to load resource: the server responded with a status of 500 (INTERNAL SERVER ERROR).
  • The traceback in my Flask app points to the following:

arduino

Copy code

File "/Users/code/PycharmProjects/HasnaGPT/hasna_gpt.py", line 47, in chat
    except openai.error.AuthenticationError as ae:
  • The API request doesn’t seem to go through successfully.
  1. What I’ve Tried:
  • Verified my OpenAI API key is correctly set (sk-... format).
  • Ensured I’m using the latest OpenAI Python library (version 1.58.1).
  • Tested the API key in isolation with a simple Python script, and it works fine.
  • Checked for network connectivity issues, and there doesn’t appear to be any.
  1. Relevant Code Snippet:

python

Copy code

import openai
from flask import Flask, request, jsonify

app = Flask(__name__)
openai.api_key = "your-api-key-here"

@app.route('/chat', methods=['POST'])
def chat():
    try:
        user_input = request.json.get("message")
        response = openai.Completion.create(
            engine="text-davinci-003",
            prompt=user_input,
            max_tokens=100
        )
        return jsonify(response)
    except openai.error.AuthenticationError as ae:
        return jsonify({"error": str(ae)}), 401
    except Exception as e:
        return jsonify({"error": str(e)}), 500
  1. Environment:
  • Python version: 3.13
  • Flask version: Latest
  • OpenAI library version: 1.58.1
  1. Questions:
  • What could be causing the 500 Internal Server Error in this scenario?
  • Could there be an issue with how Flask handles the OpenAI API response or exception?
  • Are there additional debugging steps I should take to identify the root cause?

Any guidance or suggestions would be greatly appreciated. Thank you!

Hi there and welcome to the Forum!

You have used a number of outdated conventions for the OpenAI API call and a deprecated model. Try to the below instead.

from flask import Flask, request, jsonify
from openai import OpenAI
import os

client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY","your API key"))

app = Flask(__name__)

@app.route('/chat', methods=['POST'])
def chat():
    try:
        user_input = request.json.get("message")

        completion = client.chat.completions.create(
            model="gpt-4o",
            messages=[{"role": "user", "content": user_input}],
            max_tokens=300,
            temperature=0.1
        )

        return jsonify({"response": completion.choices[0].message.content})
    
    except Exception as e:
        print("Error:", str(e))
        return jsonify({"error": str(e)}), 500

if __name__ == '__main__':
    app.run(debug=True)
1 Like