3. Explaining the flagged series
Question: Which flags deserve an explanation, and what does the language model say?
Rationale
A flag says that a value is unusual within its series. It does not say why. A value can be unusual because of a data-entry error, because of a real event such as a conflict, a disaster, or a reform, or because the statistical office revised its method. A reviewer who has to decide between these causes needs a first hypothesis, with the evidence that supports it, and writing such hypotheses for hundreds of flags by hand is the part of the work that does not scale.
The explanation pipeline of the ai4data.anomaly.explanation module asks a language model for that hypothesis. A language model is a program that produces text from a text prompt, and here it receives the series around a flagged value, the name of the indicator and the country, and instructions to name only documented causes. It returns a structured answer in a fixed format, with a classification of the cause, a confidence between 0 and 1, an explanation, and the evidence that it cites. The answer is a hypothesis for a reviewer to check, and the model can be wrong, can cite an event that did not happen, and has no access to knowledge that is not documented.
Not every flag needs an explanation. Every request costs money and review time, and a flag that only one method raises is more likely noise. This chapter selects the series with the strongest agreement, builds one request for each flagged window, and reads the answers into a file for review. The step needs the key of a provider or a model that the organization hosts, because the pipeline sends the requests to a model. The files and the demonstration notebook of this guide replay recorded stand-in answers, so that every step below can be carried out without a key.
Target state
- The series to explain are chosen by a stated rule, and the rule is the minimum number of agreeing methods.
- Only observed values are explained, and every request marks imputed values so that the model does not explain them.
- Every answer is read in the schema of the pipeline, and a request whose answer cannot be read is counted and not repaired by hand.
- A review file holds each explanation with the series around the flagged window.
Maturity levels
| Level | Steps |
|---|---|
| Foundational | Choose the series from the shortlist, send a few requests by hand, and read the answers. |
| AI-ready | Build the batch file with the pipeline, run it through the provider's batch service, parse the answers against the schema, and write the review file. |
| AI-native | Run more than one model, let an arbiter harmonise their answers into one classification, and store the model, the prompt, and the date with each answer. |
This chapter takes the 40 flagged observations of Chapter 2 down to the series that at least three methods agree on, builds eight requests for seven series of the fictional panel, and reads stand-in answers into a review file. The stand-in answers are not model output. They say that no documented cause is available, which is also what a careful model should answer about a fictional series.
Recipes
3.1 Select the series to explain
- Level
- Foundational
- Skills
- Data analyst
- Indicative time
- 20 minutes
Result: A shortlist file ranks the series that contain an observation flagged by at least a chosen number of methods, and the team knows how many requests that number produces.
The shortlist keeps a series when at least one observed value of it is flagged by the minimum count of methods. Imputed values are left out, because the model would otherwise explain a value that nobody measured. The series are ranked by the sum of the standardised scores of their flagged observations, so that a series with one extreme jump ranks near a series with several moderate flags. The minimum count is the lever for the cost: a lower count adds series and requests.
The script detect_and_shortlist.py of Chapter 2 writes the shortlist as shortlist.csv and takes the minimum count in the option --min-count, which is 3 by default.
- Decide the minimum count from the capacity of the reviewers and the cost of a request. A count of three of five methods is a reasonable start, and a count of two adds the weak flags of Recipe 2.1.
- Run the script with the chosen count. The output states the number of series on the shortlist and the number of requests.
- Open
shortlist.csvand check the first series against the plots or the tables of the data. A shortlist whose first series look ordinary points to a problem in the preparation or the thresholds. - Write the count into the run record, as Chapter 4 describes.
Worked example. At a minimum count of three, the run of Chapter 2 gives the following shortlist.
indicator_id,geography_id,anomaly_score
EG.ELC.ACCS,FFF,5.265704412443437
EG.ELC.ACCS,EEE,4.4692893078629865
EG.ELC.ACCS,GGG,4.377430032724868
SH.MORT.U5,DDD,4.322920074761178
SH.MORT.U5,EEE,3.9828034648349244
SH.MORT.U5,GGG,3.683969130244022
SI.POV.HEAD,GGG,3.4488950435953467
Seven of the 32 series are on the list. The first series, electricity access in Fenmark, scores 5.27 because two of its observations are flagged by at least three methods: the jump of 2007 with a score of 4.51 and the value of 2017 with a score of 0.75. The two observations lie ten years apart and belong to two separate windows, so that the seven series produce eight requests.
What this does not do. The shortlist ranks by agreement and by size. It does not rank by importance to users, by the size of the economy, or by the cost of an error, and a team that has such priorities adds them as a second rule before the batch is built.
3.2 Build and run the batch of explanation requests
- Level
- AI-ready
- Skills
- Data analyst with access to a provider account
- Indicative time
- 1 hour, plus the wait for the batch
Result: A batch file holds one request for each flagged window of the shortlisted series, and the requests have been submitted to the provider, or the team knows what a submission needs.
A request is a prompt that the pipeline writes for one flagged window. It holds a system message with the rules for the model, and a user message with the task and a context. The system message tells the model to use only documented and verifiable facts, to answer insufficient_data where it cannot recall a clear event, to lower its confidence to 0.5 or less when in doubt, and not to explain imputed values. The context lists the indicator, the country, and the series for the years around the flagged value, with the Imputed mark of every year. By default the window extends three years on each side of the flagged value.
The requests are written in the format of a provider's batch service, which accepts a file of requests and returns a file of answers after a delay of minutes to hours, at a lower price than interactive calls. The pipeline writes the format of OpenAI, Gemini, or Anthropic, and it writes a second file, the sidecar, that maps each request identifier back to the indicator and the geography. Only yearly data can be explained, because the prompts and the context read integer years.
The script of Recipe 2.1 builds the batch file. The following request context is the end of the first request of the example, which asks about the jump of 2007 in the electricity series of Fenmark.
# CONTEXT
{
"Indicator": "Access to electricity (% of population)",
"Country": "Fenmark",
"Series": [
{"YEAR": 2004, "VALUE": 54.07, "Imputed": false},
{"YEAR": 2005, "VALUE": 55.59, "Imputed": false},
{"YEAR": 2006, "VALUE": 57.58, "Imputed": false},
{"YEAR": 2007, "VALUE": 71.42, "Imputed": false},
{"YEAR": 2008, "VALUE": 61.49, "Imputed": false},
{"YEAR": 2009, "VALUE": 62.67, "Imputed": false},
{"YEAR": 2010, "VALUE": 63.86, "Imputed": false}
]
}
The pipeline writes this context with one entry per line. It is condensed here to fit the page, and the content is unchanged.
-
Run the script, which writes
batch.jsonlandbatch_custom_id_map.jsonin the output directory when the shortlist is not empty. With a provider other than the default, set--provider. -
Open
batch.jsonland read one request in full. Check that the context shows the right series, that the imputed years are marked, and that the system message states the rules of the organization. The system and user prompts are in the moduleai4data.anomaly.explanation.prompts, and a team that changes them records the change with the run. -
Submit the file with the batch functions of the pipeline. The function
run_batchsubmits the file, waits until the batch completes, and downloads the output. The functionssubmit_batch,wait_for_batch, anddownload_batch_outputperform the same steps one at a time.from ai4data.anomaly.explanation import run_batchrun_batch("openai", "run1/batch.jsonl", "run1/batch_output.jsonl", poll_interval=60) -
Keep the batch file, the sidecar, and the output together, because the sidecar is the only record of which request belongs to which series.
Worked example. The run of Chapter 2 wrote eight requests for the seven shortlisted series. The command prints their number.
python detect_and_shortlist.py indicator_panel.csv --outdir run1
32 series, 800 observations (20 imputed)
flagged by at least one method: 40 (5.0%)
flags by method: zscore 7, tsoutlier 13, hampel 10, capa 37, isotree 11
shortlist at 3 methods: 7 series
batch requests: 8
The example does not submit the file, because a submission needs a provider key and a batch run can take hours. The file batch.jsonl is complete and can be submitted as it stands. The next recipe uses stand-in answers in its place.
What this does not do. The batch file sends the series and the names to a provider, so that the terms of the provider apply to them. The recipe does not decide whether a series may leave the organization, which is a question for the policy of the organization, and it does not give the model access to sources beyond its own knowledge. A model that cannot name a documented cause is asked to say so.
3.3 Read the answers into a review file
- Level
- AI-ready
- Skills
- Data analyst
- Indicative time
- 30 minutes
Result: Every answer that can be read is a row of a table and an item of a review file, the requests without a readable answer are counted, and a summary shows how the classifications are distributed.
An answer is a JSON object, which is a structured text that a program can read, with a list of anomalies. Each anomaly is a window of years and the fields in the following table. The pipeline reads each answer as JSON and skips a request whose answer cannot be read, and the Anthropic reader also validates the answer against this schema. The script of this recipe counts the requests that were answered, so that a skipped request does not pass unnoticed.
| Field | Meaning |
|---|---|
window | The first and the last year of the anomaly. |
is_anomaly | Whether the model confirms the anomaly. The prompt allows true only for a well-documented cause. |
classification | The kind of cause: data_error, external_driver, measurement_system_update, modeling_artifact, or insufficient_data. |
confidence | A number between 0 and 1, which is the model's own estimate and not a measured probability. |
explanation | A short text with the cause. |
evidence_strength | strong_direct, moderate_contextual, weak_speculative, or no_evidence. |
evidence_source | The events or documents that the model cites, each with a name, a date range, a type, and a level of verifiability. |
source | Where the explanation comes from. The value is llm_inferred for every answer of the pipeline. |
The script stand_in_answers.py writes an output file with one fixed answer per request, in the format of the OpenAI batch service. The script review_export.py reads an output file, whether it is the provider's or the stand-in, and writes the review file and a summary.
"""Write stand-in answers for a batch file, so that the later steps run without a model.
Purpose: read the batch file that `detect_and_shortlist.py` wrote and the
detections table, and write an output file in the format of the OpenAI batch
service with one fixed answer per request. Each answer names the most flagged
year in the request and classifies it as `insufficient_data`. The answers are
not model output. They let the parsing and review export steps run on a
machine without a provider key, and they are what a careful model would also
conclude about a fictional series.
Usage:
python stand_in_answers.py run1/batch.jsonl run1/detections.csv --output run1/batch_output.jsonl
Requires pandas. Exit status: 0 when the file was written; 1 when an input
cannot be read or a request holds no year of the table.
What this does not check: that the answers describe the data in any real
sense. A real run replaces this file with the provider's output file.
"""
import argparse
import json
import sys
from pathlib import Path
import pandas as pd
ANSWER = {
"is_anomaly": False,
"classification": "insufficient_data",
"confidence": 0.3,
"explanation": (
"Stand-in answer written without a model. The series is fictional, "
"so no documented event can explain the value."
),
"evidence_strength": "no_evidence",
"evidence_source": [],
"source": "llm_inferred",
}
def request_context(row: dict) -> dict:
"""Return the JSON context that a request carries in its user message.
Parameters
----------
row : dict
One line of the batch file.
Returns
-------
dict
The context with the indicator, the country, and the series snippet.
"""
text = row["body"]["input"][1]["content"][0]["text"]
return json.loads(text.split("# CONTEXT", 1)[1].strip())
def main(argv: list[str] | None = None) -> int:
"""Write the stand-in output file.
Parameters
----------
argv : list[str] | None, optional
Command arguments, or the process arguments when omitted.
Returns
-------
int
Zero when the file was written.
"""
parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
parser.add_argument("batch", type=Path)
parser.add_argument("detections", type=Path)
parser.add_argument("--output", type=Path, required=True)
args = parser.parse_args(argv)
try:
rows = [json.loads(line) for line in args.batch.read_text().splitlines()]
ids = json.loads(
args.batch.with_name(args.batch.stem + "_custom_id_map.json").read_text()
)
table = pd.read_csv(args.detections)
except (OSError, ValueError) as error:
print(f"Cannot read the input: {error}", file=sys.stderr)
return 1
lines = []
for row in rows:
key = ids[row["custom_id"]]
years = {item["YEAR"] for item in request_context(row)["Series"]}
series = table[
(table["indicator_id"] == key["indicator_id"])
& (table["geography_id"] == key["geography_id"])
& table["period"].isin(years)
& ~table["is_imputed"]
]
if series.empty:
print(f"No observation for request {row['custom_id']}", file=sys.stderr)
return 1
top = series.sort_values(["outlier_count", "anomaly_score"]).iloc[-1]
answer = {"anomalies": [{"window": [int(top["period"])] * 2, **ANSWER}]}
body = {"output": [{"content": [{"text": json.dumps(answer)}]}]}
lines.append(
json.dumps({"custom_id": row["custom_id"], "response": {"body": body}})
)
args.output.write_text("\n".join(lines) + "\n", encoding="utf-8")
print(f"wrote {len(lines)} stand-in answers to {args.output}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
"""Read the answers to a batch file and write the review file and a summary.
Purpose: parse the output file of an explanation batch against the detections
table, write the JSON file that the review application opens, and print how the
explanations are distributed. Each item of the review file holds one flagged
window, the explanation, and the series around the window.
Usage:
python review_export.py run1/detections.csv run1/batch.jsonl run1/batch_output.jsonl \\
--review run1/review.json
Requires ai4data[anomaly]. Exit status: 0 when at least one explanation was
read and the review file written; 1 when an input cannot be read or no answer
could be parsed.
What this does not check: whether an explanation is correct. The script reads
the structure of the answers and skips a request whose answer does not parse and reports how many requests were answered;
the reviewer decides about every item, and the review application records the
decision.
"""
import argparse
import sys
from pathlib import Path
import pandas as pd
from ai4data.anomaly.explanation import export_for_review, parse_batch_output
def main(argv: list[str] | None = None) -> int:
"""Parse the answers, write the review file, and print the summary.
Parameters
----------
argv : list[str] | None, optional
Command arguments, or the process arguments when omitted.
Returns
-------
int
Zero when the review file was written.
"""
parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
parser.add_argument("detections", type=Path)
parser.add_argument("batch", type=Path)
parser.add_argument("answers", type=Path)
parser.add_argument("--review", type=Path, required=True)
parser.add_argument("--provider", default="openai")
args = parser.parse_args(argv)
try:
table = pd.read_csv(args.detections)
except OSError as error:
print(f"Cannot read the detections: {error}", file=sys.stderr)
return 1
table["freq"] = "A"
geography = table.drop_duplicates("geography_id").set_index("geography_id")
indicator = table.drop_duplicates("indicator_id").set_index("indicator_id")
try:
parsed = parse_batch_output(
args.answers,
args.provider,
indicator["indicator_name"].to_dict(),
geography["geography_name"].to_dict(),
custom_id_map_path=args.batch.with_name(
args.batch.stem + "_custom_id_map.json"
),
)
except (OSError, ValueError) as error:
print(f"Cannot read the answers: {error}", file=sys.stderr)
return 1
if parsed.empty:
print("No answer could be parsed.", file=sys.stderr)
return 1
export_for_review(parsed, timeseries_df=table, output_path=args.review)
requests = len(args.batch.read_text(encoding="utf-8").splitlines())
answered = parsed["custom_id"].nunique()
print(
f"{answered} of {requests} requests answered, {len(parsed)} explanations read"
)
print(f"review file {args.review.name} written")
for name, column in (
("classification", "classification"),
("evidence", "evidence_strength"),
):
counts = parsed[column].value_counts()
print(f"by {name}: " + ", ".join(f"{k} {v}" for k, v in counts.items()))
return 0
if __name__ == "__main__":
raise SystemExit(main())
- With a real run, take the provider's output file. For the example, write the stand-in file from the batch file and the detections table.
- Run
review_export.pywith the detections table, the batch file, and the output file. The script finds the sidecar next to the batch file, restores the indicator and the geography of each answer, and writes the review file with the series around each window. - Read the summary. A run in which most answers are
insufficient_datais a finding in itself: either the data contain errors without a documented cause, or the model does not know the events. - Compare the number of requests with the number of answered requests in the first line of the output. A difference means that some requests failed or returned text that could not be read, and the provider's output file is then read for those requests before the run is accepted.
Worked example. The two commands write the stand-in answers and then the review file.
python stand_in_answers.py run1/batch.jsonl run1/detections.csv --output run1/batch_output.jsonl
wrote 8 stand-in answers to run1/batch_output.jsonl
python review_export.py run1/detections.csv run1/batch.jsonl run1/batch_output.jsonl --review run1/review.json
8 of 8 requests answered, 8 explanations read
review file review.json written
by classification: insufficient_data 8
by evidence: no_evidence 8
All eight requests received a readable answer, and every answer is insufficient_data with the evidence strength no_evidence, as the stand-in file prescribes. Each of the eight items of review.json holds the indicator, the geography, the window, the explanation, and the observations around the window with their imputed marks. The reviewer application of Chapter 4 opens the file.
What this does not do. Reading the answers checks that they parse. It does not check that a cited event took place, that the dates are right, or that the classification fits the data, and a real model answer can be well formed and wrong. With more than one model, the arbiter of the pipeline can harmonise their answers into one classification, which this guide does not run. The stand-in answers show the format and not what a model says about these series.
Implementation options
- The pipeline writes batch files for OpenAI, Gemini, and Anthropic, and a team can register a provider of its own for a model that it hosts behind a compatible interface. The choice depends on the confidentiality of the series, on the price, and on how well the model knows the countries and indicators.
- For a small number of series, interactive calls to a model are quicker than a batch, and the same prompts apply. The batch route suits hundreds of requests because of its lower price.
- A team with a detector of its own can build the same batch from its scores through the adapters of the pipeline, which read a wide or a configurable file and produce the canonical table. The explanation methodology handbook describes the adapters, the prompts, and the schema.
- With several models, the arbiter harmonises their answers into one classification for each anomaly, and the reviewer application shows the answers side by side.
World Bank examples
- The anomaly detection and explanation documentation of the program describes the pipeline from detection to the reviewer application.
- The elicitation pipeline page documents the schema, the prompts, and the code of the batch steps.
Resources
- The methodology handbook explains why the pipeline asks a model for structured hypotheses, and it lists the limitations. It is used in all recipes of this chapter.
- The step-by-step notebook runs the explanation pipeline on real indicator data and is the reference for the options of the batch steps.
- The demonstration notebook runs the whole sequence of this guide on the fictional panel and replays recorded stand-in answers.
Common mistakes
- Explaining every flag sends the weak flags to the model, which raises the cost and fills the review with explanations of noise.
- Explaining imputed values asks the model about numbers that nobody measured. The pipeline marks them, and the marks are kept in the source.
- Reading the confidence of an answer as a probability of being right gives the model's own estimate a meaning that it does not have.
- Repairing a malformed answer by hand removes the evidence of how often the model fails to follow the schema.
- Sending quarterly or monthly series to the pipeline fails, because only yearly data can be explained.
Verification
- Compare the counts. The number of answered requests equals the number of requests, or the requests without a readable answer are listed.
- Open one request. The context shows the right series, with the imputed years marked, and the rules of the system message are those of the organization.
- Open one review item. The item shows the window, the explanation, and the series around the window, and the series is the one that was flagged.
Checklist
Ticks are saved in this browser only.