Arx / training /build_chat.py
umer-wasim's picture
New website: computers only, download + check list + report viewer, no AI in the browser (chat and phone check removed)
f269f89 verified
Raw History Blame Contribute Delete
24.9 kB
#!/usr/bin/env python3
"""Chat training examples for models v0.4/v0.5 (questions about endpoint security, ISO 27001, GDPR, EU AI Act, the auditor,
and the user's own audit), grounded in library/knowledge.json and cited as [n].
Answers are composed from the same library facts the passages are built from, so they are grounded by construction;
check_chat() verifies it (citations exist, numbers appear in the prompt, refusals cite nothing). Prompts are built by
training/chat-contexts.mjs with the app's own search, so training matches runtime.
v0.5 adds MY DEVICE (what the browser detected, as deviceBrief() in the former chat/device.js wrote it) to most prompts without an audit.
Usage: python3 training/build_chat.py --evidence synthetic/out-v0.3/evidence.jsonl --base training/out-v0.3 --out training/out-v0.5
"""
import argparse
import json
import os
import random
import re
import subprocess
import sys
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.join(ROOT, "library"))
import build_knowledge as kb_build # noqa: E402
DATASET_VERSION = "0.5.0"
OS_LABEL = kb_build.OS_LABEL
NUMBER = re.compile(r"(?<![\w.])\d+(?:\.\d+)?(?!\w)")
def load(*parts):
with open(os.path.join(ROOT, *parts), encoding="utf-8") as handle:
return json.load(handle)
def cite(order, cid):
return f"[{order.index(cid) + 1}]"
def steps_text(steps):
return "\n".join(f"{i}. {s}" for i, s in enumerate(steps, 1))
OUT_OF_SCOPE = ["What's a good pizza recipe?", "Write me a poem about the sea.", "Who won the football match last night?",
"Can you help me with my maths homework?", "What's the weather like tomorrow?", "Tell me a joke.",
"Translate 'good morning' into Spanish.", "Which phone should I buy?", "How do I lose weight?",
"Recommend a good film for tonight.", "Write a cover letter for a sales job.", "What is the capital of Australia?",
"How do I make sourdough bread?", "Summarise the plot of Hamlet.", "What stocks should I buy?",
"Plan a weekend trip to Paris.", "How do I fix a leaking tap?", "Write Python code to sort a list.",
"What's the best gaming laptop?", "Explain how black holes form.", "Help me write a birthday message.",
"Who is the president of France?", "How many calories are in a banana?", "Give me a workout plan."]
UNKNOWN = ["How do I configure VLANs on a Cisco switch?", "What is the PCI DSS requirement 8.3.6?", "How do I set up SSO with Okta?",
"Is our AWS S3 bucket policy secure?", "How do I configure DMARC for my domain?", "What does SOC 2 Type II require for change management?",
"How do I harden a Kubernetes cluster?", "Which SIEM should we buy?", "What does HIPAA say about encryption?",
"How do I configure Azure Conditional Access?", "What does NIS2 require from my company?", "How do I rotate keys in HashiCorp Vault?",
"Is our WordPress site secure?", "How do I set up a WAF in Cloudflare?", "What are the DORA ICT risk rules?",
"How do I scan my network with nmap?"]
OWN_DEVICE = ["Is my laptop secure?", "Is my firewall OK?", "Is my computer compliant with ISO 27001?", "What should I fix first?",
"Am I GDPR compliant?", "Does my phone have any security problems?", "Is my disk encrypted?", "Are my passwords strong enough?",
"Do I have any viruses?", "Is my screen lock OK?", "Which of my apps are outdated?", "Is my Mac up to date?",
"Am I using any unapproved AI tools?", "What is my compliance score?"]
SCOPE = ("I can only help with device security, ISO 27001, GDPR and the EU AI Act, so I can't answer that. "
"Ask me, for example, how to turn on disk encryption, whether an AI tool is OK for work, or run an audit of this device.")
DONT_KNOW = ("I don't have reliable information about that in my knowledge base, so I won't guess. I cover security settings "
"on Windows, macOS, Linux, iPhone and Android, ISO 27001, GDPR and the EU AI Act.")
def make_jobs(rng, catalog, guidance, controls, tools, phone, evidences):
"""(job for chat-contexts.mjs, answer builder(order) -> text, meta)."""
jobs = []
checks = [c for c in catalog["checks"] if c["section"] != "org"]
G = lambda cid: guidance["checks"][guidance["aliases"].get(cid, cid)]
refs_of = lambda c: [f"{lab} {r}" for key, lab in (("iso27001", "ISO 27001:2022"), ("gdpr", "GDPR"), ("ai_act", "EU AI Act")) for r in c["controls"][key]]
baseline = kb_build.read_conf("baseline.conf")
fill = lambda t: kb_build.fill(t, baseline)
for c in checks:
g = G(c["id"])
for os_family in c["os"]:
name = (c.get("names") or {}).get(os_family, c["name"])
label = OS_LABEL[os_family]
gold = f"fix:{c['id']}:{os_family}"
steps = [fill(s) for s in g["fix"].get("all", []) + g["fix"].get(os_family, [])]
q_fix = rng.choice([f"How do I fix {name.lower()} on {label}?", f"How can I set up {name.lower()} on my {label}?",
f"My audit says '{name}' is non-compliant on my {label}. What should I do?",
f"What steps do I take for {name.lower()} on {label}?"])
jobs.append(({"question": q_fix, "os": os_family, "gold": [gold]},
lambda o, g=g, steps=steps, gold=gold, label=label: f"{g['why']} To fix it on {label} {cite(o, gold)}:\n{steps_text(steps)}\n\nTo check it worked: {fill(g['verify'])}",
("fix", os_family)))
if rng.random() < 0.45:
q = rng.choice([f"Why does {name.lower()} matter?", f"What's the risk if {name.lower()} isn't set up on my {label}?",
f"Is {name.lower()} really important on {label}?"])
jobs.append(({"question": q, "os": os_family, "gold": [gold]},
lambda o, g=g, gold=gold: f"{g['why']} If it is missing, the risk is {g['risk']['level'].lower()}: {g['risk']['reason']} {cite(o, gold)}",
("why", os_family)))
if rng.random() < 0.25:
rl = refs_of(c)
if rl:
q = rng.choice([f"Which ISO 27001, GDPR or EU AI Act rules cover {name.lower()}?", f"What compliance controls relate to {name.lower()}?"])
jobs.append(({"question": q, "os": os_family, "gold": [gold]},
lambda o, rl=rl, name=name, gold=gold: f"{name} relates to {', '.join(rl)} {cite(o, gold)}. "
"Meeting the setting is evidence for these controls; it is not a certification on its own.",
("refs", os_family)))
if rng.random() < 0.2:
q = f"How do I check that {name.lower()} is set correctly on {label}?"
jobs.append(({"question": q, "os": os_family, "gold": [gold]},
lambda o, g=g, gold=gold: f"{fill(g['verify'])} {cite(o, gold)}", ("verify", os_family)))
for check_id, per_os in phone["checks"].items():
for os_family, spec in per_os.items():
name = next(((c.get("names") or {}).get(os_family, c["name"]) for c in catalog["checks"] if c["id"] == check_id), check_id)
gold = f"phone:{check_id}:{os_family}"
for q in rng.sample([f"Where do I find {name.lower()} on my {OS_LABEL[os_family]}?", f"How do I see {name.lower()} on {OS_LABEL[os_family]}?",
f"Where is the {name.lower()} setting on my {OS_LABEL[os_family]}?"], 2):
jobs.append(({"question": q, "os": os_family, "gold": [gold]},
lambda o, spec=spec, gold=gold: f"Go to {spec['where']} {cite(o, gold)}", ("phone", os_family)))
for c in controls["controls"]:
gold = f"control:{c['framework']}:{c['id']}"
name = f"{c['framework'].replace(':2022', '')} {c['id']}"
for q in rng.sample([f"What does {name} require?", f"Explain {name} ({c['title']}) in simple terms.",
f"What does an auditor look for under {name}?"], 2):
jobs.append(({"question": q, "os": None, "gold": [gold]},
lambda o, c=c, gold=gold: f"{c['id']} ({c['title']}): {c['summary']} {cite(o, gold)}\n\nAn auditor looks for:\n"
+ "\n".join(f"- {x}" for x in c.get("auditor_looks_for", [])) + (f"\n\nOn devices: {c['endpoint_relevance']}" if c.get("endpoint_relevance") else ""),
("control", "any")))
for name, t in tools["tools"].items():
gold = f"tool:{name}"
for q in rng.sample([f"Is {name} OK to use at work?", f"Can I use {name} with customer data under GDPR?",
f"What is the EU AI Act risk class of {name}?", f"Is {name} safe for my company?"], 3):
jobs.append(({"question": q, "os": None, "gold": [gold]},
lambda o, t=t, name=name, gold=gold: f"{name} is a {t['kind'].lower()} from {t['provider']}; data goes to: {t['data_location'].lower()} {cite(o, gold)}. "
f"For general office use its default EU AI Act risk class is {t['default_risk']}. GDPR: {t['gdpr_notes']}\n\n"
"Whether it is allowed depends on your organisation's approved AI tools list and on what you use it for: some purposes "
"(for example screening job applicants) make any AI tool high-risk.", ("tool", "any")))
rules = tools["purpose_rules"]
for key, qs in (("prohibited", ["Which AI uses are banned under the EU AI Act?", "What AI practices are prohibited in the EU?", "Is emotion recognition at work allowed?"]),
("high_risk_examples", ["When does an AI tool become high-risk under the EU AI Act?", "What are examples of high-risk AI uses?"]),
("limited_risk", ["What does limited-risk AI mean under the EU AI Act?"]), ("minimal_risk", ["What is minimal-risk AI?"])):
items = rules[key] if isinstance(rules[key], list) else [rules[key]]
gold = f"aiact:{key}"
for q in qs:
jobs.append(({"question": q, "os": None, "gold": [gold]},
lambda o, items=items, gold=gold: f"Under the EU AI Act {cite(o, gold)}:\n" + "\n".join(f"- {x}" for x in items), ("aiact", "any")))
faq_q = {0: ["What is the Devseis Endpoint Auditor?", "What does this tool do?"], 1: ["Does the audit change anything on my computer?", "Will the audit change my settings?"],
2: ["Where do my audit results go?", "Is my data sent anywhere?"], 3: ["How do I audit my computer?", "Can you check my laptop from the browser?"],
4: ["How do I install the app on my Mac?", "The Mac says it cannot verify the app. What do I do?"],
5: ["How do I install it on Windows?", "Windows says it protected my PC. Is that normal?"], 6: ["How do I install it on Linux?"],
7: ["How does the phone check work?", "Can you check my iPhone?"], 8: ["What does self-reported mean?"],
9: ["What is in the audit report?"], 10: ["Do I need internet to run an audit?"], 11: ["How do I set up the auditor for my company?"],
12: ["Which AI model do you use?", "Who decides if a check passes, you or code?"]}
for i, qs in faq_q.items():
gold = f"faq:{i}"
text = kb_build.FAQ[i][1]
for q in qs:
jobs.append(({"question": q, "os": None, "gold": [gold]}, lambda o, text=text, gold=gold: f"{text} {cite(o, gold)}", ("faq", "any")))
for q in ["How many checks does the audit run?", "What does the audit check?"]:
jobs.append(({"question": q, "os": None, "gold": ["faq:checks"]}, lambda o: f"{kb_build_checks_text()} {cite(o, 'faq:checks')}", ("faq", "any")))
for q in ["What does Pending mean in my report?", "What do the statuses in the report mean?", "Why does a check say Error?",
"What does NotApplicable mean?", "What does Non-Compliant mean?", "Why are some checks 'not read'?"]:
jobs.append(({"question": q, "os": None, "gold": ["status:all"]}, lambda o: f"{status_text()} {cite(o, 'status:all')}", ("status", "any")))
for q in OUT_OF_SCOPE:
for device in (None, "macos", "windows"):
jobs.append(({"question": q, "os": device, "gold": []}, lambda o: SCOPE, ("oos", "any")))
for q in UNKNOWN:
for device in (None, "linux", "windows"):
jobs.append(({"question": q, "os": device, "gold": []}, lambda o: DONT_KNOW, ("unknown", "any")))
for q in OWN_DEVICE:
for device in ("macos", "windows", "ios", None):
jobs.append(({"question": q, "os": device, "gold": ["faq:3"] if device not in ("ios", "android") else ["faq:7"]},
lambda o, device=device: ("I can't see your device from here, so I can't tell you yet. "
+ ("Run the phone check: open this page on the phone and tap Start the check " if device in ("ios", "android")
else "Run an audit with the free Devseis desktop app: it reads the settings, changes nothing, and takes about 5 to 15 minutes ")
+ cite(o, "faq:3" if device not in ("ios", "android") else "faq:7")
+ ". Then ask me again and I will answer from your real results."), ("noaudit", device or "any")))
# Questions about the user's own audit (MY AUDIT filled in from a synthetic audit).
import itertools
for ev in itertools.islice(evidences, 0, 260):
gaps = [r for r in ev["results"] if r["status"] == "Non-Compliant"][:8]
brief = audit_brief(ev)
os_family = ev["host"]["os_family"]
if not gaps:
jobs.append(({"question": "What should I fix first?", "os": os_family, "gold": [], "audit": brief},
lambda o, ev=ev: "Your audit found no gaps: every assessed check meets the baseline. Keep automatic updates on and run the audit again after major changes.",
("audit", os_family)))
continue
top = gaps[0]
gold = f"fix:{top['id']}:{os_family}"
if not any(c["id"] == top["id"] and os_family in c["os"] for c in checks):
continue
g = G(top["id"])
steps = [fill(s) for s in g["fix"].get("all", []) + g["fix"].get(os_family, [])]
s = ev["summary"]
jobs.append(({"question": rng.choice(["What should I fix first?", "Where do I start?", "What is the most important thing to fix?"]),
"os": os_family, "gold": [gold], "audit": brief},
lambda o, top=top, gaps=gaps, s=s, steps=steps, g=g, gold=gold: (
f"Your audit found {s['Non-Compliant']} gaps. Start with {top['name']} (found: {top['actual']}). {g['why']} To fix it {cite(o, gold)}:\n"
f"{steps_text(steps)}" + (f"\n\nThen look at: {', '.join(r['name'] for r in gaps[1:4])}." if len(gaps) > 1 else "")),
("audit", os_family)))
pick = rng.choice(gaps)
gold2 = f"fix:{pick['id']}:{os_family}"
if any(c["id"] == pick["id"] and os_family in c["os"] for c in checks):
g2 = G(pick["id"])
steps2 = [fill(x) for x in g2["fix"].get("all", []) + g2["fix"].get(os_family, [])]
jobs.append(({"question": f"How do I fix {pick['name'].lower()}?", "os": os_family, "gold": [gold2], "audit": brief},
lambda o, pick=pick, steps2=steps2, g2=g2, gold2=gold2: (
f"Your audit found {pick['name']}: {pick['actual']}. {g2['why']} To fix it {cite(o, gold2)}:\n{steps_text(steps2)}\n\n"
f"Then run the audit again to confirm."), ("audit", os_family)))
return jobs
# What browsers report (the former chat/device.js). arch only for computers with Chromium client hints.
DEVICES = {
"macos": {"model": "Mac", "versions": ["13.6", "14.5", "14.7.1", "15.1", "15.6", "26.0.1", "26.5.2", None], "arch": ["Intel", "Apple silicon", None],
"browsers": ["Chrome 141", "Chrome 152", "Edge 140", "Safari 18.6", "Firefox 143"]},
"windows": {"model": "Windows PC", "versions": ["10", "11", "10 or 11"], "arch": ["x86-64", "ARM", None],
"browsers": ["Chrome 141", "Chrome 152", "Edge 141", "Firefox 143"]},
"linux": {"model": "Linux computer", "versions": [None], "arch": ["x86-64", None], "browsers": ["Chrome 141", "Firefox 143", "Chrome 152"]},
"ios": {"model": "iPhone", "versions": ["17.6", "18.5", "18.6", "26.0", "26.1"], "arch": [None], "browsers": ["Safari 18.6", "Safari 26.0", "Chrome 141 (iOS)"]},
"android": {"model": "Android phone", "versions": ["13", "14", "15", "16"], "arch": [None], "browsers": ["Chrome 141", "Samsung Internet 28.0", "Firefox 143"]},
}
OS_NAMES = {"macos": "macOS", "windows": "Windows", "linux": "Linux", "ios": "iOS", "android": "Android"}
def make_device(rng, family):
"""A detected device: (MY DEVICE line, short label for answers, browser). Python twin of deviceBrief() in the former chat/device.js."""
d = DEVICES[family]
version, arch, browser = rng.choice(d["versions"]), rng.choice(d["arch"]), rng.choice(d["browsers"])
model = d["model"]
if family == "android" and rng.random() < 0.5:
model = rng.choice(["Pixel 8", "SM-S921B", "Pixel 9a", "moto g84"])
os_label = " ".join(x for x in (OS_NAMES[family], version) if x)
article = "an" if model[0].lower() in "aeiou" else "a"
on = f" on {article} {model}{f' ({arch})' if arch else ''}"
return f"{os_label} ({family}){on}, {browser}; detected by the browser, security settings not checked.", f"{os_label}{on}", browser
def add_devices(rng, jobs, share):
"""MY DEVICE on most prompts without an audit, as at runtime; the search then filters by that system, as the chat does."""
for job, answer, (kind, os_family) in jobs:
if job.get("audit") or rng.random() >= share:
continue
family = job["os"] or (None if kind == "noaudit" else rng.choice(list(DEVICES)))
if not family:
continue
job["os"] = family
job["device"], job["device_label"], _ = make_device(rng, family)
DEVICE_QUESTIONS = ["Which system am I using?", "What device am I on?", "Which operating system do I have?",
"What version of my operating system do I have?", "Can you see my device?", "What do you know about my computer?"]
def device_jobs(rng):
"""Questions about the device itself: say what the browser saw, and that settings need an audit."""
jobs = []
for q in DEVICE_QUESTIONS:
for family in ("macos", "windows", "linux", "ios", "android"):
line, label, browser = make_device(rng, family)
phone = family in ("ios", "android")
gold = "faq:7" if phone else "faq:3"
jobs.append(({"question": q, "os": family, "gold": [gold], "device": line, "device_label": label},
lambda o, label=label, browser=browser, phone=phone, gold=gold: (
f"This browser reports {label}, using {browser}. That is all a web page can see: it can't read security settings "
"such as encryption, the firewall or the screen lock. "
+ ("To check those, run the phone check: open this page on the phone and tap Start the check " if phone
else "To check those, run an audit with the free Devseis desktop app ") + f"{cite(o, gold)}."),
("device", family)))
return jobs
def audit_brief(ev):
"""Python twin of auditBrief() in app/renderer/knowledge.js (tested for identical output)."""
h, s = ev["host"], ev["summary"]
assessed = s["Compliant"] + s["Non-Compliant"]
lines = [f"{h['os_name']} {h['os_version']} ({h['os_family']}), audited {str(ev['audit']['started_at'])[:10]}; "
f"{s['Compliant']} of {assessed} assessed checks compliant; {s['Non-Compliant']} gaps, {s['Pending']} pending, {s['Error']} not read."]
gaps = [r for r in ev["results"] if r["status"] == "Non-Compliant"][:8]
if gaps:
lines.append("Gaps: " + "; ".join(f"{r['name']}: {r['actual']}" for r in gaps) + ".")
return " ".join(lines)
def kb_build_checks_text():
k = {c["id"]: c for c in load("library", "knowledge.json")["chunks"]}
return k["faq:checks"]["text"]
def status_text():
k = {c["id"]: c for c in load("library", "knowledge.json")["chunks"]}
return k["status:all"]["text"]
def check_chat(example):
"""Grounding rules for chat answers (also used at runtime in the app)."""
prompt, answer = example["messages"][-2]["content"], example["messages"][-1]["content"]
problems = []
words = answer.split()
if re.search(r"(.{2,30}?)\1{9,}", answer, re.S) or (len(words) >= 30 and len(set(words)) / len(words) < 0.2):
problems.append("repeated text")
n_passages = len(re.findall(r"^\[\d+\] ", prompt.split("MY AUDIT:")[0], re.M))
for c in re.findall(r"\[(\d+)\]", answer):
if not 1 <= int(c) <= n_passages:
problems.append(f"citation [{c}] out of range")
allowed = set(NUMBER.findall(prompt))
for n in NUMBER.findall(answer):
if n not in allowed and not (n.isdigit() and int(n) <= 12): # list numbering
problems.append(f"number {n} not in prompt")
return problems
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--evidence", default=os.path.join(ROOT, "synthetic", "out-v0.3", "evidence.jsonl"))
parser.add_argument("--base", default=os.path.join(ROOT, "training", "out-v0.3"), help="report-task data to include")
parser.add_argument("--out", default=os.path.join(ROOT, "training", "out-v0.5"))
parser.add_argument("--device-share", type=float, default=0.6, help="share of prompts without an audit that carry MY DEVICE")
parser.add_argument("--seed", type=int, default=11)
args = parser.parse_args()
rng = random.Random(args.seed)
catalog, guidance, controls = load("catalog", "checks.json"), load("library", "check_guidance.json"), load("library", "controls.json")
tools, phone = load("library", "ai_tools.json"), load("catalog", "mobile_questions.json")
evidences = [json.loads(l) for l in open(args.evidence)][:600]
jobs = make_jobs(rng, catalog, guidance, controls, tools, phone, evidences)
add_devices(rng, jobs, args.device_share)
jobs += device_jobs(rng)
# A few examples carry an earlier, unrelated turn so the model learns to answer the latest question.
for job, _, _ in jobs:
job["shuffle"] = rng.random() < 0.5
proc = subprocess.run(["node", os.path.join(ROOT, "training", "chat-contexts.mjs")], input="".join(json.dumps(j) + "\n" for j, _, _ in jobs),
capture_output=True, text=True, check=True)
built = [json.loads(l) for l in proc.stdout.splitlines() if l.strip()]
examples, bad = [], 0
for (job, answer, (kind, os_family)), b in zip(jobs, built):
text = answer(b["order"])
if kind == "noaudit" and job.get("device"):
text = text.replace("I can't see your device from here, so I can't tell you yet.",
f"I can see this is {job['device_label']}, but a web page can't read its security settings, so I can't tell you yet.")
msgs = b["messages"] + [{"role": "assistant", "content": text}]
ex = {"messages": msgs, "meta": {"task": "chat", "os": os_family, "status": kind, "dataset_version": DATASET_VERSION}}
if check_chat(ex):
bad += 1
continue
examples.append(ex)
rng.shuffle(examples)
n = len(examples)
split = {"test": examples[: n // 20], "validation": examples[n // 20: n // 10], "train": examples[n // 10:]}
os.makedirs(args.out, exist_ok=True)
for name, chat in split.items():
base = [json.loads(l) for l in open(os.path.join(args.base, f"{name}.jsonl"))]
for b in base:
b["meta"]["dataset_version"] = DATASET_VERSION
rows = base + chat
random.Random(args.seed + len(name)).shuffle(rows)
with open(os.path.join(args.out, f"{name}.jsonl"), "w", encoding="utf-8") as handle:
for r in rows:
handle.write(json.dumps(r, ensure_ascii=False) + "\n")
print(f"{name:<11} {len(rows):>6} examples ({len(chat)} chat)")
kinds = {}
for e in examples:
kinds[e["meta"]["status"]] = kinds.get(e["meta"]["status"], 0) + 1
print("chat kinds:", kinds, "| rejected by grounding check:", bad)
if __name__ == "__main__":
main()