Skip to content

100+ AI Agents, Agent Skills and RAG Apps - Free and Open Source.

Add LLM Panel Agent Team: three vendors review the same diff blind, then argue it out anonymously

Jaret Arnold71bd5ab21a66
diff --git a/README.md b/README.md
index 62a3497c..a31559c0 100644
--- a/README.md
+++ b/README.md
@@ -184,6 +184,7 @@ streamlit run travel_agent.py
* [✨ Multimodal Design Agent Team](advanced_ai_agents/multi_agent_apps/agent_teams/multimodal_design_agent_team/) - Design critiques from a Gemini-powered expert panel
* [🎨 🍌 Multimodal UI/UX Feedback Agent Team](advanced_ai_agents/multi_agent_apps/agent_teams/multimodal_uiux_feedback_agent_team/) - Landing page feedback plus an auto-generated improved version
* [🌏 AI Travel Planner Agent Team](advanced_ai_agents/multi_agent_apps/agent_teams/ai_travel_planner_agent_team/) - A complete trip itinerary, crafted by a team
+* [βš–οΈ LLM Panel Agent Team](advanced_ai_agents/multi_agent_apps/agent_teams/llm_panel_agent_team/) - Three vendors review the same diff blind, then argue it out anonymously
### πŸ—£οΈ Voice AI Agents
diff --git a/advanced_ai_agents/multi_agent_apps/agent_teams/llm_panel_agent_team/README.md b/advanced_ai_agents/multi_agent_apps/agent_teams/llm_panel_agent_team/README.md
new file mode 100644
index 00000000..e080e45a
--- /dev/null
+++ b/advanced_ai_agents/multi_agent_apps/agent_teams/llm_panel_agent_team/README.md
@@ -0,0 +1,189 @@
+# βš–οΈ LLM Panel Agent Team
+
+Several models review the same thing independently, then argue about it. One script, one
+API key, three vendors.
+
+A single reviewer has a single blind spot. Ask three models the same question in the same
+chat and the second one anchors on the first. This team keeps them apart: every model
+gets the identical prompt at the same moment and none of them can see the others. Then,
+optionally, each one is shown the other answers with the names stripped and has to
+UPHOLD, REJECT, CONCEDE or MISSED every finding that touches its own.
+
+It is not a voting machine. The panel generates candidate defects; you still check each
+one against the code. What it adds is independence in round one and, in round two, a
+wrong finding that has to survive being argued with.
+
+## How it works
+
+```
+ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
+ same prompt ─▢│ gpt-5.4-mini │──▢ answer 1 ─┐
+ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ round 2 (--rebut):
+ same prompt ─▢│ claude-haiku-4.5 │──▢ answer 2 ─┼─▢ each model sees the OTHER answers
+ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ as "Reviewer A", "Reviewer B" ...
+ same prompt ─▢│ gemini-3.8-flash │──▢ answer 3 β”€β”˜ (shuffled per model) and takes a
+ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ position on each finding
+ round 1: parallel, no model β”‚
+ sees another's answer β–Ό
+ positions regrouped BY FINDING,
+ disagreements marked CONTESTED
+```
+
+1. **Round 1**: a thread pool sends the prompt to every model at once. Each answer prints
+ in full as it lands, with its latency. A model that errors gets an `error` row, and the
+ others still finish.
+2. **Round 2** (`--rebut`): for each model, the other answers are shuffled and lettered
+ A, B, C... The shuffle is per model, so neither the letter nor the position gives away
+ which vendor wrote which review. The model is asked to start every point with one of
+ four labels and a reference like `B3`, and is told two rules: do not concede just
+ because someone disagreed, and do not invent agreement.
+3. **Grouping**: those `LABEL: B3` lines are parsed and regrouped by the finding they
+ answer, so you read "what did everyone say about finding 3" instead of three documents.
+ A finding with both a REJECT and an UPHOLD is marked CONTESTED. That is where to look
+ first.
+4. **Scoreboard**: tokens and the cost OpenRouter billed, per model and in total.
+
+## Requirements
+
+- Python 3.10+
+- An [OpenRouter](https://openrouter.ai/keys) API key. One key reaches every vendor, and
+ the three default models are deliberately the cheap tier: the run below cost $0.03.
+
+## Installation
+
+```bash
+git clone https://github.com/Shubhamsaboo/awesome-llm-apps.git
+cd awesome-llm-apps/advanced_ai_agents/multi_agent_apps/agent_teams/llm_panel_agent_team
+pip install -r requirements.txt
+export OPENROUTER_API_KEY=sk-or-...
+```
+
+## Usage
+
+Review the sample diff, which has a few defects planted in it, with the rebuttal round:
+
+```bash
+python llm_panel_agent_team.py --file sample_diff.patch --rebut
+```
+
+Ask a question instead of reviewing a file, or pick your own roster:
+
+```bash
+python llm_panel_agent_team.py --question "Is optimistic locking or a queue the better fit for a booking system, and why?"
+python llm_panel_agent_team.py --file my_change.diff --rebut \
+ --models openai/gpt-5.4,anthropic/claude-sonnet-5,google/gemini-3.8-pro,deepseek/deepseek-v4-flash
+```
+
+Any [OpenRouter model id](https://openrouter.ai/models) works. The full panel, including
+both rounds in full, is written to `panel.md` (`--out` to change that).
+
+## Example output
+
+A real run on `sample_diff.patch`, shortened. Round one, all three landing within ten
+seconds:
+
+```
+## anthropic/claude-haiku-4.5 (ok, 2.5s)
+
+1. **orders.py, line 17**: The mutable default argument `seen=[]` will be shared across
+ all function calls ...
+2. **orders.py, line 11**: The condition changed from `>=` to `>`, which changes the
+ discount logic so orders exactly at a threshold no longer qualify ...
+3. **orders.py, line 21**: Bare `except Exception` is too broad and will catch and
+ suppress unexpected errors like `KeyboardInterrupt` or `SystemExit` ...
+
+## openai/gpt-5.4-mini (ok, 2.9s)
+
+1. ... `>` instead of `>=`, so totals exactly on a tier threshold ... receive no discount.
+2. ... Reversing the tiers and returning on the first match ... can skip the correct
+ highest applicable tier if the list is not strictly ordered as expected.
+3. ... catches all exceptions and returns `[]`, which hides real failures ...
+4. ... `seen=[]` default argument is mutable and persists across calls ...
+5. ... `seen` parameter is never used by callers ... making the new side effect dead code.
+6. ... `recent()` now excludes cancelled orders and changes the cutoff comparison ...
+
+## google/gemini-3.8-flash (ok, 10.5s)
+
+1. `orders.py`, line 13: Using `total > threshold` instead of `>=` incorrectly excludes ...
+2. `orders.py`, line 18: `seen=[]` uses a mutable default argument ...
+```
+
+Round two. Note the third finding from claude-haiku: both other models reject it, and
+they are right, since `KeyboardInterrupt` and `SystemExit` derive from `BaseException`
+and are not caught by `except Exception`. That is the round doing its job.
+
+```
+## openai/gpt-5.4-mini rebuts (ok, 3.7s)
+
+UPHOLD: A2 -- `discount_for()` now uses `total > threshold` on line 13, so values exactly
+equal to 100, 500, or 1000 no longer get the tier they previously qualified for.
+UPHOLD: A1 -- `load_orders(path, seen=[])` on line 17 uses a mutable default list ...
+REJECT: A3 -- The code catches `Exception`, which does not include `KeyboardInterrupt`
+or `SystemExit`, so the claim that it suppresses those is incorrect.
+...
+
+## google/gemini-3.8-flash rebuts (ok, 21.2s)
+
+* REJECT: B2 -- The original implementation already assumed ascending tier order by
+ iterating forward and overwriting `rate`, so traversing in reverse does not introduce
+ an ordering dependency that wasn't already present.
+* REJECT: B5 -- Callers can pass an explicit list to `seen` to track loaded paths, so
+ appending to `seen` is not dead code; the issue is solely the mutable default argument.
+...
+```
+
+The positions regrouped by the finding under dispute, and the bill:
+
+```
+| finding | positions | contested |
+|-------------------------------|--------------------------------------------------------|-----------|
+| anthropic/claude-haiku-4.5 #1 | UPHOLD (gpt-5.4-mini); UPHOLD (gemini-3.8-flash) | |
+| anthropic/claude-haiku-4.5 #2 | UPHOLD (gpt-5.4-mini); UPHOLD (gemini-3.8-flash) | |
+| anthropic/claude-haiku-4.5 #3 | REJECT (gpt-5.4-mini); REJECT (gemini-3.8-flash) | |
+| google/gemini-3.8-flash #1 | UPHOLD (gpt-5.4-mini); UPHOLD (claude-haiku-4.5) | |
+| google/gemini-3.8-flash #2 | UPHOLD (gpt-5.4-mini); UPHOLD (claude-haiku-4.5) | |
+| openai/gpt-5.4-mini #1 | UPHOLD (claude-haiku-4.5); UPHOLD (gemini-3.8-flash) | |
+| openai/gpt-5.4-mini #2 | REJECT (claude-haiku-4.5); REJECT (gemini-3.8-flash) | |
+| openai/gpt-5.4-mini #3 | UPHOLD (claude-haiku-4.5); REJECT (gemini-3.8-flash) | CONTESTED |
+| openai/gpt-5.4-mini #4 | UPHOLD (claude-haiku-4.5); UPHOLD (gemini-3.8-flash) | |
+| openai/gpt-5.4-mini #5 | UPHOLD (claude-haiku-4.5); REJECT (gemini-3.8-flash) | CONTESTED |
+| openai/gpt-5.4-mini #6 | UPHOLD (claude-haiku-4.5); REJECT (gemini-3.8-flash) | CONTESTED |
+
+| model | status | time | tokens in/out | cost |
+|----------------------------|--------|-------|---------------|---------|
+| openai/gpt-5.4-mini | ok | 2.9s | 1,599/466 | $0.0033 |
+| anthropic/claude-haiku-4.5 | ok | 2.5s | 1,881/684 | $0.0053 |
+| google/gemini-3.8-flash | ok | 10.5s | 1,813/5,245 | $0.0210 |
+| total | | | | $0.0296 |
+```
+
+Reading it: the two planted bugs (`>` for `>=` on the tier threshold, the mutable default
+`seen=[]`) were found by all three and upheld by all. One false finding was rejected by
+both peers. Three findings are contested, and those are the ones a human should look at:
+one of them (the broad `except` that hides malformed data) is a real problem that
+gemini-3.8-flash talked itself out of. The panel points at where to look; it does not
+decide for you.
+
+## Things worth knowing
+
+- **Anonymity is best effort.** A model that writes in a recognisable style, or names
+ itself in its review, is identifiable to the others no matter what letter it gets.
+- **Round two is the expensive one.** Each rebuttal prompt carries the material again,
+ plus the model's own review and the others' reviews, so it is several times the size of
+ the round-one prompt. Costs scale with that.
+- **Grouping only sees positions that cite a reference.** A position that restates a
+ finding in its own words without `B3` is still printed but cannot be matched, so it
+ argues with nobody. The instructions say this to the model; some ignore it.
+- **One key, many vendors.** OpenRouter is used so the roster can mix vendors without a
+ key per vendor. Any OpenAI-compatible endpoint works if you change `base_url`, but then
+ the `cost` column depends on that endpoint reporting it.
+
+## The full tool
+
+This folder is the idea in one file. The same design, grown up, is
+[llm-panel](https://github.com/musharna/llm-panel) (`pip install llm-panel`), which
+drives the coding-agent CLIs you already have (Codex, Claude Code, opencode, ollama) so
+the judges can read your whole repository rather than a pasted diff, renders the rebuttal
+round as one HTML page grouped by finding, runs as a GitHub Action on every pull request,
+and ships a recall benchmark that measures what a panel misses on real PRs. Disclosure:
+the author of this tutorial is the author of llm-panel.
diff --git a/advanced_ai_agents/multi_agent_apps/agent_teams/llm_panel_agent_team/llm_panel_agent_team.py b/advanced_ai_agents/multi_agent_apps/agent_teams/llm_panel_agent_team/llm_panel_agent_team.py
new file mode 100644
index 00000000..f0beba8f
--- /dev/null
+++ b/advanced_ai_agents/multi_agent_apps/agent_teams/llm_panel_agent_team/llm_panel_agent_team.py
@@ -0,0 +1,230 @@
+"""
+LLM Panel Agent Team: several models review the same thing independently, then argue.
+
+Round 1 Every model on the panel gets the identical prompt at the same time. None of
+ them can see the others. Each answer is printed in full as it lands.
+Round 2 (--rebut) Each model is shown the OTHER answers, anonymised as "Reviewer A",
+ "Reviewer B", ... in a per-model shuffled order, and asked to UPHOLD, REJECT,
+ CONCEDE or MISSED on every finding that touches its own. Positions that cite a
+ finding are then grouped by the finding under dispute.
+
+The point is not a vote. A panel generates candidate defects; a human still checks each
+one against the code. What the panel adds over one reviewer is independence (no anchoring
+on the first answer) and a second round where a wrong finding has to survive being argued.
+
+Every model is called through OpenRouter with the OpenAI SDK, so one key covers vendors.
+
+ export OPENROUTER_API_KEY=sk-or-...
+ python llm_panel_agent_team.py --file sample_diff.patch --rebut
+"""
+
+import argparse
+import os
+import random
+import re
+import string
+import sys
+import time
+from concurrent.futures import ThreadPoolExecutor, as_completed
+from dataclasses import dataclass, field
+
+from openai import OpenAI
+
+DEFAULT_MODELS = [
+ "openai/gpt-5.4-mini",
+ "anthropic/claude-haiku-4.5",
+ "google/gemini-3.8-flash",
+]
+
+REVIEW_TASK = (
+ "Review the following change. Report defects only, as a numbered list, each with the "
+ "file and line it is in and one sentence on why it is wrong. If the change needs no "
+ "comment at all, say so.\n\n"
+)
+
+# The four labels are the contract the grouping step parses. The two rules at the end are
+# what stop round two from collapsing into polite agreement.
+REBUT_INSTRUCTIONS = (
+ "You already reviewed this material independently. Below are the findings of the OTHER "
+ "reviewers. They did not see your review, and their identities are withheld from you on "
+ "purpose.\n\n"
+ "Refer to a finding as <Letter><number>: B7 is Reviewer B's finding 7. Take a position "
+ "on each finding that touches yours:\n"
+ " UPHOLD: B7 -- you stand by your own claim despite theirs; say what proves it.\n"
+ " REJECT: B7 -- theirs is wrong or overstated; point at the specific code or logic "
+ "that makes it wrong.\n"
+ " CONCEDE: B7 -- you were wrong; say exactly what changed your mind.\n"
+ " MISSED: B7 -- they caught something real that you did not; confirm it against the "
+ "code rather than taking their word.\n\n"
+ "Start each point with one of those four labels verbatim, then the reference, then your "
+ "argument.\n\n"
+ "Two rules that matter more than agreeing:\n"
+ "1. Do NOT concede merely because someone disagreed with you. Concede only when you can "
+ "point at what proves you wrong. A correct finding stays correct when it is unpopular.\n"
+ "2. Do NOT invent agreement. If a finding is unverifiable from what you have, say so "
+ "instead of endorsing it.\n\n"
+ "Reviews from the other reviewers follow.\n\n"
+)
+
+POSITION = re.compile(r"^\s*\**\s*(UPHOLD|REJECT|CONCEDE|MISSED)\s*\**\s*:?\s*\**\s*([A-Z]\d+)", re.M)
+
+
+@dataclass
+class Answer:
+ model: str
+ status: str = "ok" # ok | error
+ text: str = ""
+ seconds: float = 0.0
+ tokens_in: int = 0
+ tokens_out: int = 0
+ cost: float = 0.0
+ rebuttal: "Answer | None" = None
+ positions: list = field(default_factory=list) # (label, ref) pairs from the rebuttal
+ letters: dict = field(default_factory=dict) # letter -> model, as this judge saw them
+
+
+def ask(client: OpenAI, model: str, prompt: str, timeout: float) -> Answer:
+ """One model, one prompt. A failure is reported in the row, never raised: one judge's
+ outage must not take the panel down after the others have been paid for."""
+ t0 = time.time()
+ try:
+ r = client.chat.completions.create(
+ model=model,
+ messages=[{"role": "user", "content": prompt}],
+ timeout=timeout,
+ extra_body={"usage": {"include": True}}, # OpenRouter returns the billed cost
+ )
+ text = (r.choices[0].message.content or "").strip()
+ if not text:
+ return Answer(model, "error", f"empty answer (finish_reason={r.choices[0].finish_reason})",
+ time.time() - t0)
+ u = r.usage
+ return Answer(model, "ok", text, time.time() - t0,
+ getattr(u, "prompt_tokens", 0) or 0, getattr(u, "completion_tokens", 0) or 0,
+ float(getattr(u, "cost", 0.0) or 0.0))
+ except Exception as e: # reported, not swallowed: the row says what happened
+ return Answer(model, "error", f"{type(e).__name__}: {e}", time.time() - t0)
+
+
+def round_one(client, models, prompt, timeout) -> list[Answer]:
+ print(f"round 1: asking {len(models)} models in parallel\n", flush=True)
+ answers = {}
+ with ThreadPoolExecutor(len(models)) as ex:
+ futures = {ex.submit(ask, client, m, prompt, timeout): m for m in models}
+ for f in as_completed(futures):
+ a = f.result()
+ answers[a.model] = a
+ print(f"## {a.model} ({a.status}, {a.seconds:.1f}s)\n\n{a.text}\n", flush=True)
+ return [answers[m] for m in models]
+
+
+def round_two(client, answers, prompt, timeout) -> None:
+ ok = [a for a in answers if a.status == "ok"]
+ if len(ok) < 2:
+ print("rebuttal round skipped: it needs at least two answers to argue about\n")
+ return
+ print(f"round 2: {len(ok)} models read each other's findings, anonymised\n", flush=True)
+
+ def one(me: Answer):
+ # A fresh shuffle per model: if the letters or their order were fixed, position
+ # alone would tell a model which rival wrote which review.
+ others = [o for o in ok if o is not me]
+ random.shuffle(others)
+ letters = {o.model: L for o, L in zip(others, string.ascii_uppercase)}
+ me.letters = {L: m for m, L in letters.items()} # letter -> model, for grouping
+ blocks = "\n\n".join(f"### Reviewer {letters[o.model]}\n{o.text}" for o in others)
+ p = f"{prompt}\n\n---\n\nYour own review was:\n\n{me.text}\n\n---\n\n{REBUT_INSTRUCTIONS}{blocks}"
+ me.rebuttal = ask(client, me.model, p, timeout)
+ if me.rebuttal.status == "ok":
+ me.positions = [(lab, ref) for lab, ref in POSITION.findall(me.rebuttal.text)]
+
+ with ThreadPoolExecutor(len(ok)) as ex:
+ list(ex.map(one, ok))
+ for a in ok:
+ r = a.rebuttal
+ print(f"## {a.model} rebuts ({r.status}, {r.seconds:.1f}s)\n\n{r.text}\n", flush=True)
+
+
+def grouped_positions(answers) -> list[str]:
+ """Round two, regrouped by the finding argued about instead of by who spoke."""
+ rows = {} # (author model, finding number) -> [(label, by model)]
+ for a in answers:
+ for lab, ref in a.positions:
+ author = a.letters.get(ref[0])
+ if author is None:
+ continue # a letter that was not in this model's packet
+ rows.setdefault((author, int(ref[1:])), []).append((lab, a.model))
+ if not rows:
+ return ["_No position cited a finding reference, so there is nothing to group._"]
+ out = ["| finding | positions | contested |", "|---|---|---|"]
+ for (author, n), ps in sorted(rows.items()):
+ labels = {lab for lab, _ in ps}
+ contested = "CONTESTED" if labels & {"REJECT"} and labels & {"UPHOLD", "MISSED"} else ""
+ out.append(f"| {author} #{n} | " + "; ".join(f"{lab} ({by})" for lab, by in ps) + f" | {contested} |")
+ return out
+
+
+def scoreboard(answers) -> list[str]:
+ out = ["| model | status | time | tokens in/out | cost |", "|---|---|---|---|---|"]
+ for a in answers:
+ ti, to, c = a.tokens_in, a.tokens_out, a.cost
+ if a.rebuttal:
+ ti += a.rebuttal.tokens_in; to += a.rebuttal.tokens_out; c += a.rebuttal.cost
+ out.append(f"| {a.model} | {a.status} | {a.seconds:.1f}s | {ti:,}/{to:,} | ${c:.4f} |")
+ out.append(f"| **total** | | | | **${sum(a.cost + (a.rebuttal.cost if a.rebuttal else 0) for a in answers):.4f}** |")
+ return out
+
+
+def write_panel(path, answers, question, rebut):
+ lines = ["# Panel", "", *scoreboard(answers), ""]
+ if rebut:
+ lines += ["## Positions by finding", "", *grouped_positions(answers), ""]
+ lines += ["## Question", "", question, ""]
+ for a in answers:
+ lines += ["---", "", f"## {a.model} ({a.status}, {a.seconds:.1f}s)", "", a.text, ""]
+ if a.rebuttal:
+ lines += [f"### {a.model} in the rebuttal round ({a.rebuttal.status})", "", a.rebuttal.text, ""]
+ with open(path, "w") as f:
+ f.write("\n".join(lines))
+
+
+def main():
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ src = ap.add_mutually_exclusive_group(required=True)
+ src.add_argument("--question", help="ask the panel this")
+ src.add_argument("--file", help="review this file (a diff, a design doc, a function...)")
+ ap.add_argument("--models", default=",".join(DEFAULT_MODELS),
+ help="comma-separated OpenRouter model ids (default: one per vendor)")
+ ap.add_argument("--rebut", action="store_true", help="add the anonymised rebuttal round")
+ ap.add_argument("--timeout", type=float, default=300, help="seconds per model per round")
+ ap.add_argument("--out", default="panel.md", help="where the full panel is written")
+ a = ap.parse_args()
+
+ key = os.environ.get("OPENROUTER_API_KEY")
+ if not key:
+ sys.exit("set OPENROUTER_API_KEY (https://openrouter.ai/keys)")
+ client = OpenAI(base_url="https://openrouter.ai/api/v1", api_key=key)
+
+ if a.file:
+ with open(a.file) as f:
+ material = f.read()
+ prompt = REVIEW_TASK + f"```\n{material}\n```"
+ question = f"Review `{a.file}`"
+ else:
+ prompt = question = a.question
+
+ models = [m.strip() for m in a.models.split(",") if m.strip()]
+ answers = round_one(client, models, prompt, a.timeout)
+ if a.rebut:
+ round_two(client, answers, prompt, a.timeout)
+ print("## Positions by finding\n\n" + "\n".join(grouped_positions(answers)) + "\n")
+ print("\n".join(scoreboard(answers)))
+ write_panel(a.out, answers, question, a.rebut)
+ print(f"\nfull panel written to {a.out}")
+ failed = [x.model for x in answers if x.status != "ok"]
+ if failed:
+ sys.exit(f"{len(failed)} of {len(answers)} models did not answer: {', '.join(failed)}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/advanced_ai_agents/multi_agent_apps/agent_teams/llm_panel_agent_team/requirements.txt b/advanced_ai_agents/multi_agent_apps/agent_teams/llm_panel_agent_team/requirements.txt
new file mode 100644
index 00000000..60b41c85
--- /dev/null
+++ b/advanced_ai_agents/multi_agent_apps/agent_teams/llm_panel_agent_team/requirements.txt
@@ -0,0 +1 @@
+openai>=1.50.0
diff --git a/advanced_ai_agents/multi_agent_apps/agent_teams/llm_panel_agent_team/sample_diff.patch b/advanced_ai_agents/multi_agent_apps/agent_teams/llm_panel_agent_team/sample_diff.patch
new file mode 100644
index 00000000..953cf59a
--- /dev/null
+++ b/advanced_ai_agents/multi_agent_apps/agent_teams/llm_panel_agent_team/sample_diff.patch
@@ -0,0 +1,47 @@
+diff --git a/orders.py b/orders.py
+index 3f1c2aa..9b7d4e1 100644
+--- a/orders.py
++++ b/orders.py
+@@ -1,24 +1,31 @@
+ import json
++import logging
+ from datetime import datetime
+
++log = logging.getLogger(__name__)
++
+ DISCOUNT_TIERS = [(100, 0.05), (500, 0.10), (1000, 0.15)]
+
+
+-def discount_for(total):
+- rate = 0.0
+- for threshold, r in DISCOUNT_TIERS:
+- if total >= threshold:
+- rate = r
+- return rate
++def discount_for(total, tiers=DISCOUNT_TIERS):
++ # Tiers are checked from the top so the first match is the best rate.
++ for threshold, rate in reversed(tiers):
++ if total > threshold:
++ return rate
++ return 0.0
+
+
+-def load_orders(path):
+- with open(path) as f:
+- return json.load(f)
++def load_orders(path, seen=[]):
++ try:
++ with open(path) as f:
++ orders = json.load(f)
++ except Exception:
++ log.warning("could not read %s", path)
++ return []
++ seen.append(path)
++ return orders
+
+
+ def recent(orders, days=30):
+- cutoff = datetime.now().timestamp() - days * 86400
+- return [o for o in orders if o["ts"] >= cutoff]
++ cutoff = datetime.now().timestamp() - days * 86400
++ return [o for o in orders if o["ts"] > cutoff and o.get("status") != "cancelled"]