Courses / AI Engineering: LLMs, RAG and Agentic System Design / Chapter 19
Module 9 · Case studies: diagnosis teams and personal assistants · Chapter 19 of 24
Case study: a multi-agent medical diagnosis simulator
Builds on AI agents and multi-agent systems and Agent design fundamentals. Next up: Case study: a personal AI assistant.
Part 1 · The problem and its limits
What the simulator is for
Language models answer medical exam questions well, and a real consultation is not an exam question: the facts arrive one answer at a time, and the doctor decides what to ask next. This chapter builds a small simulator that tests how a model behaves in that setting.
Every patient here is invented. Every test result is made up for the exercise. Nothing in this chapter tells anyone what to do about a symptom, and no output of these programs is a diagnosis. In a real setting a qualified clinician makes every decision, and the system's own output says so each time. If you or someone you know is unwell, ask a doctor or call your local emergency number.
The design follows the AI Hospital paper (Fan et al., 2024). In it, a doctor played by the language model under test talks to simulated characters: a patient, an examiner who supplies test results, and a chief physician. The authors built the Multi-View Medical Evaluation benchmark (MVME) on Chinese medical records to score symptom collection, examination recommendations and diagnosis. They also describe a dispute-resolution mechanism in which models discuss a case, and they report significant performance gaps for current models in multi-turn interaction compared with a one-step setting. A related simulator, Agent Hospital (Li et al., 2024), runs a whole simulated hospital of model-driven patients, nurses and doctors. This chapter borrows the idea, not the data: the code, the records and the numbers are our own, and they are small.
A simulator here means a controlled stand-in for a real process, built so that a system can be tested against it. Multi-turn means the doctor must ask, wait, and ask again, as opposed to one-step, where everything is handed over at once and the model answers in one go.
Requirements
Functional requirements:
- Hold several made-up patient records, each with symptoms, tests and a hidden answer.
- Let a doctor under test ask questions and request tests, one per turn, with a turn limit.
- Answer questions and test requests from the record only.
- End with a diagnosis, reviewed by a chief physician role.
- Score each consultation in code: symptoms covered, tests requested and diagnosis.
- Compare multi-turn with one-step, and a single doctor with a small team.
Non-functional requirements:
| Quality | Target | What it forces |
|---|---|---|
| Isolation | No role sees what it should not | Each role's input is built by code, then checked for leaks |
| Grounding | A patient or examiner can say only what its record says | The model chooses, code speaks |
| Bounded runs | A consultation ends | A turn limit and a forced final answer |
| Objective scores | A model never grades itself | Scoring functions over the record |
| Safe by default | Output never reads as medical advice | A fixed notice, invented data, a referral outcome |
Two of these deserve a sentence each. Grounding means that every statement a character makes traces to its record. If a model were free to write the patient's replies, it could invent a symptom, and the score for "did the doctor find the symptom" would measure the model's imagination. And a referral outcome is a result type that means "no consensus, a person must decide". A system like this should have one from the start, because the honest answer to a hard case is sometimes "not sure".
Four invented patients
The records are plain JSON. Each has an age, a sex, a complaint in the patient's words, a hidden diagnosis and the wording that counts as correct, a set of facts the patient can give, and a set of tests the examiner can run. Each fact and test carries need: true when a thorough doctor should find it.
The symptom lists were checked against the NHS pages, opened on 22 and 23 November 2026. The urinary tract infection page (last reviewed 11 July 2025) lists discomfort or stinging when urinating, needing to urinate more often, cloudy urine, pain in the lower abdomen and fever among the signs. The asthma symptoms page (reviewed 7 April 2025) lists wheezing, coughing, shortness of breath and a tight chest, which may be worse at night and early in the morning, and mentions a breathing test and a handheld peak flow meter. The iron deficiency anaemia page (reviewed 26 January 2024) lists fatigue, breathlessness, heart palpitations, paler skin and headaches, and says a GP usually diagnoses it with a full blood count. The records use those signs in our own wording. Records r1 to r3 are one illness each. Record r4 is built to be harder: a woman whose breathlessness and night cough could point to a lung problem, while her blood count, once someone asks for it, points to the same anaemia as r3. The chapter uses it to see what happens when doctors disagree. The test results, such as "leucocytes and nitrite positive", are invented values for the simulation and are not clinical reference data.
Checking a record before use
Each record is plain data, and plain data can be wrong. A short example shows the shape of one.
{
"id": "r2", "age": 17, "sex": "male",
"complaint": "I keep coughing at night and my chest feels tight.",
"diagnosis": "asthma", "accept": ["asthma"],
"facts": {
"wheeze": {"say": "Yes, a whistling sound when I breathe out.",
"need": true},
"fever": {"say": "No fever.", "need": false}
},
"tests": {
"peak_flow": {"say": "Peak flow diary: readings vary widely.",
"need": true},
"urine_test": {"say": "Urine test: normal.", "need": false}
}
}Record r2 with two of its eight facts and two of its four tests. The full files are in the lab.
A Pydantic model validates every record before a role sees it. It rejects a record with no required fact or no required test, because a record like that would give every consultation a perfect score for free.
class Record(BaseModel): id: str age: int = Field(ge=0, le=120) sex: str complaint: str diagnosis: str accept: list[str] = Field(min_length=1) facts: dict[str, Item] tests: dict[str, Item] @model_validator(mode="after") def something_is_needed(self): if not any(f.need for f in self.facts.values()): raise ValueError("no required fact") if not any(t.need for t in self.tests.values()): raise ValueError("no required test") return self
The record schema; the extra rule runs after the fields are checked.
r1: 31 y female facts 8 (need 4), tests 3 (need 1), answer: urinary tract infection r2: 17 y male facts 8 (need 4), tests 4 (need 2), answer: asthma r3: 38 y female facts 8 (need 4), tests 3 (need 1), answer: iron deficiency anaemia r4: 44 y female facts 8 (need 4), tests 3 (need 1), answer: iron deficiency anaemia
Output from records.py. 'Need' counts the facts and tests a thorough doctor should find. Long lines are wrapped here.
Why is record r4 built to be ambiguous?
- Easy records make every doctor agree, so a dispute step would never run. One record with overlapping signs gives the team something to disagree about.
- The ambiguity lives in the invented record, and its answer is still fixed in advance.
Why does each fact carry a need flag instead of scoring every fact?
Part 2 · Roles and what each may see
Four roles, four views
A consultation has four parts to play. The doctor under test is the model being evaluated. The patient knows the symptoms and nothing else. The examiner can run tests and report results. The chief physician reviews the doctor's conclusion. In the AI Hospital paper the doctor is the player and the other three are non-player characters, a split this design keeps.
| Role | Sees | Never sees | Does |
|---|---|---|---|
| Doctor under test | Age, sex and the patient's first complaint | Facts, test results, the answer | Asks, requests tests, diagnoses |
| Patient | Its own history, as a list of facts | Test results, the diagnosis | Picks the facts a question asks about |
| Examiner | The names of the tests it can run | Symptoms, the diagnosis | Picks the test a request means |
| Chief physician | The transcript and the doctor's diagnosis | The record, the answer | Says whether the transcript supports the diagnosis |
SeesAge, sex and the patient's first complaint
Never seesFacts, test results, the answer
DoesAsks, requests tests, diagnoses
The model chooses, code speaks
Free-text replies from a role-playing model have two flaws for an evaluation. They can add symptoms that are not in the record, and they cannot be counted, because you would need a second model to read each reply and decide which facts it contained. Both flaws disappear if the character only chooses.
The patient is shown its facts, each with an id, and the doctor's question. Its answer is the list of fact ids the question asks about, constrained to the ids that exist. Code then speaks for the patient: it joins the stored sentences for those ids. A question about something not in the history selects nothing, and the patient says it does not understand. The examiner works the same way over test ids, with a none choice for a test that is not offered.
def patient_reply(rec, question): ids = tuple(rec["facts"]) class Pick(BaseModel): fact_ids: list[Literal[ids]] system = ("You are a patient in a simulator. Pick the ids of the " "facts in your history that the doctor's question asks " "about. Pick none if the question is about something " "else.\n" + patient_view(rec)) pick = ask(Pick, system, f"Doctor asks: {question}") if pick is None or not pick.fact_ids: return "I am not sure what you mean.", [] ids_ = list(dict.fromkeys(pick.fact_ids)) return " ".join(rec["facts"][i]["say"] for i in ids_), ids_
The model picks fact ids; stored sentences are the reply.
This costs some naturalness: the patient sounds like a form. It gains three things. A statement can only come from the record. The list of ids the doctor uncovered is exact, so symptom coverage is a set operation rather than a judgement. And the schema keeps an invalid id from existing at all, since the choice type only admits the record's own ids. Where the free text of a real conversation matters, as it would in a real study, a model would phrase the stored facts. The facts it could use would still come from the record.
Proving the views are clean
The roles' inputs come from three small functions. A visibility check builds each role's view for a record and searches it for phrases that role must never contain: the diagnosis and its accepted wordings for everybody, test results for the patient and the doctor, symptom sentences for the examiner and the doctor.
def check_visibility(rec): """Return {role: leaked phrases}; empty dict means all clean.""" out = {} for role, fn in VIEWS.items(): found = leaks(rec, fn(rec), banned_for(rec, role)) if found: out[role] = found return out
The check is run on all four records and then on a record with a planted leak, a patient fact that says "the nurse said it is asthma". A check that never fails proves nothing, so the second run matters as much as the first.
--- doctor sees: Patient: 31-year-old female. Says: It hurts when I pass urine. --- patient sees: Your own history (you know nothing else): - burning: Yes, there is a burning pain every time I pass urine. It started two days ago. - frequency: I need to go much more often than usual, even at night. - belly_pain: I have a dull ache low in my tummy. - fever: No, I have not had a fever or the shivers. - back_pain: No pain in my back under the ribs. - pregnant: No, I am not pregnant. - blood: The urine looks cloudy, but I have not seen blood. - cough: No cough or breathing trouble. --- examiner sees: Tests you can run: urine_test, blood_count, peak_flow --- leak check on the four records: [{}, {}, {}, {}] --- leak check on a record with a planted leak: {'patient': ['asthma']}
Output from show_views.py: the three views for record r1, then both leak checks. Long lines are wrapped here.
The clean records produce empty results, and the planted leak is found in the patient's view. The phrase search ignores case, hyphens and underscores, so a test named urinary_tract_infection_dipstick in the examiner's list is found too, and a test covers that case. The search is simple and has a clear limit. It catches the diagnosis written out, not a hint such as "the infection" with no name attached. A record author still has to write facts that describe the patient and do not interpret.
Why does the patient role choose fact ids instead of writing its own reply?
- A written reply can contain symptoms that are not in the record, and counting which facts the doctor found would need another model.
Part 3 · The consultation loop
One turn at a time
A consultation is a loop with three kinds of move. The doctor can ask the patient a question, test by requesting a test from the examiner, or diagnose, which ends the loop. Every turn the doctor sees the patient's age and sex, the first complaint and the transcript so far, and replies with a move in a fixed schema: an action name and some text.
A turn limit bounds the run. The doctor gets at most six questions and tests in total, and the prompt says so. If it uses them all without diagnosing, the loop ends anyway and a final call asks for the most likely diagnosis from what is in the transcript. A consultation therefore costs at most six doctor calls, six patient or examiner calls, one final call and one review call: fourteen model calls in the worst case.
def take_turn(rec, turns, st, limit): """One doctor move. Returns False when the doctor is done.""" user = (doctor_view(rec) + "\nTranscript so far:\n" + transcript_text(turns) + "\nYour next action?") move = ask(Move, doctor_prompt(limit), user, max_tokens=120) if move is None: # malformed or truncated: lose a turn st["bad"] += 1 turns.append(("System", "The doctor's move was not valid.")) elif move.action == "diagnose": return False elif move.action == "ask": reply, ids = patient_reply(rec, move.text) st["facts"] += ids turns += [("Doctor", move.text), ("Patient", reply)] else: reply, tid = examiner_reply(rec, move.text) st["tests"].append(tid) turns += [("Doctor asks for a test", move.text), ("Examiner", reply)] return True
One doctor move. A bad move costs a turn and does not crash the run.
A malformed or truncated reply from the doctor, which the schema call reports as no result, is written into the transcript as a system note and uses up a turn. It is not retried and not raised. A request for a test the examiner does not offer is recorded as None, so the doctor learns that the test is not available and the score does not credit it.
A real consultation
Record r1 is the urinary case. The run below is one real consultation, printed as the program saw it: the transcript, then the diagnosis and the chief physician's review, then the score computed in code.
def consult(rec, limit=MAX_TURNS): turns = [("Patient", rec["complaint"])] st = {"facts": [], "tests": [], "bad": 0} for _ in range(limit): if not take_turn(rec, turns, st, limit): break verdict = final_verdict(rec, turns) review = chief_review(turns, verdict) if verdict else None return {"turns": turns, "facts": sorted(set(st["facts"])), "tests": st["tests"], "bad_moves": st["bad"], "verdict": verdict, "review": review}
Patient: It hurts when I pass urine. Doctor: Can you describe the type of pain you're experiencing (e.g., burning, stinging, or cramping) and do you have any urgency or frequency issues? Patient: Yes, there is a burning pain every time I pass urine. It started two days ago. I need to go much more often than usual, even at night. Doctor asks for a test: urinalysis Examiner: Urine test: leucocytes and nitrite positive. VERDICT diagnosis='Urinary Tract Infection (UTI)' reason='The presence of leukocyte and nitrite in the urine, combined with symptoms of burning pain and increased frequency, indicates a bacterial infection of the urinary tract.' REVIEW supported=True missing='While the current evidence is highly suggestive of a UTI, a complete assessment would ideally include a physical examination (to check for tenderness or localized pain) and a culture of the urine sample to identify the specific causative pathogen and its antibiotic sensitivity.' {'symptoms': 0.5, 'tests': 1.0, 'extra_tests': 0, 'diagnosis': True} calls 7
Output from try_one.py for record r1, one run. The doctor's wording differs between runs. Long lines are wrapped here.
Watch for what the doctor never asks the patient
Read it as steps
Stages and limits
The loop is a small state machine. It opens when the patient gives the first complaint, moves between asking and testing, and leaves through diagnosing to review. Review is a final state: nothing happens after it, and any further question is rejected.
Watch for the turn limit forcing a diagnosis
Read it as steps
The consultation opens, loops between asking and testing, then moves to a diagnosis and a review.
The scene ends with a rejected event on purpose. A state machine is useful because it says what cannot happen. After the review the consultation is over, and a question has no transition. In code the same guarantee comes from the loop structure: the for loop has at most six iterations and the final call is made once, outside it.
Four tests check the loop without the model, by replacing it with a script. They cover the turn limit, invalid moves, an unavailable test and the scoring rule. The turn-limit test feeds twenty questions and checks that the transcript stops at one opening line plus six exchanges.
test_consult.py::test_turn_limit_forces_a_diagnosis PASSED test_consult.py::test_invalid_moves_use_up_turns_without_crashing PASSED test_consult.py::test_unavailable_test_is_not_scored PASSED test_consult.py::test_score_counts_only_required_facts_and_tests PASSED 4 passed in 0.50s
Output from test_consult.py. The model is replaced by a scripted function. Timing varies on this machine.
Part 4 · Evaluating multi-turn diagnosis
What gets scored, and by whom
A consultation produces a transcript, a list of facts found, a list of tests requested and a diagnosis. Three things are scored, all in code. Symptom coverage is the share of the record's required facts the doctor found. Test recommendation is the share of required tests the doctor requested, with a count of extra tests beside it. Diagnosis is whether the stated diagnosis matches an accepted name for the record's answer. No model grades any of them, because a model grading a model would add its own errors to the measurement.
def diagnosis_ok(text, accept): return any(mentions(text, a) for a in accept)
A name must appear, and a negation just before it cancels the match.
def score(rec, result): need_f = {k for k, v in rec["facts"].items() if v["need"]} need_t = {k for k, v in rec["tests"].items() if v["need"]} asked = set(result["facts"]) ran = {t for t in result["tests"] if t} v = result["verdict"] return { "symptoms": len(need_f & asked) / len(need_f), "tests": len(need_t & ran) / len(need_t), "extra_tests": len(ran - need_t), "diagnosis": bool(v) and diagnosis_ok(v.diagnosis, rec["accept"]), }
The string match is crude and meant to be. It accepts "Asthma" and "likely asthma, mild", and it refuses "not asthma" because the word not sits within twelve characters before the match. It would still accept "asthma ruled out by the second test" and refuse "asthma" written in another language. A larger study would use coded diagnoses, not free text, so that a match did not depend on spelling.
Notice what the score leaves out: how good the questions were, whether the doctor was kind, whether the reasoning was sound. It scores what can be counted from the record. The chief physician's review is kept as a note and is not part of the score.
test_med.py::test_no_role_sees_what_it_should_not PASSED test_med.py::test_a_leaky_record_is_caught PASSED test_med.py::test_diagnosis_matching_handles_wording_and_negation PASSED test_med.py::test_resolution_rule PASSED test_med.py::test_canon_merges_synonyms PASSED test_med.py::test_turn_limit_is_set PASSED test_med.py::test_record_schema_rejects_a_broken_one PASSED test_med.py::test_matching_uses_whole_words_and_keeps_negation PASSED test_med.py::test_a_leak_inside_a_test_name_is_caught PASSED test_med.py::test_canon_merges_an_acronym_with_its_name PASSED 10 passed in 0.52s
Output from test_med.py. Two tests cover negation; four cover the record checks. Timing varies on this machine.
One-step against multi-turn
The one-step mode gives the doctor every fact and every test result in a single prompt and asks for a diagnosis. The multi-turn mode is the consultation from lesson 3. Both are run on all four records, three times each, so 12 consultations per mode. The doctor is the same model in both, gemma4:12b, so the difference is the setting, not the model.
for rep in range(N): for rec in load_records(): t = time.time() res = consult(rec) row = {"rep": rep, "rec": rec["id"], "mode": "multi", **score(rec, res), "turns": len(res["turns"]), "bad": res["bad_moves"], "dx": (res["verdict"].diagnosis if res["verdict"] else None), "supported": (res["review"].supported if res["review"] else None), "sec": round(time.time() - t, 1)} print(json.dumps(row), flush=True)
From run_med.py: the multi-turn half of the loop. The one-step half has the same shape and calls one_step.
consultations per mode: 12 diagnosis right one-step 12 / 12 multi 10 / 12 multi-turn, per record: r1: right 3/3, symptoms 0.67, tests 1.00, extra tests 0, transcript lines 5.0 r2: right 3/3, symptoms 0.50, tests 0.67, extra tests 0, transcript lines 13.0 r3: right 3/3, symptoms 0.42, tests 1.00, extra tests 0, transcript lines 13.0 r4: right 1/3, symptoms 0.50, tests 0.33, extra tests 2, transcript lines 13.0 symptom coverage overall 0.52 required tests requested overall 0.75 invalid moves: 0 wrong: r4 multi 'Asthma' wrong: r4 multi 'Gastroesophageal reflux disease (GERD)'
Output from summarise.py over med_runs.jsonl. One model, 12 consultations per mode. Long lines are wrapped here.
The one-step mode was right 12 times in 12. The multi-turn mode was right 10 times in 12, and both misses were on record r4: once the doctor answered "Asthma" and once "Gastroesophageal reflux disease (GERD)". An earlier saved pass of the same script also gave 12 of 12 and 10 of 12, with the misses on r3 ("Inconclusive / Insufficient data") and r4 ("Asthma"). Same totals, different misses: that is what model variation looks like.
Coverage is the more telling number. In multi-turn mode the doctors found 52 per cent of the required facts and requested 75 per cent of the required tests overall; the earlier pass gave 60 and 75. On r4 they requested the blood count in one run of three, and that was the run that got the diagnosis right. The doctors who did not ask for it had nothing pointing at anaemia, and the signs they did have, a night cough and breathlessness, pointed to the wrong answer. No invalid moves occurred in the 12 consultations.
Reading the result with care
The AI Hospital paper reports that current models do worse in multi-turn interaction than in a one-step setting. The direction here is the same: 12 of 12 against 10 of 12, in both passes. The size of the gap is not something to quote. Twelve consultations on four invented records is too few for a rate. A single different result would move it by about eight points, and the three repeats of each record are not independent cases. This run shows that the harness can measure a difference. It does not measure how big that difference is for any real use.
The misses are worth a look, because they come in two kinds. The answers "Asthma" and "GERD" on r4 are wrong diagnoses reached from thin evidence, which is the failure the multi-turn setting is built to expose. The record was designed so that its first signs fit more than one explanation. The answer "Inconclusive / Insufficient data" in the earlier pass is a refusal to guess. A scorer that counts it as wrong treats it like a confident wrong answer, and a real study would score abstentions separately, since in medicine saying "I need more information" is sometimes the right move.
A last caution about the doctors' tests. In this harness the model sees a patient who only says what its record holds, so a question phrased unexpectedly may select no fact at all and get the reply "I am not sure what you mean". That is a limit of the thin patient design from lesson 2, and it lowers coverage for reasons that have little to do with medical skill.
Why is the diagnosis scored by code and not by asking another model?
- A grading model adds its own errors to the measurement. Code over a fixed answer list is repeatable.
- The price is a crude match on wording, which is why the negation rule and its tests exist.
The multi-turn mode was right 10 times in 12 and the one-step mode 12 in 12. What can you say?
- The direction matches the paper's finding, and the harness can show a difference.
- You cannot quote the size of the gap: 12 consultations on 4 invented records is too few, and the repeats are not independent.
Part 5 · Several doctors and a dispute step
Independent answers, one discussion, a rule
One doctor can be wrong. A team of doctors might catch each other's mistakes, if they think differently and if disagreement has somewhere to go. The AI Hospital paper describes a dispute-resolution mechanism in which several doctors discuss to improve the diagnosis. Its abstract does not describe the mechanics, so this design is ours.
Three doctor calls read the same transcript and answer alone, at temperature 1.0 so that they can differ. If all three give the same diagnosis after wording is normalised, the team is done. If not, each doctor sees the other two answers and their reasons, once, and may keep or change its own. A reply carries a changed flag, and "keep" in the diagnosis field is read as no change: unguarded, the word counted as a fourth diagnosis. Then a plain rule decides: the majority answer wins, and a tie, or no answers at all, returns a referral outcome that says no consensus was reached and a clinician must decide.
def discuss(turns, first): """Each doctor sees the others' answers once and may revise.""" revised = [] for i, mine in enumerate(first): others = "\n".join(f"- {o.diagnosis}: {o.reason}" for j, o in enumerate(first) if j != i) user = ("Transcript:\n" + transcript_text(turns) + f"\nYour diagnosis: {mine.diagnosis}\nOther doctors:\n" f"{others}\nGive your final diagnosis by name. Set " "changed to true only if it differs from your first.") r = ask(Revised, "You are one of several doctors. " + NOTICE, user, max_tokens=100, temperature=1.0) keep = (r is None or not r.changed or r.diagnosis.strip().lower() in ("keep", "same")) revised.append(mine.diagnosis if keep else r.diagnosis) return revised
def resolve(answers): """Majority of canonical answers; a tie or no answers refers on.""" if not answers: return REFER counts = Counter(canon(a) for a in answers).most_common() if len(counts) > 1 and counts[0][1] == counts[1][1]: return REFER return counts[0][0]
The rule. A tie is not broken at random.
Five small tests check the flow with a scripted model. Agreement skips the discussion. A disagreement triggers exactly one round. A three-way split is referred. A reply of "keep" is not counted as a diagnosis. The guard knows only "keep" and "same". And a doctor call that returns nothing leaves fewer voices, not a crash: with no voices at all, the result is a referral.
What the team did
The team needs a transcript to read, and how much the doctor found decides everything. To get a fixed input, the first run gives the doctors the first complaint only, with no questions and no tests, so the evidence is as thin as it can be. It ran three times on each of the four records. The listing gives, for each run, whether the doctors agreed at once and what the rule resolved.
r1 transcript: tests none, facts none run 1 agreed -> urinary tract infection (right) run 2 agreed -> urinary tract infection (right) run 3 agreed -> urinary tract infection (right) r2 transcript: tests none, facts none run 1 agreed -> asthma (right) run 2 agreed -> asthma (right) run 3 agreed -> asthma (right) r3 transcript: tests none, facts none run 1 agreed -> fatigue and headache (wrong) run 2 discussed -> fatigue and headache (wrong) first: fatigue and hea | fatigue and cep | fatigue and hea after: fatigue and hea | fatigue and cep | fatigue and hea run 3 agreed -> fatigue and headache (wrong) r4 transcript: tests none, facts none run 1 agreed -> asthma (wrong) run 2 agreed -> asthma (wrong) run 3 agreed -> asthma (wrong)
Output from summarise_team.py with run_team.py 3 0: the first complaint only. Names are shortened to 18 characters after normalising.
Watch for the doctor who changes their answer
Read it as steps
Three doctors read one transcript. The wording differs, they see each other's answers, nobody changes and the majority is wrong.
Reading the tally
complaint_only.jsonl: 12 team results, 6 right; 11 unanimous at first, 5 of those wrong; 1 went to discussion two_moves_1.jsonl: 12 team results, 12 right; 12 unanimous at first, 0 of those wrong; 0 went to discussion two_moves_2.jsonl: 12 team results, 12 right; 12 unanimous at first, 0 of those wrong; 0 went to discussion
Output from tally_team.py over three passes of run_team.py: the first complaint only, then two passes where the doctor could make two moves first. Long lines are wrapped here.
Read the tally. With the first complaint only, 6 of 12 team results were right, 11 of 12 began unanimous, 5 of those 11 were wrong, and the discussion ran once. When the doctor was allowed two moves first, 24 of 24 team results were right and all 24 began unanimous. In those passes the doctor had asked about several symptoms and had requested the blood count on r3 and r4, so the team had more to read. What the team did mostly depended on the transcript, not on the discussion step, and the dispute step ran in only 1 of 36 team results. An earlier saved pass, run on an earlier version of the code, had the discussion run in 3 of 12 and the third doctor change its answer once. One model, these runs.
Design review and extensions
Agreement is a signal about the doctors, not about the patient. It is only useful when the doctors can make independent mistakes. Three samples of one model at a higher temperature are the cheapest team and the least independent. Different prompts, different models or a doctor who must argue the opposite case would be more independent, and all cost more.
| Extension | What it buys | What it costs |
|---|---|---|
| Doctors from different models | Mistakes less likely to match | More servers to run; harder to compare |
| Coded diagnoses in place of free text | Exact agreement and scoring; no 'headache' against 'cephalgia' split | A vocabulary and a way to map text to codes |
| Abstention as its own outcome | Honest 'need more information' | A scoring rule that values it fairly |
| Force a minimum of questions before a diagnosis | Fewer answers from empty transcripts | A longer consultation and more calls |
| A patient that phrases the stored facts | More natural questions work | A model between the record and the doctor to keep honest |
| Human review of every referral | A person decides the hard cases | Someone's time, and a queue |
Safety and review prompts
Breakout prompts to work through, with no model needed:
- The rule returns a referral on a tie. Under what circumstances would you rather have it pick the answer with the most cautious next step? Write the rule in two sentences.
- Three doctors agree on a wrong answer. Which signal in the chapter would have told you something was off, and what would you add to read it?
- A hospital asks to run this simulator on real patient records. List what would have to be true first, beyond the code, before you would agree.
- Suppose the chief physician's review says "supported" for a wrong diagnosis. What does that say about using its note as a score?
Say it plainly once more. This is a simulator with invented patients. It tests how a system of model roles behaves and how to measure it. It is not a tool for diagnosis, and none of its outputs, including the team's, is medical advice. The design puts the person last: every referral, and every real-world decision, belongs to a clinician.
| Term | Meaning |
|---|---|
| Simulator | A controlled stand-in for a real process, used to test a system |
| Multi-turn | A conversation in which each move depends on the last reply |
| One-step | All facts given at once, one answer returned |
| Symptom coverage | Share of required facts the doctor found |
| Dispute step | A round in which doctors see each other's answers |
| Referral outcome | A result that says no consensus; a clinician decides |
All chapters · Previous: Case study: a multimodal agent for multi-object image generation