File size: 1,498 Bytes
a96233d 6799cbc a20e683 fd060cc a96233d 787a4c3 a96233d 5a8f2e8 a96233d fd060cc 3819f95 a96233d fd060cc 756e5a7 fd060cc 9510bbe | 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 57 58 59 | from flask import Flask, request, jsonify
from flask_cors import CORS
import time
from openai import OpenAI
import os
app = Flask(__name__)
CORS(app) # 讓 Open WebUI 可跨域存取
openaikey = os.getenv("openaikey") # 或從 .env 載入
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)
# 回傳格式符合 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)
|