Spaces:
Sleeping
Sleeping
Download ai_server.py from moshabann/echo-light: direct link, hf CLI and curl.
- Browser
- Download file 1.36 kB
-
https://huggingface.co/spaces/moshabann/echo-light/resolve/main/ai_server.py
- Command line
-
hf download hf://spaces/moshabann/echo-light/ai_server.py
-
curl -L -o ai_server.py https://huggingface.co/spaces/moshabann/echo-light/resolve/main/ai_server.py
1.36 kB
| import os | |
| from flask import Flask, request, jsonify, send_from_directory | |
| from flask_cors import CORS | |
| import openai | |
| from dotenv import load_dotenv | |
| load_dotenv() | |
| app = Flask(__name__, static_folder='.', static_url_path='') | |
| CORS(app) | |
| OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") or os.getenv("NVIDIA_API_KEY") | |
| openai.api_key = OPENAI_API_KEY | |
| def chat(): | |
| data = request.get_json(force=True) | |
| user_message = data.get("message", "") | |
| if not user_message: | |
| return jsonify({"reply": "Please say something!"}) | |
| try: | |
| # Compatible with openai>=1.0.0 | |
| response = openai.chat.completions.create( | |
| model="gpt-3.5-turbo", # or your NVIDIA LLM if available | |
| messages=[{"role": "user", "content": user_message}] | |
| ) | |
| reply = response.choices[0].message.content | |
| return jsonify({"reply": reply}) | |
| except Exception as e: | |
| return jsonify({"reply": f"AI error: {str(e)}"}) | |
| def serve_index(): | |
| return send_from_directory('.', 'index.html') | |
| def serve_static(path): | |
| if os.path.exists(path): | |
| return send_from_directory('.', path) | |
| return jsonify({'error': 'File not found'}), 404 | |
| if __name__ == "__main__": | |
| port = int(os.environ.get("PORT", 7860)) | |
| app.run(host="0.0.0.0", port=port) |