File size: 1,395 Bytes
822fb48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
from flask import Flask, request, jsonify
from flask_cors import CORS
import time

app = Flask(__name__)
CORS(app)  # 讓 Open WebUI 可跨域存取

@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 模型的回覆 ✅"

    # 回傳格式符合 OpenAI Chat API 格式
    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)