Spaces:
Runtime error
Runtime error
| import os | |
| from openai import OpenAI | |
| from flask import Flask, request, jsonify, render_template | |
| app = Flask(__name__) | |
| # β Get the API key from environment variables | |
| api_key = os.getenv("OPENAI_API_KEY") | |
| if not api_key: | |
| print("WARNING: OPENAI_API_KEY is not set. Chat functionality will not work.") | |
| client = None | |
| else: | |
| try: | |
| from openai import OpenAI | |
| client = OpenAI(api_key=api_key) | |
| except Exception as e: | |
| print(f"Error initializing OpenAI client: {e}") | |
| client = None | |
| def home(): | |
| """Serve the chat web interface""" | |
| return render_template('index.html') | |
| def chat(): | |
| try: | |
| if not client: | |
| return jsonify({"error": "OpenAI API key not configured"}), 500 | |
| data = request.json | |
| user_message = data.get("message", "") | |
| if not user_message: | |
| return jsonify({"error": "Message is required"}), 400 | |
| # Use the new OpenAI client | |
| response = client.chat.completions.create( | |
| model="gpt-3.5-turbo", | |
| messages=[{"role": "user", "content": user_message}], | |
| temperature=0.7, | |
| max_tokens=1000 | |
| ) | |
| reply = response.choices[0].message.content | |
| return jsonify({"reply": reply}) | |
| except Exception as e: | |
| return jsonify({"error": str(e)}), 500 | |
| def health(): | |
| """Health check endpoint""" | |
| return jsonify({"status": "healthy", "service": "ThutoAI"}) | |
| if __name__ == "__main__": | |
| app.run(host="0.0.0.0", port=7860) |