Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2026 Azeem Ayman

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
212 changes: 101 additions & 111 deletions README.md

Large diffs are not rendered by default.

Binary file removed assets/example.png
Binary file not shown.
75 changes: 75 additions & 0 deletions docs/decisions.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,81 @@

This file records the main choices behind the agent: what I decided, what I considered instead, the evidence, and what is still uncertain.

## Numbers from the panel, reasons from the reports

**Decision.** The agent has two tools with separate jobs.
- `query_queue` runs SQL on the panel, the table of PJM projects. The agent's instructions tell it to take every count, total and cost per kW from here.
- `search_studies` returns passages from PJM's study reports. They explain the numbers: which upgrades a project needs, how their costs are shared and how long they would take. The instructions tell the agent to treat a dollar figure in a passage as one line of a project's costs, never as its total.

**Why.**
- A search returns only the 8 passages closest to the question, so it can't count or rank the panel's 7,666 projects. SQL can, exactly.
- A report spreads its costs over many lines and tables, and a passage often holds just one of them. A model reading passages can mistake one line for the total.
- Only the reports say why a cost is high.

**Alternatives.**
- **Passages only**, with the panel's rows stored as passages too. Counts and rankings would depend on which rows a search happened to return.
- **SQL only.** The agent could give numbers but not explain them.
- **Whole reports in the model's input.** A report can run to hundreds of pages (AF1-236's system impact study has 206), so every question would cost far more.

