| from flask import Flask, render_template, request |
| import os |
| import openai |
|
|
| app = Flask(__name__) |
|
|
| client = openai.OpenAI(api_key=os.environ.get("OPENAI_API_KEY")) |
|
|
| @app.route("/", methods=["GET", "POST"]) |
| def index(): |
| story = "" |
| if request.method == "POST": |
| action = request.form.get("action") |
| if action == "使用魔法": |
| try: |
| response = client.chat.completions.create( |
| model="gpt-3.5-turbo", |
| messages=[{"role": "user", "content": "你是一位幻想世界的敘述者。請描述角色施展魔法後的劇情,最多 80 字,語氣神秘、有趣。"}] |
| ) |
| story = "你施展魔法後的結果是:「" + response.choices[0].message.content.strip() + "」" |
| except Exception as e: |
| story = f"⚠️ 錯誤發生:{str(e)}" |
| else: |
| story = f"你選擇了【{action}】,你決定踏出下一步……" |
| return render_template("index.html", story=story) |
|
|
| if __name__ == "__main__": |
| app.run(host="0.0.0.0", port=7860) |
|
|