diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..a06cdf4 --- /dev/null +++ b/LICENSE @@ -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. diff --git a/README.md b/README.md index b4d3539..788c8c9 100644 --- a/README.md +++ b/README.md @@ -1,177 +1,167 @@ # Interconnection Queue Intelligence Agent -An agent that answers questions about United States electricity grid interconnection projects. It reasons over two things at once, the clean structured queue data and the messy study report PDFs that sit behind it. +An agent that answers plain-English questions about power projects that have applied to connect to PJM's grid. PJM is the grid operator across 13 US states and the District of Columbia. The agent gets its numbers from exact database queries, and its explanations from PJM's study reports. -## What it does - -You ask a plain question, for example which solar projects look most at risk of withdrawing and why. The agent finds the projects and their numbers in the structured data, reads the relevant study reports to explain the drivers, and writes an answer that cites specific projects and specific passages. It gets its totals from the structured data and uses the reports for the detail behind them. +For example, you can ask which solar projects look most at risk of withdrawing, and why. The agent finds the projects and their estimated costs in the data, searches the reports for the grid upgrades behind those costs, and says where each figure came from. ## Why I built this -Connecting new power plants to the grid is one of the biggest blockers for clean energy in the United States. Before a project can connect it has to join an interconnection queue and pass a series of engineering studies. Most projects never make it. Of all the generation capacity that asked to connect between 2000 and 2020, only about 13 percent was running by the end of 2025. Around 75 percent withdrew. - -The single biggest reason projects withdraw is the cost of network upgrades. When a project is told it must pay for expensive upgrades to the grid, it often drops out. That cost can then shift onto the projects behind it in the queue, which can trigger more withdrawals. +Before a new power plant can connect to the grid, it joins a waiting list called an interconnection queue. The grid operator, the organisation that runs the grid in that area, then studies what the connection would need and cost. Most projects never get built. Lawrence Berkeley National Laboratory (Berkeley Lab), a US Department of Energy laboratory, tracks these queues. Of the capacity that asked to connect between 2000 and 2020, it found that 13% was running by the end of 2025 and 75% had withdrawn ([Queued Up](https://emp.lbl.gov/publications/queued-2026-edition-characteristics)). -The data that explains all of this is public, but it is split between two places. The structured queue data is clean. It says which projects exist, how big they are, what fuel they use, and whether they withdrew. The cost detail is much harder to use. It sits inside long study report PDFs, one per project, full of tables and prose. +Cost is one reason. A study can find that the grid needs network upgrades, such as new lines or bigger substations, before the plant can connect, and the plant may have to pay for them. Projects told they need large upgrades tend to withdraw ([Gorman and others, 2025](https://doi.org/10.1016/j.joule.2024.11.008)). In PJM, projects that withdrew had the highest estimated costs on average, "likely a key driver for those withdrawals". For recent withdrawn projects, network upgrades made up 94% of those costs ([Berkeley Lab, 2023](https://eta-publications.lbl.gov/sites/default/files/berkeley_lab_2023.1.12-_pjm_interconnection_costs.pdf)). A withdrawal can also mean new studies for the projects behind it in the queue, which can delay them and raise their costs. The Federal Energy Regulatory Commission (FERC), the US regulator of interstate power transmission, says so in [Order No. 2023](https://www.govinfo.gov/content/pkg/FR-2023-09-06/html/2023-16628.htm) (paragraph 47). -Lawrence Berkeley National Laboratory reads those PDFs by hand to pull out the cost numbers, about twenty minutes per project. I wanted to see if a language model could do that step on its own, and if an agent could then reason over the structured data and the reports together. The structured data tells you what happened. The reports tell you why. Putting the two together is the interesting part, and almost nobody has built tooling over these PDFs. +The data that explains this sits in two places. Berkeley Lab's queue data is a tidy table of each project's size, fuel, dates and status, such as active or withdrawn. The estimated costs, and the reasons for them, are in PJM's study reports: long PDFs full of tables. For its PJM cost study, Berkeley Lab read the costs out of the reports by hand, at 30 to 50 minutes per project on average. I wanted to see whether a language model, the kind of AI behind ChatGPT, could do that reading, and whether an agent could then answer questions from both sources together. ## How it works -The system has two halves. The first half builds the data. The second half answers questions. - -Building the data runs in five steps. First, fetch_queue downloads the queue workbook from Lawrence Berkeley National Laboratory (LBNL). Then ingest_queue reads the queue data and writes one clean table to DuckDB, one row per project. Then fetch_pdfs reads the project list from the panel and downloads the PJM study report PDF for each project that has one. Then ingest_pdfs splits every PDF into chunks and embeds them into a Chroma vector store. Finally extract sends the most relevant chunks of each study to a language model, which pulls out the cost figures. Those figures become a cost per kW and are written back onto the project row in DuckDB. +An agent is a language model that can use tools, such as a database query or a search, and read their results before it answers. This one has two tools, one for each source. -Answering a question uses an agent with two tools. query_queue runs read only SQL against the DuckDB panel, so the agent can find projects and their numbers. search_studies pulls the most relevant passages from the study reports, so the agent can explain why a cost is high and what upgrades drive it. The agent decides which tools to call, reads the results, and writes the answer. +- **`query_queue`** runs SQL, the standard language for asking a database questions, on what I call the panel. The panel is a table with one row per PJM project, built from Berkeley Lab's data and stored in DuckDB, a database that runs on your computer. The agent is told to take every count, total and cost per kW from here, so these come from exact queries rather than from reading text. Cost per kW is a project's network upgrade cost divided by its size in kilowatts (a kilowatt, kW, is a thousandth of a megawatt, MW), so projects of different sizes can be compared. +- **`search_studies`** finds the passages in PJM's study reports that are closest in meaning to a question. Each report is split into overlapping passages, which the code calls chunks, of up to 1,000 characters. Each passage is stored as an embedding, a list of numbers that captures its meaning, in Chroma, a database for embeddings that also runs on your computer. Handing passages found this way to a language model is called retrieval-augmented generation (RAG). The agent uses them to explain the numbers. -The search_studies side is retrieval augmented generation (RAG). The query is embedded, the closest passages are pulled from the vector store, and the model writes its answer from them and cites them. The design leans on RAG only where it earns its place, on the narrative half, where the useful facts are scattered through long reports. The numbers never go through retrieval. They come straight from the panel with exact SQL, so a total is a real total, not a figure the model happened to read. Using RAG for the prose and exact queries for the numbers is the core design choice. - -Here is the whole flow. +One step links the two. For each report, a language model reads up to seven passages about its costs and size, and copies out the key figures, such as the totals in its cost summary. The code then works out the network upgrade cost per kW and writes it into the panel. ```mermaid -flowchart TB - Q["queue data, LBNL or gridstatus"] --> IQ["ingest_queue"] --> DB[("DuckDB panel")] - P["PJM study report PDFs"] --> FP["fetch_pdfs"] --> IP["ingest_pdfs, chunk and embed"] --> CH[("Chroma vectors")] - CH --> EX["extract, a model reads the top chunks"] -->|cost per kW| DB - U(["your question"]) --> AG["LangGraph agent"] - AG -->|query_queue| DB - AG -->|search_studies| CH - AG --> ANS(["grounded answer"]) - DB -.->|which studies to fetch| FP +flowchart LR + LBNL["Berkeley Lab queue data"] -->|make data, make panel| PANEL[("Panel, in DuckDB")] + PANEL -->|make fetch picks the projects| PDF["PJM study reports"] + PDF -->|make embed| VEC[("Passages, in Chroma")] + VEC -->|make extract adds costs| PANEL + Q(["Your question"]) --> AGENT["Agent"] + AGENT -->|query_queue| PANEL + AGENT -->|search_studies| VEC + AGENT --> A(["Answer"]) ``` -## Project layout +| Command | What it does | Paid | +|---|---|---| +| `make data` | Downloads Berkeley Lab's queue spreadsheet, which the code calls the workbook, and checks it is the exact copy this project expects | No | +| `make panel` | Builds the panel from the spreadsheet's PJM projects | No | +| `make fetch` | Downloads PJM's study reports for up to 25 projects | No | +| `make embed` | Splits the reports into passages and embeds them | Yes | +| `make extract` | Reads each report's costs into the panel | Yes | +| `make app`, or `python -m src.cli ask` or `chat` | Answers your questions | Yes | -``` -src/ - config.py settings, paths, and model prices - fetch_queue.py download the LBNL queue workbook - ingest_queue.py build the DuckDB panel - fetch_pdfs.py download PJM study PDFs - ingest_pdfs.py chunk and embed the PDFs - extract.py pull cost figures with a language model - tools.py the two agent tools - agent.py the LangGraph agent - cli.py the command line entry point - app.py the chat page, a small web server on your computer - static/ the chat page's HTML, CSS and JavaScript -tests/ offline tests, the fixture builder and the by hand evaluation -``` +The paid steps only call OpenAI when `DRY_RUN` is false (see [Cost](#cost)). The [design decisions](docs/decisions.md) explain the main choices. -## The data +## What the data holds now -Two stores hold the data. DuckDB holds the structured panel, one row per project, with capacity, fuel, status, dates, location, and a cost per kW where a study has been extracted. Chroma holds the embedded chunks of the study PDFs, each tagged with the project it came from. +These figures come from runs on 30 November 2026 at the default settings. -Right now three projects have a full extracted cost, all of them withdrawn solar or solar plus storage. AC2-093 sits at about 412 dollars per kW, AF1-236 at about 391, and AF2-353 at about 374. Each figure comes from hundreds of millions of dollars of required network upgrades, read out of the study reports. +**The panel.** It holds 7,666 PJM projects from Berkeley Lab's Queued Up: 2026 Edition, which covers queues to the end of 2025. Of these, 5,226 have withdrawn, 1,192 are operating, 1,134 are active and 114 are suspended. By fuel, 3,661 are solar, 1,096 gas, 943 storage, 730 wind, 516 solar with storage, 89 hydro and 631 other. "Other" covers coal, nuclear, oil and diesel, hybrids other than solar with storage, and projects Berkeley Lab itself lists as other. -## Built with +**The study reports.** PJM groups applications into queue windows, with names such as AC2, AF1 and AG1. `make fetch` only looks for reports for projects that applied before 1 October 2020, when the AG2 window opened. I tried 14 projects from the AG2, AH1 and AH2 windows, and none has a report at either address `make fetch` uses. By default it takes the 25 active or withdrawn projects that applied most recently before that date. All 25 applied on 30 September 2020. So did 192 other active or withdrawn projects, which it leaves out because it takes the first 25 by queue ID. Of the 25, 14 are 5 MW or smaller. Their reports are 13 feasibility studies, PJM's first, rough estimate of what a connection needs; 6 system impact studies, the more detailed study that follows; and 6 that combine the two. -- Python 3.11 to 3.14 -- LangChain and LangGraph for the agent and the retrieval plumbing -- OpenAI for embeddings, cost extraction, and the agent's reasoning -- DuckDB for the structured queue panel -- Chroma for the local vector store -- Starlette and Uvicorn for the chat page in the browser ([why this approach](docs/decisions.md#the-chat-page)) -- gridstatus and the LBNL Queued Up dataset for the queue data +**Costs.** The panel has no extracted costs yet. They need the reports embedded and then read by the extraction model, which has been shut down (see [Limitations](#limitations)). To show the calculation, here is one report read by hand. AC2-093 was a 675 MW solar project in North Carolina, now withdrawn. Its system impact study, from May 2018, estimates $280,825,093 of costs. Of that, $2,300,000 is for attachment facilities, the equipment where the plant meets the grid, and the other $278,525,093 is for network upgrades. Divided by its 675 MW, that is about $413 of network upgrades per kW. ## Quickstart -Everything runs locally in a Python virtual environment, on Python 3.11 to 3.14. Install the pinned packages, activate the environment and create your env file. Run `make help` to see every step. +You need Python 3.11 to 3.14, `make`, and, for the paid steps, an OpenAI API key: the password that lets the code use OpenAI's models and bills your OpenAI account. ``` -make install +make install # creates .venv and installs the pinned packages source .venv/bin/activate -cp .env.example .env +cp .env.example .env # then set OPENAI_API_KEY in .env +make check # shows what is set up so far, with no API call ``` -Open .env and set OPENAI_API_KEY to your own key. DRY_RUN ships as true, so nothing calls the paid API until you set it to false on purpose. - -Check your setup at any point. This makes no API call. - -``` -make check -``` - -Download the LBNL Queued Up workbook and build the queue panel from it. The download is checked against a pinned checksum, a fingerprint of the exact file, so every build starts from the same data. +`DRY_RUN` is true in `.env.example`, so nothing calls OpenAI until you set it to false, either in `.env` or for one command, as below. `make help` lists every step. ``` make data make panel -``` - -To use PJM's live queue instead, through gridstatus, set PJM_API_KEY in .env to a free PJM Data Miner key and run `python -m src.ingest_queue --source gridstatus`. - -Fetch a small sample of study PDFs, then embed them. The fetch is free. The embed calls the API, so it needs DRY_RUN=false. Reading the default 25 PDFs takes about ten minutes. - -``` make fetch -make embed DRY_RUN=false +make embed DRY_RUN=false # an estimated $0.03 for the 25 default reports +# make extract DRY_RUN=false # skip for now: its model has been shut down (see Limitations) ``` -Extract the cost figures. This reads the top chunks of each study and writes a cost per kW back into the panel. +Then ask questions, in the browser or the terminal: ``` -make extract DRY_RUN=false +make app DRY_RUN=false +DRY_RUN=false python -m src.cli ask "How many withdrawn solar projects are in the panel, and what is their combined capacity in MW?" +DRY_RUN=false python -m src.cli chat ``` -Ask a question. Like the steps above, this only calls the API with DRY_RUN=false, and gives a canned reply otherwise. +`make app` opens a chat page at http://127.0.0.1:8000. It listens only on your computer, and each browser tab keeps its own conversation. Press Ctrl+C in the terminal to stop it. It stops once any answer in progress has finished. -``` -DRY_RUN=false python -m src.cli ask "which projects have the highest network upgrade cost per kW and why" -``` - -For a running conversation that keeps context across turns, use chat instead. +**Adding a report.** To add another project's report, save it as `data/raw/pdfs/.pdf`, with the queue ID written exactly as in the panel, and run `make embed` again. It skips reports it has already embedded. For example, for AF1-236: ``` -DRY_RUN=false python -m src.cli chat +curl -fo data/raw/pdfs/AF1-236.pdf https://www.pjm.com/pjmfiles/pub/planning/project-queues/impact_studies/af1236_imp.pdf +make embed DRY_RUN=false ``` -To chat in your browser instead, start the chat page. It opens at http://127.0.0.1:8000 and keeps a separate conversation in each browser tab. It listens only on your computer. Ctrl+C in the terminal stops it, once any answer in progress has finished. +**PJM's live queue.** To build the panel from PJM's live queue instead of Berkeley Lab's data, put a free PJM Data Miner API key in `PJM_API_KEY` in `.env`, then run `python -m src.ingest_queue --source gridstatus`. I haven't tested this route. -``` -make app DRY_RUN=false -``` +## Cost -## Example +Nothing calls OpenAI until you set `DRY_RUN` to false. In a dry run, `make embed` and `make extract` say how much they would send and estimate its cost, and the agent gives a fixed reply. OpenAI charges by the token, a chunk of text a few characters long. The prices this project uses are in `src/config.py`. -A real run of the ask command. The agent ranks the costed projects from the panel, then reads the study report to explain what drives the most expensive one, and it is clear about which numbers come from the panel and which come from the report. +- **Embedding the 25 default reports** is estimated at $0.0272: 1,357,677 tokens at $0.02 per million. The dry run, which reads all 25 PDFs, took 11 minutes on my laptop. +- **Extraction and questions.** I'll measure these after the move to current models. Extraction sends the model up to seven passages per report, never a whole PDF. +- **Limits.** `make embed` and `make extract` handle at most 25 reports per run (`MAX_PDFS`) and skip any they have already done. The agent stops after 10 steps, at most five calls to the model, on any one question. -![A terminal run of the ask command, ranking projects by network upgrade cost per kW and explaining the top one](assets/example.png) +## Tests and evaluation -## Cost +`make test` runs the offline tests. They use small sample files in `data/fixtures/`, and stand-ins for the model and the network, so they need no key, no network and no downloads. GitHub runs them on Python 3.11 and 3.14 for every pull request. -Running this is cheap by design. Nothing calls the paid API until you set DRY_RUN to false. Every paid step has a cap and skips work it has already done. Extraction only sends the few most relevant chunks of each study to the model, never a whole PDF. A full test of the finished system costs well under one dollar. The evaluation over all of its questions costs a few cents. +`make eval DRY_RUN=false` puts six questions to the real agent. It prints each answer, the result of each check, and the tokens and cost. The checks test, for example, that the agent used the right tool, stated the right count, and didn't present one line of a report as a project's total. Some checks compare answers with the extracted costs. With no extracted costs, two of them are skipped, and two others pass whatever the answer says, because there is nothing to compare with. One question is about AF1-236, whose report isn't in the default sample; the Quickstart shows how to add it. The evaluation needs extracted costs, so I'll run it after the move to current models. -## Tests and evaluation +## Limitations + +- **Study costs are preliminary estimates, not final bills.** They are the grid operator's estimates at the time of the study, and a later study can change them. +- **PJM only.** The panel holds PJM's projects, and the reports are PJM's. +- **`make fetch` only looks for reports of projects that applied before October 2020, and the default sample is narrow.** See [What the data holds now](#what-the-data-holds-now). +- **Extraction can't run at the default settings.** 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 ([OpenAI](https://developers.openai.com/api/docs/deprecations)). Moving to current models is the next change ([future work](docs/future_work.md)). +- **The model can misread a report.** It can miss or misread a figure, and its output can vary between runs, so check any cost that matters against its report. +- **My cost per kW is defined differently from Berkeley Lab's.** Berkeley Lab counts every cost except attachment facilities as network cost, divides by the plant's nameplate capacity (its rated maximum output) and converts to 2022 dollars. I use the report's own network upgrade total, or if it gives none, its total minus the cost of the physical connection. Either can leave out connection work that Berkeley Lab counts. I divide by the megawatts the study assessed, or by the panel's capacity if it gives none, and don't adjust for inflation. +- **Two background findings in the agent's instructions don't match Berkeley Lab's PJM study.** One says cost is "the dominant driver" of withdrawal, where the study says high costs are "likely a key driver". The other says network upgrades are about 70% of recently withdrawn projects' costs, where the study's figure is 94%. Fixing them needs a fresh paid evaluation, so the fix comes with the model change. +- **Withdrawal risk is reasoning, not prediction.** The agent weighs a project's costs against research findings and describes the risk. It is told never to say a project will certainly withdraw. It isn't a statistical model trained on past withdrawals. +- **Queue age, the days since a project applied, counts to the day you build the panel,** even for projects that withdrew or started operating years ago. -The test suite runs offline with the model mocked, so it needs no key and no network. +## Project layout ``` -make test +src/ + config.py every setting, path, model name and price + fetch_queue.py downloads Berkeley Lab's queue spreadsheet + ingest_queue.py builds the panel, and runs the agent's SQL safely + fetch_pdfs.py downloads PJM's study reports + ingest_pdfs.py splits the reports into passages and embeds them + extract.py reads the costs out of the reports into the panel + tools.py the agent's two tools + agent.py the agent and its instructions + cli.py the terminal commands: setup-check, ask and chat + app.py the chat page's web server + static/ the chat page's HTML, CSS and JavaScript +tests/ the offline tests and the evaluation +docs/ design decisions and future work +data/fixtures/ small sample files for the tests ``` -There is also a small evaluation that runs the real agent against a handful of realistic questions. It prints each answer, whether it passed a check, and the running cost. It is run by hand because it calls the API. +Downloads and built data go in `data/raw/`, `data/processed/` and `data/vectors/`, which stay on your computer and out of Git. -``` -make eval DRY_RUN=false -``` +## Built with -## Limitations +Python 3.11 to 3.14, LangChain and LangGraph for the agent, and OpenAI's models: `gpt-4.1-mini` for answers, `gpt-4.1-nano` for extraction and `text-embedding-3-small` for embeddings. DuckDB holds the panel, Chroma holds the passages and PyMuPDF reads the PDFs. Starlette and Uvicorn serve the chat page. `requirements.txt` pins the exact versions. + +## Sources and credits -- Quoted study costs are early estimates, not final bills. A project that withdraws usually does not pay the full amount, so read a quoted cost as an upper bound. -- The study report PDFs are PJM only. Other grid operators do not post them freely, so the narrative half of the system covers PJM. -- Withdrawal risk here is reasoning, not prediction. The agent weighs known cost signals against public research findings and frames risk. It never claims a project will withdraw for certain, and it is not a trained model. -- Cost extraction can miss figures. Some studies give one clean upgrade total, others spread the cost across many lines with no total, which is harder to read. The code handles the common shapes, so read the numbers as careful estimates. +| Data | What I use it for | Licence and terms | +|---|---|---| +| [Berkeley Lab, Queued Up: 2026 Edition](https://emp.lbl.gov/publications/queued-2026-edition-characteristics) ([data file](https://eta-publications.lbl.gov/sites/default/files/2026-05/lbnl_ix_queue_data_file_thru2025.xlsx)) | The panel, and the national figures on completion and withdrawal | [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/), credited to Lawrence Berkeley National Laboratory and GridTracker. `make data` downloads it, and Git ignores it. | +| PJM study reports, such as [AC2-093's](https://www.pjm.com/pjmfiles/pub/planning/project-queues/impact_studies/ac2093_imp.pdf) | The passages the agent reads, and the costs | © PJM Interconnection, all rights reserved. `make fetch` downloads them for your own use, and Git ignores them. | +| PJM's live queue, through [gridstatus](https://github.com/gridstatus/gridstatus) (optional) | An alternative to Berkeley Lab's data | PJM's terms apply (see its [legal page](https://www.pjm.com/about-pjm/legal.aspx)). The data stays on your computer. | -## Future work +Research and other sources: -- Add more grid operators to the structured data. The schema already has an iso column for this. -- Add CAISO study reports where they are posted publicly. -- Train a withdrawal model once enough cost history has been extracted, to replace the reasoning layer with a calibrated probability. +- Gorman and others (2025), "Grid connection barriers to renewable energy deployment in the United States", *Joule* 9(2), [doi:10.1016/j.joule.2024.11.008](https://doi.org/10.1016/j.joule.2024.11.008). +- Berkeley Lab (2023), "Interconnection Cost Analysis in the PJM Territory", [summary](https://emp.lbl.gov/publications/interconnection-cost-analysis-pjm) and [brief](https://eta-publications.lbl.gov/sites/default/files/berkeley_lab_2023.1.12-_pjm_interconnection_costs.pdf): the costs of withdrawn PJM projects, how it defines each cost, and the time it took to read costs by hand. +- FERC Order No. 2023, Federal Register, 6 September 2023, [official text](https://www.govinfo.gov/content/pkg/FR-2023-09-06/html/2023-16628.htm): how a withdrawal affects the projects behind it (paragraph 47). +- [PJM's home page](https://www.pjm.com/): it serves 13 states and the District of Columbia. +- OpenAI's [pricing](https://developers.openai.com/api/docs/pricing) and [deprecations](https://developers.openai.com/api/docs/deprecations) pages: the model prices in `src/config.py` and the shutdown dates. The pricing page doesn't list `gpt-4.1-nano`, which has been shut down, so its price in `src/config.py` is an assumption, used only for the extraction's cost estimates. -## References +## Licence -- LBNL Queued Up dataset and interconnection cost series, https://emp.lbl.gov/queues -- The queue panel is built from the Queued Up: 2026 Edition data file, with queues as of the end of 2025, by Lawrence Berkeley National Laboratory and GridTracker, licensed CC BY 4.0, https://emp.lbl.gov/publications/queued-2026-edition-characteristics -- US Department of Energy i2X program -- Gorman et al., grid connection barriers, Joule 2024 +The code is under the [MIT licence](LICENSE). Each dataset keeps its publisher's licence and terms, listed above. diff --git a/assets/example.png b/assets/example.png deleted file mode 100644 index d95559b..0000000 Binary files a/assets/example.png and /dev/null differ diff --git a/docs/decisions.md b/docs/decisions.md index 369d8b6..022770d 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -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 `. + +**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`. diff --git a/docs/future_work.md b/docs/future_work.md new file mode 100644 index 0000000..53f8120 --- /dev/null +++ b/docs/future_work.md @@ -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. diff --git a/src/config.py b/src/config.py index cd671fb..5c1d080 100644 --- a/src/config.py +++ b/src/config.py @@ -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. diff --git a/src/fetch_pdfs.py b/src/fetch_pdfs.py index 6cbaca2..d7c2eb9 100644 --- a/src/fetch_pdfs.py +++ b/src/fetch_pdfs.py @@ -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 @@ -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') " diff --git a/src/ingest_pdfs.py b/src/ingest_pdfs.py index 51b6c1b..c4151a7 100644 --- a/src/ingest_pdfs.py +++ b/src/ingest_pdfs.py @@ -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