mcpField
P
predictive-intelligence

predictive-intelligence

github.com/serac-labs数据与数据库7777 次安装9 周前更新
代码仓库

关于 predictive-intelligence

面向 ServiceNow 的 Predictive Intelligence 技能,介绍机器学习预测能力及其配置与运维示例。涵盖分类、相似记录、聚类、回归和推荐,并说明如何通过 MCP 工具查询及训练解决方案。

主要功能

  1. 01自动分类记录
  2. 02查找相似记录
  3. 03聚类与簇分析
  4. 04预测数值并推荐操作
  5. 05训练模型并检查状态
  6. 06记录反馈与分析准确率

适用场景

  1. 01自动归类事件或案例
  2. 02查找相关历史记录
  3. 03评估风险或其他数值
  4. 04收集预测反馈并监控效果

MCP 相关

说明使用 ServiceNow MCP 工具查询 ML 表、测试预测、运行预测及训练 Predictive Intelligence 解决方案。

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/serac-labs/serac --skill predictive-intelligence

安装后在 Claude Code 中输入/predictive-intelligence确认已加载。

详细介绍

ServiceNow 预测智能

预测智能使用机器学习自动执行分类、路由和推荐。

PI 功能

功能用例
分类自动对事件和案例分类
相似度查找相似记录
聚类对相关项目分组
回归预测数值
推荐推荐后续操作

关键表

表用途
ml_solutionML 解决方案定义
ml_solution_definition解决方案配置
ml_capability_definition功能设置
ml_model已训练的模型
ml_prediction_result预测结果

分类(ES5)

配置分类解决方案
// Create classification solution (ES5 ONLY!)
// Note: Usually done via UI, shown for understanding

var solution = new GlideRecord("ml_solution")
solution.initialize()

solution.setValue("name", "Incident Category Classifier")
solution.setValue("label", "Incident Category Classifier")
solution.setValue("table", "incident")
solution.setValue("active", true)

// Capability type
solution.setValue("capability", "classification")

// Target field to predict
solution.setValue("target_field", "category")

// Input fields for training
solution.setValue("input_fields", "short_description,description")

solution.insert()
获取分类预测
// Get classification prediction for record (ES5 ONLY!)
function getClassificationPrediction(tableName, recordSysId, solutionName) {
  var predictor = new sn_ml.ClassificationPredictor(solutionName)

  var gr = new GlideRecord(tableName)
  if (!gr.get(recordSysId)) {
    return null
  }

  try {
    var result = predictor.predict(gr)

    return {
      predicted_value: result.getPredictedValue(),
      confidence: result.getConfidence(),
      top_predictions: result.getTopPredictions(5),
    }
  } catch (e) {
    gs.error("Prediction failed: " + e.message)
    return null
  }
}
将预测应用于记录
// Auto-apply classification prediction (ES5 ONLY!)
// Business Rule: before, insert, incident

;(function executeRule(current, previous) {
  // Skip if already categorized
  if (current.category) {
    return
  }

  var solutionName = "incident_category_classifier"

  try {
    var predictor = new sn_ml.ClassificationPredictor(solutionName)
    var result = predictor.predict(current)

    // Only apply if confidence is high enough
    if (result.getConfidence() >= 0.8) {
      current.category = result.getPredictedValue()
      current.work_notes =
        "Category auto-assigned by Predictive Intelligence " +
        "(Confidence: " +
        Math.round(result.getConfidence() * 100) +
        "%)"
    }
  } catch (e) {
    gs.warn("Classification prediction failed: " + e.message)
  }
})(current, previous)

相似度(ES5)

查找相似记录
// Find similar incidents (ES5 ONLY!)
function findSimilarIncidents(incidentSysId, maxResults) {
  maxResults = maxResults || 5

  var incident = new GlideRecord("incident")
  if (!incident.get(incidentSysId)) {
    return []
  }

  try {
    var similarity = new sn_ml.SimilarityPredictor("incident_similarity")
    var results = similarity.findSimilar(incident, maxResults)

    var similar = []
    for (var i = 0; i < results.length; i++) {
      var match = results[i]
      similar.push({
        sys_id: match.getRecordSysId(),
        similarity_score: match.getSimilarityScore(),
        record: match.getRecord(),
      })
    }

    return similar
  } catch (e) {
    gs.error("Similarity search failed: " + e.message)
    return []
  }
}
相似记录小组件
// Widget Server Script for similar records (ES5 ONLY!)
;(function () {
  if (!input || !input.table || !input.sys_id) {
    data.similar = []
    return
  }

  var solutionName = input.table + "_similarity"

  try {
    var gr = new GlideRecord(input.table)
    if (!gr.get(input.sys_id)) {
      data.similar = []
      return
    }

    var similarity = new sn_ml.SimilarityPredictor(solutionName)
    var results = similarity.findSimilar(gr, 5)

    data.similar = []
    for (var i = 0; i < results.length; i++) {
      var match = results[i]
      var record = match.getRecord()

      data.similar.push({
        sys_id: match.getRecordSysId(),
        score: Math.round(match.getSimilarityScore() * 100),
        number: record.getValue("number"),
        short_description: record.getValue("short_description"),
        state: record.state.getDisplayValue(),
      })
    }
  } catch (e) {
    data.error = "Similarity search unavailable"
    data.similar = []
  }
})()

