# Importsfrom transformers import AutoModelForCausalLM, AutoTokenizer
import torch
import gradio as gr
# Load the Phi-4 model and tokenizer
model_name ="NyxKrage/Microsoft_Phi-4"
model=AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.float16, device_map="auto")
tokenizer = AutoTokenizer.from_pretrained(model_name)# Set tokenizer padding token if not setif tokenizer.pad_token_id isNone:
tokenizer.pad_token_id = tokenizer.eos_token_id技术支持
# Function to validate the solution and provide feedbackdefcheck_homework(exercise, solution):
prompt =f"""
Exercise: {exercise}
Solution: {solution}
Task: Validate the solution to the math problem, provided by the user. If the user's solution is correct, confirm else provide an alternative if the solution is messy. If it is incorrect, provide the correct solution with step-by-step reasoning.
"""# Tokenize and generate response
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)print(f"Tokenized input length: {len(inputs['input_ids'][0])}")
outputs = model.generate(**inputs, max_new_tokens=1024)print(f"Generated output length: {len(outputs[0])}")
response = tokenizer.decode(outputs[0], skip_special_tokens=True)# response = response.replace(prompt, "").strip()
prompt_len =len(prompt)
response = response[prompt_len:].strip()print(f"Raw Response: {response}")return response技术支持
# Define the function that integrates with the Gradio appdefhomework_checker_ui(exercise, solution):return check_homework(exercise, solution)# Create the Gradio interface using the new syntax
interface = gr.Interface(
fn=homework_checker_ui,
inputs=[
gr.Textbox(lines=2, label="Exercise (e.g., Solve for x in 2x + 3 = 7)"),
gr.Textbox(lines=1, label="Your Solution (e.g., x = 1)")],
outputs=gr.Textbox(label="Feedback"),
title="AI Homework Checker",
description="Validate your homework solutions, get corrections, and receive cleaner alternatives.",)# Launch the app
interface.launch(debug=True)技术支持
Microsoft 近期发布了 Phi-4,这是 Phi 小型语言模型家族的最新成员。由于其在数学方面表现出色,我决定用 Phi-4 构建一个与 Gradio 集成的作业检查器。
在本教程中,我将一步步带您构建一个可用的网页应用,它能够验证解答、纠正错误,并提供替代思路——就像一位虚拟助教!
什么是 Microsoft 的 Phi-4 模型?
Phi-4 在复杂推理任务(尤其是数学)方面表现突出,同时也具备常规语言处理能力。其主要特性包括:
Phi-4 在数学推理任务中表现优异,甚至在数学竞赛题上超过了像 Gemini Pro 1.5 这样的更大模型。这使其非常适合需要高级数学问题求解能力的应用。
来源:Microsoft
Phi-4 作业检查器:实现概览
我们将用 Phi-4 构建一个 AI 驱动的作业检查器。用户的使用流程如下:
为了提供一个网页界面,便于用户与作业检查器交互,我们将使用 Gradio。
步骤 1:前置条件
在开始之前,请确保已安装以下组件:
运行以下命令安装这些依赖:
现在我们已经安装好所有依赖。接下来设置 Phi-4 模型。
步骤 2:设置模型
我们从 HuggingFace 的 Transformers 库加载 Phi-4 模型。随后,分词器会对输入(题目与解答)进行预处理,为推理做准备。
上述代码片段完成 Phi-4 模型与分词器的设置,并将其与 PyTorch 集成以进行计算。下面对其作进一步说明:
AutoModelForCausalLM和AutoTokenizer以便使用模型与分词功能。from_pretrained()方法从 Hugging Face 仓库加载模型,并配置为使用 FP16 精度,以优化内存占用与计算速度。device_map="auto"参数可将模型自动映射至可用硬件。eos_token_id(序列结束标记)指定为填充标记。步骤 3:设计核心功能
模型设置完成后,我们为应用定义三个关键功能:
以下函数
check_homework()构造一个提示,包含题目、用户解答,以及给模型的具体指令,用于确认正确性、定位问题,或在解答不正确时提供分步指导。check_homework()函数使用模型的分词器对提示进行分词。它将输入转换为 PyTorch 张量,以便在模型所在设备上处理。随后,模型在
max_new_tokens=1024的限制下生成响应,用于控制输出长度。您可根据需求调整该值。最后返回处理后的响应,其中包含反馈或订正解答。
步骤 4:使用 Gradio 创建友好界面
Gradio 让作业检查器的部署更为简单,用户可交互式输入题目与解答。以下代码片段为
check_homework()函数创建了一个友好的 Gradio 网页界面。界面接收用户输入(题目与解答),并将其传递给模型进行验证。我们使用
gr.Textbox创建了两个输入框:一个用于数学题目(exercise),另一个用于用户解答。输出显示在一个标注为"Feedback"的gr.Textbox中。interface.launch()命令会在浏览器中启动 Gradio 应用,debug=True标志可输出详细日志以便排查错误。步骤 5:测试与验证
现在来测试我们的 AI 作业检查器应用。以下是我进行的一些测试:
结语
在本教程中,我们使用 Phi-4 模型创建了一个 AI 驱动的作业检查器。该应用能够验证解答、提供详细订正,并给出更优雅的替代方案,堪称学生的理想虚拟老师。
准备扩展该应用了吗?不妨尝试更复杂的问题,或将其集成到教育平台中,让更多人受益!