Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Lesson 14 · 55 minutes

Build a triage copilot and report its errors on the fixed week

After this lesson you can
  • Combine the classifier, the enrichment and a review rule into one copilot
  • Measure what each part adds by switching the parts off one by one
  • Write the error report that a lead needs before the copilot goes live
Lab files of this lesson (55)

The lab folder as it stands after this lesson. Unzip it in ~/krlab.

More

The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.

Scenario

The trial is over, and your lead must decide whether the copilot goes on the night shift. She asks for one page: "Which parts does it have? What does each part change? How many real incidents does it still miss, how many hours does it save, and how many false alarms does it add? Give me numbers from the fixed week, not words." You put the parts of the course into one program and measure it.

Recall

Lesson 13: at which score does an alert close with no person, and what did that cost?

Below REVIEW_FROM, which is 0.02. Seven real incidents are in that pile. They are the silent misses that no reviewer can catch, because nobody reads them.

Lesson 9: why is enrichment allowed to run with no gate?

It only reads. It changes no ticket and no firewall. A gate is for actions that change something.

The idea

A tool built from parts is only as good as the parts that you can measure. Each part of the copilot has a job and a known weak spot.

PartLessonJobWeak spot
Classifier (triage.py)2Scores each alertQuiet incidents get a low score
Enrichment (enrich.py)9Adds owner and bad-address factsKnows only the addresses on its list
Review rule13Decides which alerts a person readsA tired reviewer errs, and a person may not see a quiet incident
Note writer3A model drafts the note for an escalation, and check decidescheck sees only the facts that you list
Error report2, 13Counts misses and false alarms against labelsLabels come late
The finished copilot
Week 5CopilotPerson and gateAlertsClassifierEnrichmentReview ruleGateReviewer12345Week 5CopilotPerson and gateAlertsClassifierEnrichmentReview ruleGateReviewer12345
  1. Alerts → Classifier: 1,000 alerts, each with a score
  2. Classifier → Enrichment: facts and a bad-list check
  3. Enrichment → Review rule: who must read it
  4. Review rule → Reviewer: 328 read, 672 closed by rule
  5. Reviewer → Gate: an escalation becomes a suggestion

The method is to switch parts off one by one. A part that changes no number should not stay, because each part is code that you must keep and test.

Worked example

1. Save the build

Save triage_copilot.py. It uses the files of the earlier lessons, so keep them in the same folder. build makes one proposal: it starts from propose of lesson 13, applies the enrichment if it is switched on, and sets needs_review. The enrichment does two things: a source address on the bad list forces "escalate", and an alert on the finance and payroll team's assets always goes to a person. run gives every alert a final verdict, through a person (the simulated reviewer of lesson 13) or by rule. report counts the results.

triage_copilot.py

"""triage_copilot.py: the course build. Classifier + enrichment + human review + error report.

    python3 triage_copilot.py            run the fixed week with every part, then switch the parts off one by one
"""
from copilot import REVIEW_FROM, auto, errors, propose, review, simulated_reviewer
from enrich import enrich
from gen import alerts
from triage import scores, train
from workload import MINUTES_PER_ALERT


def build(alert, score, use_enrichment):
    """One proposal: the verdict of the model, the facts of the enrichment and the review rule."""
    p = propose(alert, score)
    p["needs_review"] = score >= REVIEW_FROM
    if use_enrichment:
        e = enrich(alert)
        if e["known_bad"]:
            p["verdict"] = "escalate"
            p["evidence"].append("source address is on the bad list")
        p["needs_review"] = p["needs_review"] or e["known_bad"] or e["owner"] == "finance and payroll team"
    return p


def run(week, model, use_enrichment=True, use_review=True, sees_all=True):
    """Every alert gets a final verdict. Returns the records and the true labels."""
    labels = {a["id"]: a["label"] for a in week}
    props = [build(a, s, use_enrichment) for a, s in zip(week, scores(model, week))]
    ask = simulated_reviewer(labels, sees_all)
    records = [review(p, ask) if use_review and p["needs_review"] else auto(p) for p in props]
    return records, labels


