import openai
import gradio as gr
設定 OpenAI API 金鑰
openai.api_key = "your-openai-api-key"
題庫示例(可從資料庫中讀取)
questions = [
{"subject": "math", "question": "5 + 3 = ?", "answer": "8"},
{"subject": "math", "question": "10 - 2 = ?", "answer": "8"},
{"subject": "science", "question": "水的沸點是多少攝氏度?", "answer": "100"}
]
AI 故事生成邏輯
def generate_game(theme, role):
# 故事生成 Prompt
story_prompt = f"""
主題:{theme}
角色:{role}
請生成一個背景故事,描述角色的目標,並列出3個挑戰關卡。
"""
story_response = openai.Completion.create(
engine="text-davinci-003",
prompt=story_prompt,
max_tokens=150
)
story = story_response["choices"][0]["text"].strip()
# 嵌入題目到故事
tasks = []
for i, question in enumerate(questions[:3]):
task_description = f"關卡 {i+1}:{story}\n問題:{question['question']}"
tasks.append({"level": i+1, "description": task_description, "answer": question["answer"]})
return {"story": story, "tasks": tasks}
Gradio 界面
theme_input = gr.Textbox(label="輸入主題(如:魔法學校)")
role_input = gr.Textbox(label="輸入角色(如:巫師)")
output = gr.JSON(label="生成的遊戲")
interface = gr.Interface(fn=generate_game, inputs=[theme_input, role_input], outputs=output)
啟動應用
interface.launch()