**Evidence.** The evaluation checks this split. Its first question must use `query_queue` and not `search_studies`. Once costs have been extracted, two more checks fail an answer that presents one line of a report as the project's total. The evaluation needs extracted costs, so I'll run it after the move to current models (see the README's limitations).

**Trade-offs.**
- The panel's costs are only as good as the extraction, which reads passages too.
- Only the instructions and the evaluation stop the agent quoting a passage's figure as a total. The code doesn't.

## A pinned copy of Berkeley Lab's data

**Decision.** The panel is built from one release of Berkeley Lab's queue spreadsheet: the Queued Up 2026 file, with queues to the end of 2025. `src/config.py` holds its address and its SHA-256 checksum, a fingerprint of the exact file. `make data` downloads it and checks the fingerprint. `make panel` refuses a spreadsheet that doesn't match. To build from another copy, name it with `python -m src.ingest_queue --file <path>`.

**Why.** Every number in the README must come from a known copy of the data. The check also catches a download that broke part way, or a file Berkeley Lab has since replaced.

**Alternatives.**
- **Always the newest release.** Results would change without warning.
- **PJM's live queue, through gridstatus, as the default.** It changes whenever PJM updates it, needs a PJM key, and PJM's terms apply. It is available with `python -m src.ingest_queue --source gridstatus`.
- **Committing the spreadsheet.** Its CC BY 4.0 licence allows that, with credit, but the file is about 16 MB, and a pinned download gives the same copy.

**Evidence.** Tests check that a download with another fingerprint is refused and not kept, that a download that breaks part way leaves nothing behind, and that the panel build refuses a spreadsheet that isn't the pinned one.

**Trade-off.** When Berkeley Lab publishes a new release, the address and fingerprint have to be updated by hand, and the README's figures recalculated.

## The agent's database queries can't reach files

**Decision.** The agent writes its own SQL. `query_queue` only runs a single statement that starts with `SELECT`, on a read-only connection to the panel, with DuckDB's external access switched off (`enable_external_access = false`).

**Why.**
- Text in a study report could steer the agent. This is called prompt injection.
- By default, DuckDB's SQL can read files and web addresses. For example, `SELECT * FROM read_text('.env')` returns the file that holds the OpenAI key.
- With external access off, every function that reads a file or the web fails, and ordinary queries on the panel still work.

**Alternatives.**
- **A list of allowed tables and functions.** DuckDB has many functions that read files, so such a list is easy to get wrong.
- **A fresh in-memory copy of the panel for each query.** It only helps if external access is also off, and then the copy adds nothing.
- **Keeping the key somewhere other than `.env`.** That protects the key, but not other files.

**Evidence.**
- Tests check that `read_text`, `read_csv` and a quoted file path are refused.
- On 30 November 2026 I also tried `read_blob`, `read_csv_auto`, `sniff_csv`, the JSON and Parquet readers, `glob`, a file read wrapped in `query()`, and a web address through the agent's query function. DuckDB refused each one. `INSTALL` was refused because it isn't a `SELECT`.
- The evaluation's own queries work within these limits.

**Trade-offs.**
- The agent can't read any outside file, even a harmless one. It never needs to.
- The check also refuses a query that starts with `WITH`, a common way to write a query in steps.

## Rebuilding the panel keeps the extracted costs

**Decision.** The table of figures extracted from the reports, `study_extracts`, is created with the panel and survives a rebuild. Each rebuild recalculates every project's `cost_per_kw` from it, using the same ratio as the extraction step: the network upgrade total, divided by the megawatts the study assessed, or by the project's capacity in the panel if the study gives none or gives zero.

**Why.** The extraction skips projects it has already done, so it doesn't pay twice for a report. Without this, rebuilding the panel would blank every cost, and the extraction would skip those projects unless run again with `--rebuild`, at a cost.

**Alternatives.**
- **Extracting again after every rebuild.** It costs money, and a model's answers can vary between runs.
- **Keeping the cost only in `study_extracts`**, and joining the two tables in every query. That changes the table the agent's tool describes, and makes every cost question more complex.
- **Recalculating in Python, by calling the extraction code.** The panel module would then depend on the extraction module, which already depends on it.

**Evidence.** A test rebuilds the panel after extracting three projects and checks that their costs come back unchanged, whether the study gives its megawatts, omits them or gives zero.

**Trade-off.** The ratio is written twice, once in Python and once in SQL. That test keeps the two in step.

## The chat page

**Decision.** Alongside the terminal chat, the agent has a chat page in the browser, started with `make app`.
Expand Down
31 changes: 31 additions & 0 deletions docs/future_work.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# Future work

Changes I plan or propose, starting with the most urgent.

## Next

- **Move to current OpenAI models.** OpenAI shut down `gpt-4.1-nano`, the extraction model, on 23 October 2026, and shuts down `gpt-4.1-mini`, the agent's model, on 14 January 2027. After the change, I'll check the extracted costs of three reports (AC2-093, AF1-236 and AF2-353) against the figures I read from them by hand, and run the evaluation.
- **Correct the agent's instructions.** Two of its background findings don't match Berkeley Lab's PJM study (see the README's limitations), so I'll correct them and give each finding its source. I'll also remove the instruction to treat a quoted cost as an upper bound, which no cited source supports.
- **Make the evaluation skip checks it can't make.** With no extracted costs, two checks have nothing to compare with, so they pass whatever the answer says.

## Method