def report(records, labels):
    real = sum(labels.values())
    closed = [r for r in records if not r["reviewed"]]
    missed, false_alarms = errors(records, labels)
    read = len(records) - len(closed)
    escalated = sum(r["final"] == "escalate" for r in records)
    return "\n".join([
        f"alerts: {len(records)}   real incidents: {real}",
        f"closed with no person: {len(closed)}   real incidents among them: {errors(closed, labels)[0]}",
        f"read by a person: {read}   ({read * MINUTES_PER_ALERT / 60:.1f} hours instead of {len(records) * MINUTES_PER_ALERT / 60:.1f})",
        f"overridden by a person: {sum(r['human'] == 'override' for r in records)}",
        f"final: escalated {escalated}   missed incidents {missed} of {real}   false alarms {false_alarms}",
        f"recall of incidents: {(real - missed) / real:.2f}   precision of escalations: {(real - missed) / max(1, escalated):.2f}",
        "assumes: a reviewer who recognises every real incident that they read, and errs on 1 alert in 20",
    ])


if __name__ == "__main__":
    week, model = alerts(5), train()
    records, labels = run(week, model)
    text = report(records, labels)
    print(text)
    open("report.txt", "w").write(text + "\n")
    print()
    print(f"{'parts switched on':26}{'missed':>8}{'false alarms':>14}{'read by a person':>18}")
    for name, enrichment, human, sees in (("classifier alone", False, False, True), ("+ enrichment", True, False, True),
                                          ("+ human review", False, True, True), ("all parts", True, True, True),
                                          ("all parts, weak reviewer", True, True, False)):
        rows, _ = run(week, model, enrichment, human, sees)
        m, f = errors(rows, labels)
        print(f"{name:26}{m:>8}{f:>14}{sum(r['reviewed'] for r in rows):>18}")

2. Run the week

python3 triage_copilot.py
alerts: 1000   real incidents: 59
closed with no person: 672   real incidents among them: 3
read by a person: 328   (32.8 hours instead of 100.0)
overridden by a person: 42
final: escalated 66   missed incidents 6 of 59   false alarms 13
recall of incidents: 0.90   precision of escalations: 0.80
assumes: a reviewer who recognises every real incident that they read, and errs on 1 alert in 20

parts switched on           missed  false alarms  read by a person
classifier alone                15            11                 0
+ enrichment                    10            19                 0
+ human review                  10             9               254
all parts                        6            13               328
all parts, weak reviewer        13             0               328

3. Read the report

The top block is the report for all parts. Of 1,000 alerts, 672 closed with no person, and 3 real incidents are among them. A person read 328 alerts, which is 32.8 hours against 100, a saving of two thirds. The person overrode the copilot 42 times. At the end, 66 alerts were escalated, 6 of the 59 incidents were missed, and 13 false alarms came with the 53 that were caught: recall 0.90, precision 0.80. The last line of the report is the assumption behind these numbers. The person in this test is a simulation that knows every label.

Compare this with lesson 1. In arrival order the team reached 32 incidents, and with the model as a reading order it reached 56. The copilot reaches 53, and it also closes alerts, so the team is free for other work. These are different jobs, and the report states which one it measures.

4. Read the table of parts

The first four rows switch parts on and off. Classifier alone: 15 missed and 11 false alarms, as in lesson 13. Plus enrichment: the bad-address list catches 5 more incidents (10 missed instead of 15), and it raises 8 more false alarms, because some harmless alerts come from listed addresses. Plus human review: 254 alerts are read, 10 are missed, and 9 false alarms remain. All parts: 6 missed, 13 false alarms, 328 read.

The last row is a weak reviewer: a person who cannot tell a quiet incident from a harmless alert, and so accepts every proposal to close (sees_all=False). This person still reverses wrong escalations, which is why no false alarm remains, and has the same one error in twenty. They let 13 incidents pass, more than the classifier and the enrichment give alone. The lead should sign a range, not 6: 6 to 13 missed incidents of 59 (recall 0.78 to 0.90), and the better number holds only for a reviewer who sees every incident. A real reviewer is measured on alerts with labels that came later (lesson 13, Field notes).

