| from flask import Flask, request, jsonify |
| from flask_cors import CORS |
| import time |
|
|
| app = Flask(__name__) |
| CORS(app) |
|
|
| @app.route('/') |
| def hello(): |
| return "✅ Flask API is running!" |
|
|
| @app.route('/v1/chat/completions', methods=['POST']) |
| def chat(): |
| print("💬 收到請求") |
|
|
| data = request.get_json() |
| print("資料內容:", data) |
|
|
| |
| messages = data.get("messages", []) |
| user_message = "" |
| for m in messages[::-1]: |
| if m.get("role") == "user": |
| user_message = m.get("content", "") |
| break |
|
|
| |
| reply = f"你剛剛說的是:「{user_message}」,這是來自 Flask 模型的回覆 ✅" |
|
|
| |
| 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) |
|
|
|
|