Spaces:
Runtime error
Runtime error
| import os | |
| import openai | |
| from flask import Flask, request, jsonify | |
| app = Flask(__name__) | |
| # β Get the API key from environment variables | |
| openai.api_key = os.getenv("OPENAI_API_KEY") | |
| if not openai.api_key: | |
| raise ValueError("β OPENAI_API_KEY is not set. Go to Hugging Face > Settings > Variables and Secrets and add it there.") | |
| def chat(): | |
| try: | |
| data = request.json | |
| user_message = data.get("message", "") | |
| if not user_message: | |
| return jsonify({"error": "Message is required"}), 400 | |
| # Example: call the ChatGPT model | |
| response = openai.ChatCompletion.create( | |
| model="gpt-3.5-turbo", # or gpt-4 if available | |
| messages=[{"role": "user", "content": user_message}], | |
| temperature=0.7 | |
| ) | |
| reply = response.choices[0].message["content"] | |
| return jsonify({"reply": reply}) | |
| except Exception as e: | |
| return jsonify({"error": str(e)}), 500 | |
| if __name__ == "__main__": | |
| app.run(host="0.0.0.0", port=7860) | |