- **Choose a more varied sample of reports.** The default 25 all applied on the same day, and 14 of them are 5 MW or smaller. A better rule could set a minimum size, prefer system impact studies and spread the choice across queue windows.
- **Select reports by queue window, not by date.** Berkeley Lab dates 10 projects from the AG1 window 1 or 2 October 2020, so the date cutoff leaves them out. At least one of them, AG1-462, has a report.
- **Fetch named projects' reports,** instead of saving them by hand.
- **Compare the extracted costs with Berkeley Lab's.** Its [PJM cost data](https://eta-publications.lbl.gov/sites/default/files/pjm_costs_2022_clean_data.xlsx) has costs read by hand for 1,127 projects, including AF1-236 and 12 of the default 25. `python -m src.extract --validate` looks for these costs in the Queued Up spreadsheet, which doesn't have them, so it never compares anything.
- **Settle the cost definition.** Either match Berkeley Lab's (every cost except attachment facilities, divided by nameplate capacity, in 2022 dollars) or keep mine and show the difference.
- **Check which megawatts the extraction copies.** AC2-093's report gives 675 MW of output, of which PJM counts 429.4 MW as capacity. Its cost per kW depends on which one the model takes.
- **Count queue age to a fixed date,** such as the end of the data, or the date a project withdrew or started operating.
- **Give coal, nuclear, oil and diesel fuel types of their own.** Berkeley Lab labels 138 of the panel's projects coal, 77 nuclear, 53 oil and 24 diesel, and the panel counts them all as "other".
- **Compare PDF readers.** On my laptop, PyMuPDF took 143.5 seconds to read AG1-321's 65-page report with its tables added in Markdown, a simple text format, and gave 365,148 characters. Without the Markdown tables it took 0.3 seconds and gave 133,495. I haven't measured whether the tables help the extraction.
- **Move off `langchain-community`,** which provides the PDF readers and is [no longer actively maintained](https://github.com/langchain-ai/langchain-community/issues/674).
- **Let `search_studies` search one project's report,** so a question about one project doesn't bring back passages from others.
- **Allow `WITH` queries in `query_queue`,** and stop queries that run too long.
- **Pin every package,** including the ones the pinned packages depend on.

## Scope

- **More grid operators.** The panel has an `iso` column for the operator, but queue IDs repeat across operators: 151 of PJM's also appear in other regions. The table's key would need to include the operator.
- **Other grid operators' study reports,** where they publish them.
- **A withdrawal model.** Once enough costs are extracted, a statistical model trained on past withdrawals could give a calibrated probability, in place of the agent's reasoning.
4 changes: 2 additions & 2 deletions src/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,8 @@ class Settings(BaseSettings):
)
pdf_fetch_delay_seconds: float = 1.0

# pjm switched to the cluster cycle process on this date. projects from it onward have no
# individual study PDF at these URLs, so the fetch selection only considers earlier ones.
# pjm's AG2 queue window opened on this date. none of the AG2 or later projects checked has a
# study PDF at the fetch urls, so the fetch selection only considers earlier ones.
pdf_study_cutoff: date = date(2020, 10, 1)

# chunking for the PDF ingester.
Expand Down
6 changes: 3 additions & 3 deletions src/fetch_pdfs.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

Reads a small, capped set of queue ids from the panel, builds the two
candidate PJM study urls for each, and saves whichever one exists to
data/raw/pdfs/{queue_id}.pdf. Most panel ids have no downloadable study. That is
data/raw/pdfs/{queue_id}.pdf. Some projects have no study at either url. That is
normal, so a missing pdf is a quiet skip, not an error.

Panel ids are stored uppercase and hyphenated, for example AC2-115, but the PJM
Expand Down Expand Up @@ -44,8 +44,8 @@
MAX_FETCH_ATTEMPTS = 3
RETRY_WAIT_SECONDS = 2

# individual study PDFs exist only for the pre cluster era. the selection takes the most recent
# projects before the cutoff, ties broken by queue_id so the same sample comes back each run.
# the selection takes the most recent projects before the cutoff, ties broken by queue_id so the
# same sample comes back each run.
CANDIDATE_IDS_SQL = (
"SELECT queue_id FROM projects "
"WHERE status IN ('active', 'withdrawn') "
Expand Down
6 changes: 3 additions & 3 deletions src/ingest_pdfs.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
"""Chunk PJM study PDFs, embed them, and store the vectors in Chroma.

Loads with PyMuPDF by default, since it renders the cost tables in these studies as
markdown rather than flattening them to plain text, which keeps the numbers readable.
PyPDFLoader is kept as a fallback for a file PyMuPDF cannot parse.
Loads with PyMuPDF by default, which keeps each page's text and adds every table it finds
as markdown, so a cost line and its amount stay on one row. --loader pypdf uses PyPDF
instead, for when PyMuPDF cannot parse a file.
"""

import argparse
Expand Down