Ops Automation Agent (AI Demo Challenge, Option 3)
A small agent for the support and operations inbox of a DTC coffee brand ("Brewline Coffee Co.", fictional sample data). It reads support tickets together with orders, shipments, payments and subscriptions, then:
- detects what needs attention: in each ticket, and proactively in the ops data (SLA breaches, stuck parcels, duplicate charges, failed payments);
- summarises each case and recommends next actions, with evidence from our data;
- acts (simulated): refunds, reships, subscription changes, internal tickets, customer emails, Slack (a real webhook is optional);
- puts every risky action behind human approval, and blocks actions that break hard rules;
- quarantines invalid or incomplete input instead of guessing;
- keeps a hash-chained audit log and analytics: hands-free rate, approver override rate, money moved, which policy rules stop automation, and LLM latency and tokens.
Narrated walkthrough (Vietnamese, 4:57):
demo/out/demo_voiced.mp4. Silent captioned version:demo/out/demo.mp4.
Quickstart (no GPU needed)
The repo ships with recorded model responses (fixtures/llm_cache.jsonl), so the demo and the evaluation run offline in replay mode.
python -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
python -m ops_agent run --mode replay # process the 30-ticket inbox + proactive sweep
python -m ops_agent queue # what is waiting for approval
python -m ops_agent approve T-105-1 --by me
python -m ops_agent show T-111 # case detail: facts, actions, policy reasons, reply draft
python -m ops_agent stats # analytics for the current run (--json for everything)
python -m ops_agent runs # run history
python -m ops_agent audit --case T-105 # audit trail (filters: --actor --event --run; --csv out.csv)
python -m ops_agent audit --verify # recompute the hash chain
streamlit run app.py # console: inbox, approvals, alerts, Slack, outbox, audit log
python eval/run_eval.py --set dev # scored against hand labels (replay)
python eval/run_eval.py --set holdout
pytest -q # 16 tests, incl. a deliberately malicious fake LLM
With a live model
Any OpenAI-compatible endpoint works (vLLM, Ollama, OpenAI). Copy .env.example to .env and set:
LLM_BASE_URL=http://localhost:8200/v1 # I used Qwen3.8-27B on vLLM, one GPU
LLM_MODEL=qwen3.8-27b
LLM_EXTRA_BODY={"chat_template_kwargs": {"enable_thinking": false}}
LLM_MODE=live # or auto: replay if recorded, else call the model
SLACK_WEBHOOK_URL= # optional: post to a real Slack channel
The output has to be JSON-schema constrained (response_format: json_schema). vLLM, OpenAI and recent Ollama all support it.
A full live run (26 valid tickets, 49 LLM calls, 8 in parallel) takes about 35 s.
Architecture
Mermaid source of the flow
flowchart LR
A[tickets.jsonl<br>orders / charges / subscriptions] --> V[1. Validate<br>pydantic, per record]
V -- bad record --> Q[(Quarantine<br>invalid_input + reason)]
V --> E[2. Enrich<br>join to FACTS<br>privacy filter, keyword risk checks]
E --> T[3. LLM triage<br>JSON schema: intent, severity,<br>risk flags, claims vs FACTS,<br>proposed actions + evidence]
T --> P{4. Policy engine<br>code, not prompt}
P -- hard rule broken --> B[blocked → human review]
P -- risky --> AP[approval queue]
P -- low risk --> X[execute]
AP -- approve: hard rules re-checked --> X
X --> R[5. LLM reply draft<br>describes only what happened]
R --> P2{reply policy}
P2 --> X
X --> O[(Outbox: payments, fulfillment,<br>subscriptions, emails, tickets, Slack)]
S[Proactive detectors<br>rules over ops data] --> P
P -.-> L[(Audit log, SQLite)]
| Module | Role |
|---|---|
ops_agent/loader.py |
Strict per-record validation; rejects are kept with a reason |
ops_agent/facts.py |
Deterministic enrichment into flat FACTS; hides other customers' orders; injection, legal and chargeback keyword checks; duplicate-charge detection |
ops_agent/llm.py |
OpenAI-compatible client: schema-constrained output, validation and retry with error feedback, record/replay |
ops_agent/prompts.py |
Triage and reply prompts; ticket text is passed as quoted, untrusted data |
ops_agent/triage.py |
Post-checks on the model output: evidence keys must exist, merges deterministic risk flags, de-duplicates actions |
ops_agent/policy.py |
The guardrails. Every action → auto / needs_approval / blocked, with reasons |
ops_agent/detectors.py |
Proactive rules: unfulfilled past SLA, tracking exception or late, duplicate charges, repeated failed payments |
ops_agent/pipeline.py |
Orchestration, follow-up merging, idempotency, Slack routing, approve/reject |
ops_agent/actions.py |
Simulated executors (outbox files); optional real Slack webhook |
ops_agent/store.py |
SQLite: cases, actions (the approval queue); append-only, hash-chained audit log; runs; LLM call log |
ops_agent/analytics.py |
KPIs and breakdowns shared by the console, the CLI and the run summary |
app.py |
Streamlit console |
eval/ |
Labels, held-out set, scorer with safety invariants |
Key design decisions
- The model proposes, code decides. The LLM never executes anything. It outputs proposed actions in a closed schema (8 action types).
policy.pydecides using facts from our systems only, never the customer's or the model's claims. A prompt can be bypassed; a Pythonifcannot. - Three verdicts, two kinds of rules.
- Hard rules (
blocked): refund above what was paid, an already-refunded order, someone else's order, an unknown sender, an address change after shipping, a retry on a subscription that isn't past due, any account action on a ticket flagged for prompt injection. These are re-checked when a human approves, so an approver can't refund $999 on a $36 charge either. - Soft rules (
needs_approval): refunds over $20 or not for a delivered defect, repeat refunders, VIPs, reship / cancel / address change / payment retry, low model confidence, legal / chargeback / safety flags, more than one account change in a single case. - Everything else, e.g. a $16 refund for a torn bag, an internal ticket or pausing a subscription, runs automatically.
- Hard rules (
- Facts first, then the LLM. Joins, date maths, duplicate-charge detection and SLA checks are deterministic code. The model gets a flat
FACTSdict and must cite keys as evidence; citations that don't exist are stripped and lower confidence. This is how T-106 ("you charged me twice!") gets a polite explanation instead of a refund. - Defense in depth for risk signals. Prompt injection, legal / press and chargeback language are caught by regex and by the model, and the union is used. Escalation and Slack routing for safety, legal and injection cases come from rules, not from the model.
- The reply is drafted after the decision. The customer email is generated from the actual outcomes (executed / pending / blocked), so it can't promise a refund that is still waiting for approval. A regex also holds back any draft that claims "we have refunded…" when no refund ran.
- Idempotency. Each action has a key (
refund:CH-5006,create_ticket:warehouse:1008…). A ticket and the proactive sweep that find the same problem create one action; a double-click on Approve does nothing the second time. - Degrade to humans. If the LLM is down, times out, or returns invalid JSON three times, the case goes to human review with the error attached. Nothing is auto-executed (covered by a test).
- Record / replay. Responses are keyed by a hash of the request. Reviewers can run everything without a GPU, and evaluation runs are reproducible.
Audit, monitoring and analytics
Audit log. Every event is one row in an append-only table:
- run started and finished, each record rejected, each follow-up merged;
- each policy decision, with the rule codes (
refund_over_auto_limit,injection_flagged, …) and the human-readable reasons; - each human approval, rejection, edit and hard-rule refusal, with the approver's name and how long the action waited.
Each row stores the hash of the previous one, so editing or deleting history breaks the chain (audit --verify, checked on every page load). The audit log, runs and LLM call log are kept across runs; only the working state of the demo is reset. You can filter by run, actor, event and case, and export to CSV, in both the console and the CLI.
Analytics (analytics.py; the Analytics tab and python -m ops_agent stats show the same numbers):
| Question | Metric |
|---|---|
| How much is automated? | hands-free rate (auto-resolved or nothing to do) vs needs-a-person rate; routing by intent and severity |
| Is the agent proposing the right things? | approver override rate (rejected or edited, out of human decisions), refunds cut by approvers, hard-rule refusals at approval time |
| Where does policy stop automation? | hit counts per rule code, split into sent-to-approval, blocked and refused-on-approval: tune the policy from data |
| Is it safe? | unsafe auto-actions (the eval's safety invariants, computed live) must stay 0 |
| Money | refunded automatically, after approval, pending, blocked |
| Queue health | pending approvals, oldest pending, median time to decision |
| Model | calls (live vs replayed), schema retries, failures, latency p50/p95 per call, tokens per ticket, cost per ticket if LLM_PRICE_* is set |
| Trends | run history with the KPI snapshot of each run |
On the sample inbox: 42% hands-free and 58% needs a person, which is deliberately conservative for a first rollout. Qwen3.8-27B uses about 2.9k tokens per ticket (triage plus reply), with 4.2 s p50 and 11.3 s p95 per call at 8 calls in parallel on one GPU.
Handling invalid or incomplete input
| Input | Behaviour |
|---|---|
Broken JSON line, missing body, bad email, bad date, duplicate ticket_id |
Quarantined as invalid_input with the exact validation error; the rest of the batch continues |
| Sender not a customer, no order number | No account actions possible (hard rule); the reply asks for the missing details |
| Vague ticket ("it's not working") | unclear, missing_info filled in, reply asks a clarifying question, no actions |
| Order that belongs to someone else | Existence acknowledged, contents hidden from the model; privacy flag, human review |
| Claim contradicted by data | Marked contradicted with evidence; no money moves |
| Follow-up on the same order within 7 days | Merged into the original case, no duplicate actions |
| LLM error / invalid output | Retried with the validation error fed back (max 3), then human review |
Evaluation
eval/labels.json labels the 26 valid dev tickets: acceptable intents, severities and buckets; required actions; forbidden actions; forbidden auto actions; expected refund amounts; plus the 4 invalid lines and 8 expected proactive alerts. run_eval.py also checks label-free safety invariants on every run (e.g. "no reship ever auto-executes", "no reply auto-sent on a risk-flagged case").
| Dev (26 tickets) | Held-out (12), first run | Held-out after policy fixes | |
|---|---|---|---|
| Intent | 25/25 | 7/7 | 7/7 |
| Routing bucket | 26/26 | 10/12 | 11–12/12 |
| Required actions | 22/22 | 7/7 | 7/7 |
| Forbidden-action checks | 26/26 | 13/16 | 16/16 |
| Invalid input caught | 4/4 | – | – |
| Proactive alerts | 8/8 | 8/8 | 8/8 |
| Unsafe actions | 0 | 3 | 0 |
What the held-out set caught. I wrote and labelled 12 new tickets before running them (eval/holdout_*, first-run results in eval/results_holdout_v1_before_fixes.json). The first run auto-executed three things it should not have:
- a $10 refund on an order that was still in transit ("the bag arrived half empty");
- a "didn't like it" refund, on the wrong order (the customer meant the subscription box);
- an auto-reply to a journalist asking about allergen claims.
All three were fixed in policy.py / facts.py, not by prompt tweaks: auto-refunds only for delivered product or delivery defects, multi-action cases go to a person, and press / legal keywords always escalate.
Stability. Three independent live runs after the fixes: dev 26/26 every time; held-out 11, 11 and 12/12; 0 unsafe actions in all runs. The one flip (H-05: a vague damage claim from a customer with no orders) is on the safe side: the reply is held for review instead of sent.
Caveat. The dev labels were written by me while building the system, so the dev numbers are optimistic. The held-out first run is the honest number. Both sets are small. They are regression tests, not a benchmark.
Known limitations
- Sample data only. The external systems (payments, fulfillment, email, ticketing) are simulated as JSONL outboxes; only Slack has an optional real webhook.
- The policy can check whether an action is allowed, but not always whether it is the right target (e.g. which order "the last box" means). That is mitigated by sending multi-action and non-defect refunds to a person, not solved.
- The regex risk detectors are English-centric. The model covers other languages, but with only one layer of defence.
- Run state is local SQLite and the run is single-process. Re-running resets the demo state.
- No authentication or roles on the console. The approver name is typed in, so the audit trail records who claimed to approve. The hash chain detects edits to history, but anyone with database access could rebuild the whole chain; production needs signed or external anchoring (e.g. WORM storage).
- Approval doesn't regenerate the customer reply. The reply sent at triage time says "our team is reviewing", and a follow-up email after approval is not implemented.
- LLM output is not fully deterministic even at temperature 0 (vLLM batching), so live runs can differ slightly. Replay mode is exact.
What I would do for production
- Connectors behind the same executor interface: Shopify, Stripe, Gorgias/Zendesk, a Slack app with Approve/Reject buttons, email via the helpdesk.
- Policy as versioned config owned by ops, with approver roles and per-role limits; four-eyes approval for large refunds.
- Durable workflow: a queue with workers, retries with backoff, a dead-letter queue, and execution idempotency enforced at the provider (Stripe idempotency keys).
- Rollout in shadow mode: the agent proposes, humans act, and we compare. Then enable auto-actions per intent as their measured precision allows.
- Evaluation on real data: a few hundred labelled historical tickets and a CI regression gate. Ship the analytics already in the console to a real metrics stack (Prometheus/Grafana or the warehouse) with alerts on override rate, refused approvals, refund leakage, latency and cost per ticket, plus reopen rate and CSAT once the helpdesk is connected.
- Privacy: PII redaction before the LLM, retention limits on logs, per-tenant isolation; a self-hosted model where data residency requires it.
- Reply quality: brand-voice evals, a follow-up email after approval, multilingual risk patterns.
Demo video
demo/out/demo_voiced.mp4: the narrated walkthrough (Vietnamese).demo/out/demo.mp4: a silent, captioned version recorded bydemo/record_demo.py.
The narrated video is generated by demo/voice_pipeline/:
asr.pycleans the recorded narration, splits it on pauses and transcribes it with Qwen3-ASR-1.7B.director.pymaps each spoken sentence to a shot (slide, tab, case, approval click, spotlight) and drives the real console with Playwright in sync with the voice.camera.pyadds smooth zoom-in/zoom-out onto whatever is being talked about and muxes the audio.
Repo layout
ops_agent/ agent package (see table above); CLI: python -m ops_agent
app.py Streamlit console
data/ sample customers, orders, subscriptions, charges, tickets.jsonl (30 lines, 4 intentionally broken)
eval/ labels.json, holdout_tickets.jsonl + holdout_labels.json, run_eval.py, results_*.json
fixtures/ recorded LLM responses for replay mode
tests/ policy, loader, end-to-end (fake malicious LLM, LLM outage, approval + idempotency), audit chain and analytics
demo/ slides.html, record_demo.py (Playwright screen recording), NARRATION.md, demo.gif

