import openai import os from flask import Flask, request, jsonify, render_template app = Flask(__name__) # Set your OpenAI API key openai.api_key = os.getenv("OPENAI_API_KEY") @app.route('/') def home(): return render_template('index.html') @app.route('/chat', methods=['POST']) def chat(): user_message = request.json.get("message") if not user_message: return jsonify({"error": "Empty message received"}) try: client = openai.OpenAI() # New API usage response = client.chat.completions.create( model="gpt-3.5-turbo", messages=[{"role": "user", "content": user_message}] ) reply = response.choices[0].message.content return jsonify({"reply": reply}) except openai.OpenAIError as e: print(f"OpenAI API Error: {e}") # Print error for debugging return jsonify({"reply": f"Error in response: {str(e)}"}) # Show error in UI if __name__ == '__main__': app.run(host='0.0.0.0', port=7860)