如果我们的表格能够预测未来?
Source: Dev.to
请提供您希望翻译的正文内容,我将把它翻译成简体中文并保持原有的格式、Markdown 语法以及技术术语不变。谢谢!
预测学生成绩追踪器
使用 Syncfusion React Data Grid + Azure OpenAI
思路
在最近的 Syncfusion 网络研讨会上,我了解到如何将 AI 直接嵌入 UI 组件。
我们可以让大型语言模型(LLM)代替手动计算学生的未来 GPA。
使用场景:
教授查看一个仪表盘,列出每位学生的第一学年、第二学年和第三学年的 GPA。
当点击 “Calculate Grade” 按钮时,应用应:
- 基于前三年的数据预测 第四学年(最终)GPA。
- 将 总 GPA 计算为四年 GPA 的平均值。
- 根据以下比例从总 GPA 推导 总成绩:
| GPA range | Grade |
|---|---|
| 0 – 2.5 | F |
| 2.6 – 2.9 | C |
| 3.0 – 3.4 | B |
| 3.5 – 3.9 | B+ |
| 4.0 – 4.4 | A |
| 4.5 – 5.0 | A+ |
LLM 接收当前网格数据和上述提示,返回 JSON 负载,网格随后自动更新。
完整实现 (TypeScript)
import { loadCultureFiles } from '../common/culture-loader';
import { Grid, Toolbar, Page, QueryCellInfoEventArgs } from '@syncfusion/ej2-grids';
import { Button } from '@syncfusion/ej2-buttons';
import { predictiveData, predictive } from './data-source';
/* -------------------------------------------------
Predictive Data Entry
------------------------------------------------- */
loadCultureFiles();
Grid.Inject(Page, Toolbar);
const grid = new Grid({
dataSource: predictiveData,
toolbar: [{ template: `Calculate Grade` }],
queryCellInfo: customizeCell,
columns: [
{ field: 'StudentID', isPrimaryKey: true, headerText: 'Student ID', textAlign: 'Right', width: 100 },
{ field: 'StudentName', headerText: 'Student Name', width: 100 },
{ field: 'FirstYearGPA', headerText: 'First Year GPA', textAlign: 'Center', width: 100 },
{ field: 'SecondYearGPA', headerText: 'Second Year GPA', textAlign: 'Center', width: 100 },
{ field: 'ThirdYearGPA', headerText: 'Third Year GPA', textAlign: 'Center', width: 100 },
{ field: 'FinalYearGPA', headerText: 'Final Year GPA', visible: false, textAlign: 'Center', width: 100 },
{ field: 'TotalGPA', headerText: 'Total GPA', visible: false, textAlign: 'Center', width: 100 },
{ field: 'TotalGrade', headerText: 'Total Grade', visible: false, textAlign: 'Center', width: 100 }
],
enableHover: false,
created: onCreated
});
grid.appendTo('#Grid');
/* -------------------------------------------------
Grid lifecycle & UI handlers
------------------------------------------------- */
function onCreated(): void {
const button = document.getElementById('calculate_Grade') as HTMLButtonElement;
button.onclick = calculateGrade;
new Button({ isPrimary: true }, '#calculate_Grade');
}
function calculateGrade(): void {
grid.showSpinner();
executePrompt();
}
/* -------------------------------------------------
Helper utilities
------------------------------------------------- */
function delay(ms: number): Promise {
return new Promise(resolve => setTimeout(resolve, ms));
}
/* -------------------------------------------------
AI interaction
------------------------------------------------- */
function executePrompt(): void {
const prompt = `
Final year GPA column should be updated based on GPA of FirstYearGPA, SecondYearGPA and ThirdYearGPA columns.
Total GPA should update based on average of all years GPA.
Total Grade update based on total GPA.
Grading scale: 0‑2.5 = F, 2.6‑2.9 = C, 3.0‑3.4 = B, 3.5‑3.9 = B+, 4.0‑4.4 = A, 4.5‑5 = A+.
Average value decimal should not exceed 1 digit.
`.trim();
const gridReportJson = JSON.stringify(grid.dataSource);
const userInput = generatePrompt(gridReportJson, prompt);
// Azure OpenAI request (wrapper defined elsewhere)
const aiOutput = (window as any).getAzureChatAIRequest({
messages: [{ role: 'user', content: userInput }]
});
aiOutput.then((result: string) => {
// Strip possible markdown fences returned by the model
const cleanResult = result.replace(/```json/g, '').replace(/```/g, '').trim();
const generatedData: predictive[] = JSON.parse(cleanResult);
grid.hideSpinner();
if (generatedData.length) {
grid.showColumns(['Final Year GPA', 'Total GPA', 'Total Grade']);
updateRows(generatedData);
}
});
}
/* -------------------------------------------------
Grid row update
------------------------------------------------- */
async function updateRows(generatedData: predictive[]): Promise {
await delay(300);
for (const item of generatedData) {
grid.setRowData(item.StudentID, item);
await delay(300);
}
}
/* -------------------------------------------------
Cell styling
------------------------------------------------- */
function customizeCell(args: QueryCellInfoEventArgs): void {
const data = args.data as predictive;
if (args.column!.field === 'FinalYearGPA' || args.column
!.field === 'TotalGPA') {
if (data.FinalYearGPA! > 0 || data.TotalGPA! > 0) {
args.cell!.classList.add('e-PredictiveColumn');
}
}
if (args.column!.field === 'TotalGrade') {
if (data.TotalGPA! = 4.5) {
args.cell!.classList.add('e-activecolor');
} else if (data.TotalGPA! > 0) {
args.cell!.classList.add('e-PredictiveColumn');
}
}
}
/* -------------------------------------------------
提示生成器
------------------------------------------------- */
function generatePrompt(data: string, userInput: string): string {
return `
以下数据源已绑定到 Grid 表格:
${data}
根据用户查询返回一个新的数据源:
${userInput}
仅输出 **有效的** JSON —— 不要有额外的文本或 Markdown。
`.trim();
}
工作原理 – 步骤说明
- 网格创建 – Columns for Student ID, Name, and the three historic GPAs are defined.
- 工具栏按钮 –
created()injects a Calculate Grade button and wires it tocalculateGrade(). - 用户点击 –
calculateGrade()shows a spinner and callsexecutePrompt(). - 提示构建 –
generatePrompt()concatenates the current grid data (JSON) with a natural‑language instruction for the LLM. - Azure OpenAI 调用 –
getAzureChatAIRequest()sends the prompt; the model returns a JSON payload with the predicted Final GPA, Total GPA, and Grade. - 结果处理 – The JSON string is cleaned of any markdown fences, parsed, and fed back into the grid via
updateRows(). - 样式设置 –
customizeCell()adds CSS classes so predictive cells stand out (e.g., red for failing grades, green for top grades).
需要注意的事项
| 关注点 | 建议 |
|---|---|
| 提示一致性 | 保持指令简短且确定性;避免使用模糊的措辞。 |
| JSON 验证 | 在 LLM 调用外层使用 try/catch 包裹,并在更新 UI 前验证解析后的对象。 |
| 速率限制 | Azure OpenAI 有请求配额——必要时批量更新或对按钮进行防抖处理。 |
| 安全性 | 切勿在客户端暴露 Azure OpenAI 密钥;包装函数 (getAzureChatAIRequest) 应通过安全的后端进行代理。 |
| 性能 | delay(300) 调用为 UI 带来流畅的“打字”感,但在生产环境中可以移除。 |
最终思考
通过将 LLM 直接嵌入 Syncfusion Data Grid,我们只用了几行代码就把静态表格变成了 预测分析 组件。相同的模式可以在任何需要即时丰富表格数据的场景中复用——销售预测、库存消耗、风险评分,等等。
试一试,针对你的领域微调提示词,看看你的 UI 如何在无需从头构建自定义机器学习模型的情况下变得 智能!🚀
摘要
- 最终输出是动态数据;第 4 列 完全由 AI 生成。