聚类(ES5)

获取聚类分配
// Get cluster for record (ES5 ONLY!)
function getClusterAssignment(tableName, recordSysId, solutionName) {
  var gr = new GlideRecord(tableName)
  if (!gr.get(recordSysId)) {
    return null
  }

  try {
    var clustering = new sn_ml.ClusteringPredictor(solutionName)
    var result = clustering.predict(gr)

    return {
      cluster_id: result.getClusterId(),
      cluster_label: result.getClusterLabel(),
      confidence: result.getConfidence(),
    }
  } catch (e) {
    gs.error("Clustering failed: " + e.message)
    return null
  }
}
分析聚类
// Get cluster statistics (ES5 ONLY!)
function getClusterStats(solutionName) {
  var stats = []

  var cluster = new GlideRecord("ml_cluster")
  cluster.addQuery("solution.name", solutionName)
  cluster.query()

  while (cluster.next()) {
    stats.push({
      cluster_id: cluster.getValue("cluster_id"),
      label: cluster.getValue("label"),
      size: parseInt(cluster.getValue("record_count"), 10),
      keywords: cluster.getValue("keywords"),
    })
  }

  return stats
}

训练模型(ES5)

触发模型训练
// Trigger retraining of ML solution (ES5 ONLY!)
function retrainSolution(solutionName) {
  var solution = new GlideRecord("ml_solution")
  if (!solution.get("name", solutionName)) {
    gs.error("Solution not found: " + solutionName)
    return false
  }

  try {
    // Queue training job
    var trainer = new sn_ml.MLTrainer()
    trainer.train(solution.getUniqueValue())

    gs.info("Training queued for solution: " + solutionName)
    return true
  } catch (e) {
    gs.error("Training failed: " + e.message)
    return false
  }
}
检查训练状态
// Check model training status (ES5 ONLY!)
function getTrainingStatus(solutionName) {
  var model = new GlideRecord("ml_model")
  model.addQuery("solution.name", solutionName)
  model.orderByDesc("sys_created_on")
  model.setLimit(1)
  model.query()

  if (model.next()) {
    return {
      model_id: model.getUniqueValue(),
      status: model.getValue("state"),
      accuracy: model.getValue("accuracy"),
      trained_on: model.getValue("sys_created_on"),
      record_count: model.getValue("training_record_count"),
    }
  }

  return null
}

预测结果(ES5)

存储预测反馈
// Record prediction feedback for model improvement (ES5 ONLY!)
function recordPredictionFeedback(predictionSysId, wasCorrect, actualValue) {
  var prediction = new GlideRecord("ml_prediction_result")
  if (!prediction.get(predictionSysId)) {
    return false
  }

  prediction.setValue("feedback", wasCorrect ? "correct" : "incorrect")
  prediction.setValue("actual_value", actualValue)
  prediction.setValue("feedback_date", new GlideDateTime())
  prediction.setValue("feedback_user", gs.getUserID())

  prediction.update()

  return true
}
分析预测准确性
// Get prediction accuracy stats (ES5 ONLY!)
function getPredictionAccuracy(solutionName, days) {
  days = days || 30

  var startDate = new GlideDateTime()
  startDate.addDaysLocalTime(-days)

  var ga = new GlideAggregate("ml_prediction_result")
  ga.addQuery("solution.name", solutionName)
  ga.addQuery("sys_created_on", ">=", startDate)
  ga.addNotNullQuery("feedback")
  ga.addAggregate("COUNT")
  ga.groupBy("feedback")
  ga.query()

  var stats = { correct: 0, incorrect: 0 }

  while (ga.next()) {
    var feedback = ga.getValue("feedback")
    var count = parseInt(ga.getAggregate("COUNT"), 10)
    stats[feedback] = count
  }

  var total = stats.correct + stats.incorrect
  stats.accuracy = total > 0 ? Math.round((stats.correct / total) * 100) : 0
  stats.total = total

  return stats
}

MCP 工具集成

可用工具
工具用途
snow_query_table查询 ML 表
snow_execute_script测试预测
snow_ml_predict使用已训练的模型运行预测
snow_list_pi_solutions列出预测智能解决方案
snow_train_pi_solution训练 / 重新训练解决方案
示例工作流
// 1. Query ML solutions
await snow_query_table({
  table: "ml_solution",
  query: "active=true",
  fields: "name,table,capability,target_field",
})

// 2. Check model status
await snow_query_table({
  table: "ml_model",
  query: "solution.active=true",
  fields: "solution,state,accuracy,sys_created_on",
})

// 3. Test prediction
await snow_execute_script({
  script: `
        var result = getClassificationPrediction('incident', 'inc_sys_id', 'incident_classifier');
        gs.info(JSON.stringify(result));
    `,
})

最佳实践

  1. 高质量数据 - 清理训练数据至关重要
  2. 特征选择 - 选择相关的输入字段
  3. 置信度阈值 - 仅应用高置信度预测
  4. 反馈循环 - 收集用户反馈
  5. 定期重新训练 - 定期更新模型
  6. 监控准确性 - 跟踪预测性能
  7. 回退方案 - 预测失败时应有人工处理流程
  8. 仅限 ES5 - 不使用现代 JavaScript 语法

评论

支持 Markdown