diff --git a/README.md b/README.md index ce5c911..f5ff471 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,7 @@ These figures come from runs on 30 November 2026 at the default settings. **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 21 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. -**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. +**Costs.** The panel has no extracted costs yet, because embedding the reports and extracting their costs are paid steps I haven't run (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 @@ -72,7 +72,7 @@ make data make panel make fetch 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) +make extract DRY_RUN=false ``` Then ask questions, in the browser or the terminal: @@ -99,24 +99,24 @@ make embed DRY_RUN=false 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`. - **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. +- **Extraction and questions.** I haven't measured these yet. 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. ## Tests and evaluation `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. -`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. +`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. I haven't run the evaluation yet, because it needs the paid steps first. ## 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 paid steps haven't run yet.** Embedding the reports, extracting their costs, asking the agent questions and the evaluation all call OpenAI's paid models, and I haven't run any of them. The agent and the extraction use `gpt-6-luna` ([why](docs/decisions.md#the-models-gpt-6-luna-with-reasoning-off)), and no request has gone to it yet. So I haven't confirmed that OpenAI accepts the settings the code sends, or that the costs the code reports match OpenAI's bill. Nor have I measured how accurately the model extracts costs, how well the agent answers, or what either costs. The offline tests use a stand-in for OpenAI, so they check what the code sends, not what OpenAI does with it. - **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. +- **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%. - **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. @@ -144,7 +144,7 @@ Downloads and built data go in `data/raw/`, `data/processed/` and `data/vectors/ ## Built with -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. +Python 3.11 to 3.14, LangChain and LangGraph for the agent, and OpenAI's models: `gpt-6-luna`, with its reasoning (the hidden working-out it can do before it answers) switched off, for answers and 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 @@ -160,7 +160,7 @@ Research and other sources: - 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. +- OpenAI's [pricing](https://developers.openai.com/api/docs/pricing), [deprecations](https://developers.openai.com/api/docs/deprecations) and [prompt caching](https://developers.openai.com/api/docs/guides/prompt-caching) pages: the model prices and cache rates in `src/config.py`, and the models OpenAI is retiring. ## Licence diff --git a/docs/decisions.md b/docs/decisions.md index 022770d..28ac704 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -18,12 +18,46 @@ This file records the main choices behind the agent: what I decided, what I cons - **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). +**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. I haven't run the evaluation yet, because it needs the paid steps first (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. +## The models: gpt-6-luna with reasoning off + +**Decision.** The agent and the cost extraction both use OpenAI's `gpt-6-luna`, and the study reports are embedded with `text-embedding-3-small`. Every request to `gpt-6-luna`: +- switches its reasoning off (`reasoning_effort` set to `none`); +- sets the temperature, which controls how much randomness the model adds when it picks its words, to 0; +- goes through Chat Completions, the older of OpenAI's two interfaces for sending a conversation to a model; +- asks for OpenAI's standard service tier (OpenAI sells several processing speeds, each at its own price), the one whose prices `src/config.py` lists. A request that names no tier gets whichever tier the OpenAI account's project settings choose, and other tiers have other prices. + +The model names and prices live in `src/config.py`. + +**Why.** +- **The jobs suit a small model.** In the extraction, the model copies figures from a few passages into a fixed set of fields. As the agent, it picks a tool, writes a database query or a search, and writes an answer that cites its evidence. +- **It replaces the retiring models, and it is the cheapest.** OpenAI shut down `gpt-4.1-nano`, the old extraction model, on 23 October 2026, and shuts down `gpt-4.1-mini`, the old agent model, on 14 January 2027. It lists `gpt-6-luna` as the replacement for `gpt-4.1` and `gpt-4.1-mini`. OpenAI charges by the token, a chunk of text a few characters long. At $0.10 per million input tokens and $0.50 per million output tokens, `gpt-6-luna` is the cheapest chat model on OpenAI's price list that isn't due to retire. +- **Reasoning off suits these jobs.** `gpt-6-luna` is a reasoning model: unless told otherwise, it works through hidden steps before it answers, and they are billed as output tokens. Copying figures and querying a table need little of that. OpenAI's deployment checklist advises keeping a model's current reasoning effort when moving work to GPT-6, which for a model that doesn't reason, such as `gpt-4.1-mini`, means none. +- **It is the only setting the agent can use on Chat Completions.** OpenAI's model page and GPT-6 guide say that with reasoning on, `gpt-6-luna` doesn't support tool calls there, which the agent needs, or any temperature setting. + +**Alternatives.** +- **`gpt-5.6-luna`,** OpenAI's listed replacement for `gpt-4.1-nano`. It costs $0.20 and $1.20 per million, two to two and a half times as much, and is an older generation. +- **A larger model,** such as `gpt-6-sol` ($2 and $10 per million) or `gpt-6.1-terra` ($1 and $5). These cost 10 to 20 times as much, for jobs a small model should manage. OpenAI's GPT-6 guide says `gpt-6-sol` accepts the same settings, so it would need only its prices added to `src/config.py`. The newer `gpt-6.1-sol` and `gpt-6.2-sol` can't switch reasoning off, and `gpt-6.1-terra` can only call tools through the Responses API. I'd switch only if the evaluation shows the small model failing. +- **Reasoning on, at `low`.** OpenAI's [deployment checklist](https://developers.openai.com/api/docs/guides/deployment-checklist) suggests it for jobs that are mostly extraction. It adds output tokens, rules out temperature 0, and blocks the agent's tool calls on Chat Completions. I'd test it for the extraction if the extracted figures come out wrong. +- **The Responses API,** OpenAI's newer interface, which it recommends for new work and requires for reasoning with tools. It changes how requests and replies are sent, so it would need its own tests, and it brings nothing while reasoning is off. +- **`text-embedding-3-large`** for the embeddings, at 6.5 times the price ($0.13 per million). I'd consider it only if search keeps missing the passages that hold the costs. +- **Turning off prompt caching for the extraction.** OpenAI keeps the start of any prompt of 1,024 tokens or more in a short-term cache, and bills writing it at $0.125 per million tokens, a quarter more than plain input. Each extraction prompt is used once, so the writes only add cost. I left them on, because a prompt holds at most seven passages of up to 1,000 characters plus the instructions, so for 25 reports the writes cost less than a cent more than plain input would. + +**Evidence.** +- I read OpenAI's [deprecations page](https://developers.openai.com/api/docs/deprecations), [pricing page](https://developers.openai.com/api/docs/pricing), [gpt-6-luna model page](https://platform.openai.com/docs/models/gpt-6-luna), [GPT-6 guide](https://developers.openai.com/api/docs/guides/latest-model/gpt-6-astra), [prompt caching guide](https://developers.openai.com/api/docs/guides/prompt-caching), [deployment checklist](https://developers.openai.com/api/docs/guides/deployment-checklist) and [Chat Completions reference](https://platform.openai.com/docs/api-reference/chat/create) on 28 November 2026, and the pricing page, GPT-6 guide and deployment checklist again on 30 November. +- Offline tests check that every request carries the settings above, and that the agent's requests include both tools. + +**Uncertain.** +- **Whether OpenAI accepts the requests.** I haven't sent any request to `gpt-6-luna`. The settings above come from OpenAI's documentation, and the offline tests only check, against a stand-in for OpenAI, that the code sends them. I also haven't compared the costs the code reports, including its pricing of cached tokens, with a real OpenAI bill. +- **How well it works.** I haven't run the paid steps yet. I'll check the extraction by adding the reports of three projects outside the default sample (AC2-093, AF1-236 and AF2-353), and comparing the costs it extracts with the figures I read from them by hand. The evaluation questions (`make eval`) check whether the agent picks the right tool, writes a correct query and grounds its answer in the evidence. +- **Repeatability.** Temperature 0 makes answers less random, but not identical from run to run. +- **The cost estimates.** The estimate before an extraction run counts the tokens in the first project's prompt and assumes every prompt is that long. It adds the description of the reply's fields that goes with each request, and allows a fixed amount for each reply. The `tiktoken` library, which counts tokens offline, doesn't know `gpt-6-luna`, so the count uses `o200k_base`, the encoding `tiktoken` uses for `gpt-4o`, `gpt-4.1` and `gpt-5`. The estimate prices every prompt token at the cache-write rate, since each prompt is new. Paid runs report the tokens OpenAI measured, and price cached tokens at their own rates. + ## 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 `. diff --git a/docs/future_work.md b/docs/future_work.md index 75601ad..8686f39 100644 --- a/docs/future_work.md +++ b/docs/future_work.md @@ -4,7 +4,7 @@ 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. +- **Run the paid steps.** Embed the reports, extract their costs and run the evaluation. Then add the reports of AC2-093, AF1-236 and AF2-353, which aren't in the default sample, and check their extracted costs against the figures I read from them by hand. This needs OpenAI credits. - **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. diff --git a/src/agent.py b/src/agent.py index b65b2ee..7344d9d 100644 --- a/src/agent.py +++ b/src/agent.py @@ -13,7 +13,7 @@ from langgraph.errors import GraphRecursionError from langgraph.graph.state import CompiledStateGraph -from src.config import settings +from src.config import REASONING_EFFORT, SERVICE_TIER, TEMPERATURE, settings from src.tools import GROUNDING_FINDINGS, query_queue, search_studies # a single question must never trigger an unbounded chain of tool calls, this caps the @@ -83,8 +83,13 @@ def build_agent(checkpointer: BaseCheckpointSaver | None = None) -> CompiledStat Pass a checkpointer to keep the running message history across calls, which is how the chat loop carries context between questions. The single shot ask path leaves it unset. """ - # zero temperature, answers should be reproducible and stay close to the retrieved evidence. - model = ChatOpenAI(model=settings.chat_model, api_key=settings.openai_api_key, temperature=0) + model = ChatOpenAI( + model=settings.chat_model, + api_key=settings.openai_api_key, + temperature=TEMPERATURE, + reasoning_effort=REASONING_EFFORT, + service_tier=SERVICE_TIER, + ) agent = create_agent(model, AGENT_TOOLS, system_prompt=SYSTEM_PROMPT, checkpointer=checkpointer) agent = agent.with_config({"recursion_limit": RECURSION_LIMIT}) # confirm the cap took, an unbounded tool loop is the one real cost risk in this component. diff --git a/src/cli.py b/src/cli.py index ec2811f..f5d1cd1 100644 --- a/src/cli.py +++ b/src/cli.py @@ -9,7 +9,7 @@ import argparse from src.agent import Conversation, ask -from src.config import PLACEHOLDER_API_KEY, require_key_for_paid_run, settings +from src.config import MODEL_PRICES, PLACEHOLDER_API_KEY, require_key_for_paid_run, settings from src.fetch_queue import workbook_is_verified from src.ingest_pdfs import existing_queue_ids, get_querying_store, open_store from src.ingest_queue import query_projects @@ -27,6 +27,13 @@ def _key_status() -> str: return "present" if settings.openai_api_key else "missing, set OPENAI_API_KEY in .env" +def _model_status(model: str) -> str: + """The model name, flagged if it has no price, as for a retired model named in an older .env.""" + if model in MODEL_PRICES: + return model + return f"{model}, which has no price in src/config.py. delete its line in .env to use the default" + + def _workbook_status() -> str: """Whether the pinned LBNL workbook is on disk and unaltered.""" path = settings.lbnl_workbook_path @@ -66,9 +73,9 @@ def run_setup_check() -> None: print("setup check") print(f" openai key: {_key_status()}") print(f" dry run: {settings.dry_run}") - print(f" chat model: {settings.chat_model}") - print(f" extract model: {settings.extract_model}") - print(f" embed model: {settings.embed_model}") + print(f" chat model: {_model_status(settings.chat_model)}") + print(f" extract model: {_model_status(settings.extract_model)}") + print(f" embed model: {_model_status(settings.embed_model)}") print(f" queue workbook: {_workbook_status()}") print(f" queue panel: {_panel_status()}") print(f" study pdfs: {_pdf_status()}") diff --git a/src/config.py b/src/config.py index 5c1d080..936608d 100644 --- a/src/config.py +++ b/src/config.py @@ -9,6 +9,7 @@ from datetime import date from pathlib import Path +from langchain_core.messages.ai import UsageMetadata from pydantic import Field from pydantic_settings import BaseSettings, SettingsConfigDict @@ -19,25 +20,81 @@ PLACEHOLDER_API_KEY = "sk-your-key-here" # openai list prices in dollars per million tokens, keyed by model so a model swap picks up the -# right price with no change in the calling code. the embedding model bills input only. +# right price with no change in the calling code. standard tier, from +# https://developers.openai.com/api/docs/pricing as of 28 November 2026. gpt-6-luna caches any +# prompt of 1,024 tokens or more by default, and bills cached tokens at their own rates: +# cache_write for a prompt written with the default 30 minute lifetime, cache_read for one read +# back (https://developers.openai.com/api/docs/guides/prompt-caching). it charges more for prompts +# over 272,000 input tokens, far beyond any request here. the embedding model bills input only. MODEL_PRICES: dict[str, dict[str, float]] = { - "gpt-4.1": {"input": 2.00, "output": 8.00}, - "gpt-4.1-mini": {"input": 0.40, "output": 1.60}, - "gpt-4.1-nano": {"input": 0.10, "output": 0.40}, + "gpt-6-luna": {"input": 0.10, "cache_read": 0.01, "cache_write": 0.125, "output": 0.50}, "text-embedding-3-small": {"input": 0.02, "output": 0.00}, } +# gpt-6-luna reasons before it answers unless reasoning is off. with it off the model accepts +# temperature 0 and can call tools on the chat completions API, which the agent uses. a swapped +# chat model has to do both with reasoning off, as gpt-6-sol does. +REASONING_EFFORT = "none" -def token_cost(model: str, input_tokens: int, output_tokens: int) -> float: +# standard processing, the tier MODEL_PRICES lists. a request that leaves it unset gets the tier +# set in the openai project's settings, and a faster or cheaper tier is billed at other prices. +SERVICE_TIER = "default" + +# zero temperature. the extraction copies figures and the agent answers from evidence, so both +# should vary as little as possible between runs. +TEMPERATURE = 0 + + +def token_cost( + model: str, + input_tokens: int, + output_tokens: int, + cache_read_tokens: int = 0, + cache_write_tokens: int = 0, +) -> float: """Dollar cost for the given token counts at a model's list price. - Raises for a model with no listed price rather than guessing, so an unpriced model is caught - at the point of use instead of silently reporting a wrong cost. + input_tokens counts every prompt token. The ones read from or written to OpenAI's prompt cache + are billed at their own rates and the rest at the plain input rate. Raises for a model with no + listed price rather than guessing, so an unpriced model is caught at the point of use instead + of silently reporting a wrong cost. """ price = MODEL_PRICES.get(model) if price is None: - raise KeyError(f"no list price for model {model!r}, add it to MODEL_PRICES in config") - return (input_tokens * price["input"] + output_tokens * price["output"]) / 1_000_000 + raise KeyError( + f"no price for model {model!r} in MODEL_PRICES in src/config.py. " + "if .env names an older model, delete that line to use the default" + ) + plain_input_tokens = input_tokens - cache_read_tokens - cache_write_tokens + return ( + plain_input_tokens * price["input"] + + cache_read_tokens * price.get("cache_read", price["input"]) + + cache_write_tokens * price.get("cache_write", price["input"]) + + output_tokens * price["output"] + ) / 1_000_000 + + +def require_price(model: str) -> None: + """Raise before the first paid call if the model has no listed price, as token_cost would after it.""" + token_cost(model, 0, 0) + + +def usage_cost(model: str, usage: UsageMetadata | None) -> float: + """Dollar cost of the token counts OpenAI reported for one or more replies. + + The counts come from LangChain's usage metadata, whose input details say how many prompt + tokens were read from or written to the cache. + """ + if not usage: + return 0.0 + details = usage.get("input_token_details") or {} + return token_cost( + model, + usage["input_tokens"], + usage["output_tokens"], + cache_read_tokens=details.get("cache_read") or 0, + cache_write_tokens=details.get("cache_creation") or 0, + ) class Settings(BaseSettings): @@ -56,8 +113,8 @@ class Settings(BaseSettings): pjm_api_key: str = "" # the env names carry an OPENAI_ prefix, the public attributes stay short. - chat_model: str = Field(default="gpt-4.1-mini", validation_alias="OPENAI_CHAT_MODEL") - extract_model: str = Field(default="gpt-4.1-nano", validation_alias="OPENAI_EXTRACT_MODEL") + chat_model: str = Field(default="gpt-6-luna", validation_alias="OPENAI_CHAT_MODEL") + extract_model: str = Field(default="gpt-6-luna", validation_alias="OPENAI_EXTRACT_MODEL") embed_model: str = Field(default="text-embedding-3-small", validation_alias="OPENAI_EMBED_MODEL") # one ISO keeps the first build tight. the queue panel and the study PDFs both come diff --git a/src/extract.py b/src/extract.py index 27afa57..2c9c51d 100644 --- a/src/extract.py +++ b/src/extract.py @@ -1,13 +1,14 @@ """Extract cost fields from PJM study excerpts and write them back into the queue panel. Each project sends only its top retrieved chunks to the chat model, never the whole -PDF, which is what keeps a nano tier model both cheap and focused on the passages that +PDF, which is what keeps a small model both cheap and focused on the passages that actually mention cost. The full extracted record lands in the study_extracts table, and cost_per_kw is copied onto the matching row of the projects table, since that is the field the structured query tool already expects to find populated. """ import argparse +import json from pathlib import Path import duckdb @@ -15,11 +16,21 @@ import tiktoken from langchain_chroma import Chroma from langchain_core.documents import Document +from langchain_core.messages.ai import UsageMetadata, add_usage from langchain_core.runnables import Runnable from langchain_openai import ChatOpenAI, OpenAIEmbeddings from pydantic import BaseModel, Field -from src.config import require_key_for_paid_run, settings, token_cost +from src.config import ( + REASONING_EFFORT, + SERVICE_TIER, + TEMPERATURE, + require_key_for_paid_run, + require_price, + settings, + token_cost, + usage_cost, +) from src.ingest_pdfs import existing_queue_ids, open_store from src.ingest_queue import ( CREATE_STUDY_EXTRACTS_TABLE, @@ -60,8 +71,9 @@ # a small structured record, used only to size the dry run cost estimate. ESTIMATED_OUTPUT_TOKENS = 120 -# used only if the configured extract model is not in tiktoken's built in table. -FALLBACK_ENCODING = "cl100k_base" +# used only if the configured extract model is not in tiktoken's built in table, as gpt-6-luna is +# not in tiktoken 0.14. it is the encoding tiktoken gives the gpt-4o, gpt-4.1, gpt-5 and o series. +FALLBACK_ENCODING = "o200k_base" # the current lbnl snapshot carries no hand extracted cost column, so this only matters # if a future release of the workbook adds one under this name. @@ -113,6 +125,11 @@ class StudyExtract(BaseModel): ) +# every extraction request carries this description of the reply's fields, and openai counts it +# as prompt tokens, so the dry run's estimate adds it to each project's prompt. +REPLY_SCHEMA = json.dumps(StudyExtract.model_json_schema()) + + def network_upgrade_total(extract: StudyExtract) -> float | None: """The network upgrade cost, a single stated total when the study gives one, else derived. @@ -195,23 +212,21 @@ def retrieve_chunks( def extract_for_project( chain: Runnable, queue_id: str, prompt: str -) -> tuple[StudyExtract | None, int, int]: - """Run the structured output chain and return the record with the tokens the call used. +) -> tuple[StudyExtract | None, UsageMetadata | None]: + """Run the structured output chain and return the record with the usage the call reported. The chain is built with include_raw, so the reply's usage metadata gives the real token counts. The record is None, and the reason is printed, when the reply holds no record that fits the schema, for example a refusal. The known queue id wins over whatever the model guesses. """ result = chain.invoke(prompt) - usage = result["raw"].usage_metadata or {} - input_tokens = usage.get("input_tokens", 0) - output_tokens = usage.get("output_tokens", 0) + usage = result["raw"].usage_metadata if result["parsed"] is None: reason = str(result["parsing_error"] or "the reply held no record").partition("\n")[0] print(f"{queue_id}: no structured reply, skipped, {reason}") - return None, input_tokens, output_tokens + return None, usage extract = result["parsed"].model_copy(update={"queue_id": queue_id}) - return extract, input_tokens, output_tokens + return extract, usage def already_extracted_queue_ids() -> set[str]: @@ -275,8 +290,14 @@ def _extract_encoding() -> tiktoken.Encoding: def _estimate_cost(input_tokens: int, output_tokens: int) -> float: - """Return the dollar cost for the given token counts at the extract model's list price.""" - return token_cost(settings.extract_model, input_tokens, output_tokens) + """Estimate the dollar cost of these token counts at the extract model's list price. + + Each project's prompt is new, so OpenAI may write all of it to its prompt cache, which costs + more than plain input. Every input token is priced at that cache write rate. + """ + return token_cost( + settings.extract_model, input_tokens, output_tokens, cache_write_tokens=input_tokens + ) def extract_all(limit: int | None = None, rebuild: bool = False) -> dict[str, float]: @@ -306,7 +327,7 @@ def _preview_extraction(store: Chroma, pending: list[str]) -> dict[str, float]: chunks = preview_chunks(store, sample_id, settings.retrieval_k + CAPACITY_SUPPLEMENT_CHUNKS) prompt = build_prompt(sample_id, chunks) encoding = _extract_encoding() - tokens_per_project = len(encoding.encode(prompt)) + tokens_per_project = len(encoding.encode(prompt)) + len(encoding.encode(REPLY_SCHEMA)) input_tokens = tokens_per_project * len(pending) output_tokens = ESTIMATED_OUTPUT_TOKENS * len(pending) cost = _estimate_cost(input_tokens, output_tokens) @@ -322,8 +343,14 @@ def _preview_extraction(store: Chroma, pending: list[str]) -> dict[str, float]: def _run_extraction(store: Chroma, pending: list[str]) -> dict[str, float]: """Extract and write back cost fields for every pending project, then report measured usage.""" - # zero temperature, this is a factual extraction task and should not vary between runs. - chat = ChatOpenAI(model=settings.extract_model, api_key=settings.openai_api_key, temperature=0) + require_price(settings.extract_model) + chat = ChatOpenAI( + model=settings.extract_model, + api_key=settings.openai_api_key, + temperature=TEMPERATURE, + reasoning_effort=REASONING_EFFORT, + service_tier=SERVICE_TIER, + ) chain = chat.with_structured_output(StudyExtract, include_raw=True) embeddings = OpenAIEmbeddings(model=settings.embed_model, api_key=settings.openai_api_key) # both queries are fixed, so embed each once and reuse them for every project. @@ -331,14 +358,12 @@ def _run_extraction(store: Chroma, pending: list[str]) -> dict[str, float]: capacity_vector = embeddings.embed_query(CAPACITY_RETRIEVAL_QUERY) extracted = 0 - input_tokens = 0 - output_tokens = 0 + usage = add_usage(None, None) for queue_id in pending: chunks = retrieve_chunks(store, cost_vector, capacity_vector, queue_id, settings.retrieval_k) prompt = build_prompt(queue_id, chunks) - extract, call_input, call_output = extract_for_project(chain, queue_id, prompt) - input_tokens += call_input - output_tokens += call_output + extract, call_usage = extract_for_project(chain, queue_id, prompt) + usage = add_usage(usage, call_usage) if extract is None: # nothing is stored, so the project stays pending for the next run. continue @@ -346,12 +371,15 @@ def _run_extraction(store: Chroma, pending: list[str]) -> dict[str, float]: extracted += 1 print(f"{queue_id}: extracted, cost_per_kw {cost_per_kw}") - cost = _estimate_cost(input_tokens, output_tokens) + cost = usage_cost(settings.extract_model, usage) + cached = usage.get("input_token_details") or {} print( - f"extracted {extracted} of {len(pending)} projects, measured input tokens {input_tokens}, " - f"output tokens {output_tokens}, cost ${cost:.4f}" + f"extracted {extracted} of {len(pending)} projects, measured input tokens " + f"{usage['input_tokens']} ({cached.get('cache_creation') or 0} written to and " + f"{cached.get('cache_read') or 0} read from the prompt cache), " + f"output tokens {usage['output_tokens']}, cost ${cost:.4f}" ) - return {"projects": extracted, "input_tokens": input_tokens, "cost": cost} + return {"projects": extracted, "input_tokens": usage["input_tokens"], "cost": cost} def find_lbnl_workbook() -> Path | None: diff --git a/tests/conftest.py b/tests/conftest.py index a63ad42..62bc6eb 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,7 +1,7 @@ import pytest import tiktoken -from src.config import settings +from src.config import Settings, settings class StandInEncoding: @@ -17,6 +17,11 @@ def offline_and_unpaid(monkeypatch): # that forgets to mock the model cannot spend money. tests that need a paid path set both. monkeypatch.setattr(settings, "dry_run", True) monkeypatch.setattr(settings, "openai_api_key", "") + # the developer's .env may name other models, so tests request and price the defaults. + for field in ("chat_model", "extract_model", "embed_model"): + monkeypatch.setattr(settings, field, Settings.model_fields[field].default) + # ChatOpenAI refuses a proxy set in the shell alongside the stub client some tests pass it. + monkeypatch.delenv("OPENAI_PROXY", raising=False) # tiktoken downloads its encodings on first use, so token counts use a local stand-in. monkeypatch.setattr(tiktoken, "encoding_for_model", lambda model: StandInEncoding()) monkeypatch.setattr(tiktoken, "get_encoding", lambda name: StandInEncoding()) diff --git a/tests/eval_questions.py b/tests/eval_questions.py index 40b1161..b5d6b18 100644 --- a/tests/eval_questions.py +++ b/tests/eval_questions.py @@ -13,11 +13,12 @@ from dataclasses import dataclass from langchain_core.messages import BaseMessage, HumanMessage, ToolMessage +from langchain_core.messages.ai import UsageMetadata, add_usage from langgraph.errors import GraphRecursionError from langgraph.graph.state import CompiledStateGraph from src.agent import STEP_LIMIT_REPLY, ask, build_agent -from src.config import require_key_for_paid_run, settings, token_cost +from src.config import require_key_for_paid_run, require_price, settings, usage_cost from src.ingest_pdfs import get_querying_store from src.ingest_queue import query_projects @@ -248,24 +249,22 @@ def _tools_called(messages: list[BaseMessage]) -> list[str]: return [message.name for message in messages if isinstance(message, ToolMessage)] -def _token_usage(messages: list[BaseMessage]) -> tuple[int, int]: - """Sum input and output tokens across the run from each reply's usage metadata.""" - input_tokens = 0 - output_tokens = 0 +def _token_usage(messages: list[BaseMessage]) -> UsageMetadata: + """Sum the usage metadata of every reply in the run, cache reads and writes included.""" + usage = add_usage(None, None) for message in messages: - usage = getattr(message, "usage_metadata", None) - if usage: - input_tokens += usage.get("input_tokens", 0) - output_tokens += usage.get("output_tokens", 0) - return input_tokens, output_tokens + usage = add_usage(usage, getattr(message, "usage_metadata", None)) + return usage -def _cost(input_tokens: int, output_tokens: int) -> float: - return token_cost(settings.chat_model, input_tokens, output_tokens) +def _cost(usage: UsageMetadata) -> float: + return usage_cost(settings.chat_model, usage) -def answer_question(agent: CompiledStateGraph, prompt: str) -> tuple[str | None, list[str], int, int]: - """Run one question and return its answer, the tools it called, and its token counts. +def answer_question( + agent: CompiledStateGraph, prompt: str +) -> tuple[str | None, list[str], UsageMetadata]: + """Run one question and return its answer, the tools it called, and the tokens it used. The run is streamed so the messages so far survive a stop at the step limit. A stopped question has no answer, and the tokens it used still count. @@ -278,8 +277,7 @@ def answer_question(agent: CompiledStateGraph, prompt: str) -> tuple[str | None, answer = None else: answer = messages[-1].text - input_tokens, output_tokens = _token_usage(messages) - return answer, _tools_called(messages), input_tokens, output_tokens + return answer, _tools_called(messages), _token_usage(messages) def run_wiring_pass(questions: list[EvalQuestion]) -> None: @@ -294,18 +292,17 @@ def run_wiring_pass(questions: list[EvalQuestion]) -> None: def run_eval(questions: list[EvalQuestion]) -> None: """Ask each question for real, run its checks, and report token use and cost as they add up.""" + require_price(settings.chat_model) agent = build_agent() # build the vector client on the main thread, the agent calls search_studies from worker threads # where creating the native chroma client fresh has proven flaky. get_querying_store() - total_input = 0 - total_output = 0 + total = add_usage(None, None) passed = 0 total_checks = 0 for index, question in enumerate(questions, start=1): - answer, tools, input_tokens, output_tokens = answer_question(agent, question.prompt) - total_input += input_tokens - total_output += output_tokens + answer, tools, usage = answer_question(agent, question.prompt) + total = add_usage(total, usage) print(f"[{index}] {question.prompt}") print(f" tools called, {', '.join(tools) or 'none'}") @@ -319,14 +316,17 @@ def run_eval(questions: list[EvalQuestion]) -> None: total_checks += 1 print(f" [{'pass' if ok else 'FAIL'}] {label}") print( - f" tokens this question in {input_tokens} out {output_tokens}, " - f"running in {total_input} out {total_output}, cost so far ${_cost(total_input, total_output):.4f}\n" + f" tokens this question in {usage['input_tokens']} out {usage['output_tokens']}, " + f"running in {total['input_tokens']} out {total['output_tokens']}, " + f"cost so far ${_cost(total):.4f}\n" ) + cached = total.get("input_token_details") or {} print(f"checks passed {passed} of {total_checks}") print( - f"measured tokens in {total_input} out {total_output}, " - f"total cost ${_cost(total_input, total_output):.4f}" + f"measured tokens in {total['input_tokens']} ({cached.get('cache_creation') or 0} written to " + f"and {cached.get('cache_read') or 0} read from the prompt cache) out {total['output_tokens']}, " + f"total cost ${_cost(total):.4f}" ) diff --git a/tests/openai_stub.py b/tests/openai_stub.py new file mode 100644 index 0000000..23d27b8 --- /dev/null +++ b/tests/openai_stub.py @@ -0,0 +1,47 @@ +"""A local stand-in for the OpenAI API, so a test can read the exact requests a model sends.""" + +import json + +import httpx + + +class StubOpenAI: + """Answers every request with one fixed chat completion and keeps each request's path and body. + + Pass http_client to ChatOpenAI and its requests go here instead of over the network. Each reply + reports 50 input tokens, 10 of them read from the prompt cache and 30 written to it, and 5 + output tokens. + """ + + def __init__(self, content: str) -> None: + self.content = content + self.paths: list[str] = [] + self.bodies: list[dict] = [] + self.http_client = httpx.Client(transport=httpx.MockTransport(self._answer)) + + def _answer(self, request: httpx.Request) -> httpx.Response: + self.paths.append(request.url.path) + self.bodies.append(json.loads(request.content)) + return httpx.Response( + 200, + json={ + "id": "chatcmpl-stub", + "object": "chat.completion", + "created": 0, + "model": self.bodies[-1]["model"], + "service_tier": "default", + "choices": [ + { + "index": 0, + "message": {"role": "assistant", "content": self.content}, + "finish_reason": "stop", + } + ], + "usage": { + "prompt_tokens": 50, + "completion_tokens": 5, + "total_tokens": 55, + "prompt_tokens_details": {"cached_tokens": 10, "cache_write_tokens": 30}, + }, + }, + ) diff --git a/tests/test_agent.py b/tests/test_agent.py index 3c7edfd..ea6aef4 100644 --- a/tests/test_agent.py +++ b/tests/test_agent.py @@ -3,6 +3,7 @@ from langchain_core.language_models.chat_models import BaseChatModel from langchain_core.messages import AIMessage, HumanMessage, ToolMessage from langchain_core.outputs import ChatGeneration, ChatResult +from langchain_openai import ChatOpenAI from langgraph.checkpoint.memory import InMemorySaver from src.agent import ( @@ -15,6 +16,7 @@ ) from src.config import settings from src.tools import GROUNDING_FINDINGS, MAX_QUERY_ROWS, query_queue, search_studies +from tests.openai_stub import StubOpenAI class RoutingFakeChatModel(BaseChatModel): @@ -358,3 +360,19 @@ def test_system_prompt_carries_the_findings_and_the_withdrawal_caveats() -> None assert "preliminary" in lowered or "upper bound" in lowered # comparing a count based share to a capacity share needs the basis called out. assert "counting projects" in lowered or "capacity share" in lowered + + +def test_the_agent_asks_with_reasoning_off_and_both_tools_on_chat_completions(monkeypatch) -> None: + # gpt-6-luna takes tools on chat completions, and temperature 0, only with reasoning off. + stub = StubOpenAI("the panel holds 15 projects.") + monkeypatch.setattr(settings, "dry_run", False) + monkeypatch.setattr(settings, "openai_api_key", "fake-key-for-test") + monkeypatch.setattr( + "src.agent.ChatOpenAI", lambda **kwargs: ChatOpenAI(**kwargs, http_client=stub.http_client) + ) + assert ask("how many projects are in the panel?") == "the panel holds 15 projects." + assert len(stub.paths) == 1 and stub.paths[0].endswith("/chat/completions") + body = stub.bodies[0] + assert (body["reasoning_effort"], body["temperature"]) == ("none", 0) + assert body["service_tier"] == "default" + assert {tool["function"]["name"] for tool in body["tools"]} == {"query_queue", "search_studies"} diff --git a/tests/test_cli.py b/tests/test_cli.py index 5448227..00c4610 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -46,6 +46,15 @@ def test_setup_check_flags_a_workbook_that_is_not_the_pinned_release(monkeypatch assert "queue workbook: present, but not the pinned release" in capsys.readouterr().out +def test_setup_check_flags_a_model_with_no_price(monkeypatch, tmp_path, capsys) -> None: + monkeypatch.setattr(settings, "data_dir", tmp_path) + monkeypatch.setattr(settings, "extract_model", "a-retired-model") + cli.run_setup_check() + out = capsys.readouterr().out + assert "extract model: a-retired-model, which has no price in src/config.py" in out + assert f"chat model: {settings.chat_model}\n" in out + + def test_setup_check_reports_present_pieces_without_an_api_call(monkeypatch, tmp_path, capsys) -> None: monkeypatch.setattr(settings, "openai_api_key", "a-key") monkeypatch.setattr(settings, "data_dir", tmp_path) diff --git a/tests/test_config.py b/tests/test_config.py index 2e1b014..cd7d148 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -1,4 +1,5 @@ import pytest +from langchain_core.messages.ai import InputTokenDetails, UsageMetadata from src.config import ( PLACEHOLDER_API_KEY, @@ -7,6 +8,7 @@ require_key_for_paid_run, settings, token_cost, + usage_cost, ) # every setting .env.example mentions, cleared so a developer's shell cannot change the result. @@ -123,12 +125,32 @@ def test_search_k_reads_at_least_as_wide_as_extraction_retrieval() -> None: def test_token_cost_reads_the_price_from_the_model_table() -> None: - assert token_cost("gpt-4.1-mini", 1_000_000, 0) == pytest.approx(0.40) - assert token_cost("gpt-4.1-mini", 0, 1_000_000) == pytest.approx(1.60) + assert token_cost("gpt-6-luna", 1_000_000, 0) == pytest.approx(0.10) + assert token_cost("gpt-6-luna", 0, 1_000_000) == pytest.approx(0.50) + + +def test_token_cost_bills_cache_reads_and_writes_at_their_own_rates() -> None: + # the token counts of openai's worked example, with every write at the default 30 minute + # lifetime: 12,000 input tokens, 4,000 read from the cache and 7,000 written to it, so 1,000 + # are plain input. gpt-6-luna reads at $0.01 and writes at $0.125 a million. + cost = token_cost("gpt-6-luna", 12_000, 0, cache_read_tokens=4_000, cache_write_tokens=7_000) + assert cost == pytest.approx((1_000 * 0.10 + 4_000 * 0.01 + 7_000 * 0.125) / 1_000_000) + + +def test_usage_cost_reads_the_cache_counts_from_langchain_usage_metadata() -> None: + usage = UsageMetadata( + input_tokens=12_000, + output_tokens=100, + total_tokens=12_100, + input_token_details=InputTokenDetails(cache_read=4_000, cache_creation=7_000), + ) + # $0.0001 plain input, $0.00004 cache reads, $0.000875 cache writes and $0.00005 output. + assert usage_cost("gpt-6-luna", usage) == pytest.approx(0.001065) + assert usage_cost("gpt-6-luna", None) == 0.0 def test_token_cost_raises_for_a_model_with_no_listed_price() -> None: - with pytest.raises(KeyError): + with pytest.raises(KeyError, match="delete that line to use the default"): token_cost("some-unlisted-model", 100, 100) diff --git a/tests/test_eval_questions.py b/tests/test_eval_questions.py index 5924bd3..e4b2822 100644 --- a/tests/test_eval_questions.py +++ b/tests/test_eval_questions.py @@ -12,7 +12,11 @@ class MeteredLoopingModel(BaseChatModel): - """Always calls query_queue and reports 100 input and 10 output tokens per reply.""" + """Always calls query_queue and reports the same usage for every reply. + + Each reply reports 100 input tokens, 60 of them read from the prompt cache and 40 written to + it, and 10 output tokens. + """ @property def _llm_type(self) -> str: @@ -26,7 +30,12 @@ def _generate(self, messages, stop=None, run_manager=None, **kwargs) -> ChatResu reply = AIMessage( content="", tool_calls=[{"name": "query_queue", "args": {"sql": "SELECT 1"}, "id": f"call-{call_number}"}], - usage_metadata={"input_tokens": 100, "output_tokens": 10, "total_tokens": 110}, + usage_metadata={ + "input_tokens": 100, + "output_tokens": 10, + "total_tokens": 110, + "input_token_details": {"cache_read": 60, "cache_creation": 40}, + }, ) return ChatResult(generations=[ChatGeneration(message=reply)]) @@ -60,11 +69,12 @@ def looping_agent(monkeypatch): def test_a_question_stopped_at_the_step_limit_still_counts_its_tokens(looping_agent) -> None: - answer, tools, input_tokens, output_tokens = eval_questions.answer_question(build_agent(), "loop") + answer, tools, usage = eval_questions.answer_question(build_agent(), "loop") assert answer is None assert tools and set(tools) == {"query_queue"} - # five model replies ran before the stop, each reporting 100 in and 10 out. - assert (input_tokens, output_tokens) == (500, 50) + # five model replies ran before the stop. + assert (usage["input_tokens"], usage["output_tokens"]) == (500, 50) + assert usage["input_token_details"] == {"cache_read": 300, "cache_creation": 200} def test_a_question_stopped_at_the_step_limit_fails_every_check(looping_agent, capsys) -> None: @@ -80,3 +90,14 @@ def test_a_question_stopped_at_the_step_limit_fails_every_check(looping_agent, c output = capsys.readouterr().out assert STEP_LIMIT_REPLY in output assert "checks passed 0 of 3" in output + assert "measured tokens in 500 (200 written to and 300 read from the prompt cache) out 50" in output + + +def test_the_eval_with_an_unpriced_model_stops_before_the_first_question( + looping_agent, monkeypatch +) -> None: + monkeypatch.setattr(settings, "chat_model", "some-unlisted-model") + monkeypatch.setattr(eval_questions, "build_agent", lambda: pytest.fail("the agent was built")) + question = eval_questions.EvalQuestion(prompt="loop", checks=[]) + with pytest.raises(KeyError, match="no price for model 'some-unlisted-model'"): + eval_questions.run_eval([question]) diff --git a/tests/test_extract.py b/tests/test_extract.py index cb976df..9ba8a11 100644 --- a/tests/test_extract.py +++ b/tests/test_extract.py @@ -1,16 +1,20 @@ +import json import shutil from unittest.mock import MagicMock import pandas as pd import pytest +import tiktoken from langchain_chroma import Chroma from langchain_core.documents import Document from langchain_core.embeddings import DeterministicFakeEmbedding from langchain_core.messages import AIMessage +from langchain_openai import ChatOpenAI from pydantic import ValidationError from src.config import settings from src.extract import ( + ESTIMATED_OUTPUT_TOKENS, StudyExtract, already_extracted_queue_ids, build_prompt, @@ -33,6 +37,7 @@ query_projects, read_fixture, ) +from tests.openai_stub import StubOpenAI @pytest.fixture @@ -181,7 +186,7 @@ def _structured_reply( def test_extract_for_project_overrides_the_model_returned_queue_id() -> None: chain = MagicMock() chain.invoke.return_value = _structured_reply(StudyExtract(queue_id="wrong-id", studied_mw=100.0)) - result, _, _ = extract_for_project(chain, "ac2115", "a prompt") + result, _ = extract_for_project(chain, "ac2115", "a prompt") assert result.queue_id == "ac2115" assert result.studied_mw == 100.0 @@ -189,21 +194,25 @@ def test_extract_for_project_overrides_the_model_returned_queue_id() -> None: def test_extract_for_project_returns_the_tokens_the_reply_reports() -> None: chain = MagicMock() chain.invoke.return_value = _structured_reply(StudyExtract(studied_mw=100.0), 900, 40) - _, input_tokens, output_tokens = extract_for_project(chain, "ac2115", "a prompt") - assert (input_tokens, output_tokens) == (900, 40) + _, usage = extract_for_project(chain, "ac2115", "a prompt") + assert (usage["input_tokens"], usage["output_tokens"]) == (900, 40) def test_extract_for_project_skips_a_reply_that_does_not_parse_and_says_why(capsys) -> None: chain = MagicMock() chain.invoke.return_value = _structured_reply(None, 600, 9, ValueError("bad json\nat line 1")) - assert extract_for_project(chain, "ac2115", "a prompt") == (None, 600, 9) + record, usage = extract_for_project(chain, "ac2115", "a prompt") + assert record is None + assert (usage["input_tokens"], usage["output_tokens"]) == (600, 9) assert "ac2115: no structured reply, skipped, bad json" in capsys.readouterr().out def test_extract_for_project_returns_no_record_when_the_model_gives_none() -> None: chain = MagicMock() chain.invoke.return_value = _structured_reply(None, 700, 5) - assert extract_for_project(chain, "ac2115", "a prompt") == (None, 700, 5) + record, usage = extract_for_project(chain, "ac2115", "a prompt") + assert record is None + assert (usage["input_tokens"], usage["output_tokens"]) == (700, 5) def test_write_extract_updates_the_panel_cost_per_kw(panel) -> None: @@ -254,6 +263,22 @@ def _blow_up(*args: object, **kwargs: object) -> None: assert summary["input_tokens"] > 0 +def test_the_dry_run_estimate_adds_the_reply_schema_and_prices_input_as_cache_writes( + store_with_chunks, monkeypatch +) -> None: + monkeypatch.setattr(settings, "dry_run", True) + monkeypatch.setattr("src.extract.build_prompt", lambda queue_id, chunks: "a fixed prompt") + encoding = tiktoken.get_encoding("o200k_base") + schema = json.dumps(StudyExtract.model_json_schema()) + expected_input = len(encoding.encode("a fixed prompt")) + len(encoding.encode(schema)) + + summary = extract_all() + assert summary["input_tokens"] == expected_input + # gpt-6-luna's list prices: $0.125 per million tokens written to the cache, $0.50 for output. + expected_cost = (expected_input * 0.125 + ESTIMATED_OUTPUT_TOKENS * 0.50) / 1_000_000 + assert summary["cost"] == pytest.approx(expected_cost) + + def test_extract_all_writes_the_panel_back_through_the_run_path_with_a_mocked_llm( store_with_chunks, monkeypatch ) -> None: @@ -281,6 +306,57 @@ def test_extract_all_writes_the_panel_back_through_the_run_path_with_a_mocked_ll assert rows[0]["cost_per_kw"] == pytest.approx(20.0) +def test_extraction_asks_with_reasoning_off_for_a_reply_in_the_schema( + store_with_chunks, monkeypatch +) -> None: + # the whole request path offline, through the real structured output chain to a stub API. + record = StudyExtract(studied_mw=100.0, total_network_upgrade_cost_usd=2_000_000.0) + stub = StubOpenAI(record.model_dump_json()) + monkeypatch.setattr(settings, "dry_run", False) + monkeypatch.setattr(settings, "openai_api_key", "fake-key-for-test") + monkeypatch.setattr( + "src.extract.ChatOpenAI", lambda **kwargs: ChatOpenAI(**kwargs, http_client=stub.http_client) + ) + monkeypatch.setattr( + "src.extract.OpenAIEmbeddings", lambda **kwargs: DeterministicFakeEmbedding(size=16) + ) + + summary = extract_all() + assert summary["projects"] == 1 + # the stub reports 50 input tokens, 10 read from the prompt cache and 30 written to it, so 10 + # are plain input, plus 5 output tokens. + assert summary["input_tokens"] == 50 + assert summary["cost"] == pytest.approx( + (10 * 0.10 + 10 * 0.01 + 30 * 0.125 + 5 * 0.50) / 1_000_000 + ) + assert len(stub.paths) == 1 and stub.paths[0].endswith("/chat/completions") + body = stub.bodies[0] + assert (body["reasoning_effort"], body["temperature"]) == ("none", 0) + assert body["service_tier"] == "default" + assert body["response_format"]["type"] == "json_schema" + rows = query_projects("SELECT cost_per_kw FROM projects WHERE queue_id = 'ac2115'") + assert rows[0]["cost_per_kw"] == pytest.approx(20.0) + + +def test_a_paid_extraction_with_an_unpriced_model_stops_before_any_request( + store_with_chunks, monkeypatch +) -> None: + stub = StubOpenAI("{}") + monkeypatch.setattr(settings, "dry_run", False) + monkeypatch.setattr(settings, "openai_api_key", "fake-key-for-test") + monkeypatch.setattr(settings, "extract_model", "some-unlisted-model") + monkeypatch.setattr( + "src.extract.ChatOpenAI", lambda **kwargs: ChatOpenAI(**kwargs, http_client=stub.http_client) + ) + monkeypatch.setattr( + "src.extract.OpenAIEmbeddings", lambda **kwargs: DeterministicFakeEmbedding(size=16) + ) + + with pytest.raises(KeyError, match="no price for model 'some-unlisted-model'"): + extract_all() + assert stub.paths == [] + + @pytest.mark.parametrize("parsing_error", [None, ValueError("bad json")]) def test_a_project_with_no_structured_reply_stays_pending( store_with_chunks, monkeypatch, parsing_error