| from flask import Flask, request, jsonify |
| from flask_cors import CORS |
| import time |
| from openai import OpenAI |
| import os |
|
|
|
|
| app = Flask(__name__) |
| CORS(app) |
| openaikey = os.getenv("openaikey") |
| client = OpenAI(api_key=openaikey) |
| @app.route('/') |
| def home(): |
| return "✅ Flask API is running!" |
|
|
| @app.route('/v1/chat/completions', methods=['POST']) |
| def chat(): |
| |
| data = request.get_json(force=True) |
|
|
| messages = data.get("messages", []) |
| model = data.get("model", "gpt-3.5-turbo") |
|
|
| try: |
| response = client.chat.completions.create( |
| model=model, |
| messages=messages |
| ) |
| reply = response.choices[0].message.content |
| except Exception as e: |
| reply = f"⚠️ OpenAI API 錯誤:{str(e)}" |
| print(reply) |
|
|
| |
| return jsonify({ |
| "id": "chatcmpl-xyz", |
| "object": "chat.completion", |
| "created": int(time.time()), |
| "model": "local-flask-test-001", |
| "choices": [ |
| { |
| "index": 0, |
| "message": { |
| "role": "assistant", |
| "content": reply |
| }, |
| "finish_reason": "stop" |
| } |
| ], |
| "usage": { |
| "prompt_tokens": 10, |
| "completion_tokens": 10, |
| "total_tokens": 20 |
| } |
| }) |
|
|
| if __name__ == '__main__': |
| app.run(host='0.0.0.0', port=7860) |
|
|