Missed incidents of 59, parts switched on
Classifier alone15+ enrichment10+ human review10All parts6All parts, weak reviewer13Classifier alone15+ enrichment10+ human review10All parts6All parts, weak reviewer13

The parts add up, and none is free. Enrichment helps recall and costs precision. Review helps both and costs hours. The finance rule is the part to watch: it adds reading, and the "Your turn" asks you to measure its value.

5. Connect the copilot to the gate

The copilot proposes a verdict. To turn an escalation into an action, it writes a suggestion, and the gate of lesson 9 decides. Here are three known-bad addresses from the escalated alerts, passed to the gate as block_ip suggestions. decide only gives a verdict, and it acts on nothing.

python3 -c "
import gate
from enrich import enrich
from gen import alerts
rows = [a for a in alerts(5) if enrich(a)['known_bad']][:3]
for a in rows:
    print(a['id'], a['src_ip'], gate.decide({'action': 'block_ip', 'args': {'ip': a['src_ip']}}))
"
W5-0112 203.0.113.90 ('approval', 'needs a person')
W5-0116 203.0.113.12 ('approval', 'needs a person')
W5-0119 203.0.113.23 ('approval', 'needs a person')

Each suggestion needs a named person. The copilot never blocks anything itself.

6. Check the note that a model writes

The copilot's note for an escalated alert may come from a model. The part is the same as in lesson 3: the model drafts, and check decides whether a person may trust the note. Here it grades two of the four recorded summaries of lesson 3 (recorded-03.json).

python3 -c "
import json
from summarise import case_log, check, facts
log = case_log()
for text in json.load(open('recorded-03.json'))[:2]:
    print(check(text, facts(log), log))
"
['time', 'count']
['count']

Both notes lost a fact, so both go back to the analyst. The week of this lesson holds no model note of its own, so the table of parts has no number for this part.

Your turn

Change the build and measure again on the fixed week. You write the changes in a copy, triage_copilot.py stays as it is, and the numbers are those of "all parts" with the change.

  1. Add a rule: an alert on an admin account (alert["admin"] is 1) always needs review. How many alerts does a person read, and how many incidents are missed?
  2. Remove the rule for the finance and payroll assets, and keep the other rules. How many alerts does a person read, and how many false alarms are there?

Last, write three sentences for your lead: which rules do you keep, which do you drop, and why.

Check yourself

Why switch the parts off one by one?

Only a measure with and without a part shows what it adds. A part can feel useful and change no number. Each part costs code, tests and attention.

Enrichment raised the false alarms from 11 to 19. Is it a bad part?

No. It also cut the misses from 15 to 10. The bad-address list is a fact, and an escalation on it is a good reason for a person to look. You decide by the cost of a miss against the cost of six minutes. If the false alarms are too many, a person reviews the listed addresses before an escalation.

The report says recall 0.90. Which number must a manager still hear?

The count of missed incidents, 6 of 59 in the best case and 13 with a weak reviewer, and the 3 that nobody read. And the warnings that the labels are from one week, and that the reviewer is a simulation: the next week and a real person can look different (lesson 15).

Why does the copilot write suggestions and never act?

A copilot that acts has excessive agency. The gate checks the action against a list, keeps a dry run and an approval, and writes the audit line. The copilot stays a source of proposals that a person and a gate can check.

Field notes

  • Keep the report with the model version, the data weeks, the rule values and the date. A number without these cannot be checked or compared next month.
  • Run the same report on every new week and plot it. A rising miss count is your drift alarm (lessons 4 and 15).
  • A person who reads 328 alerts in a week still needs a rota. The saving of 67 hours is a figure on paper until the shift plan uses it.
  • Treat the thresholds and rules as code: put them in a file that a person reviews, with a date and an owner, and test them in the build.
  • For the control families around this work, read the NIST AI Risk Management Framework and the course "AI governance for engineers". They name the roles that this copilot needs: an owner, a reviewer and an auditor.