From 182e8d5932a180a055358656585375c7fbb1178f Mon Sep 17 00:00:00 2001 From: Azeem Ayman <110621518+aymanazeem@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:30:55 +0000 Subject: [PATCH 1/4] Move the agent and extraction to gpt-6-luna OpenAI shut down gpt-4.1-nano, the extraction default, on 23 October 2026, and shuts down gpt-4.1-mini, the chat default, on 14 January 2027. Both now default to gpt-6-luna, OpenAI's listed replacement. - gpt-6-luna is a reasoning model. Reasoning stays off, so it accepts temperature 0 and tool calls on the chat completions API. - Prices cite OpenAI's pricing page. The retired models' prices are removed. - The dry run estimate falls back to o200k_base, since tiktoken has no entry for gpt-6-luna. - make check flags a model with no price, such as a retired model named in an older .env. - Tests use the default models whatever .env names, and check the real requests through a local stub of the API. - docs/decisions.md records this choice, the DuckDB lockdown and the cost restore on rebuild. --- README.md | 2 +- docs/decisions.md | 78 +++++++++++++++++++++++++++++++++++++++++++ src/agent.py | 9 +++-- src/cli.py | 15 ++++++--- src/config.py | 18 ++++++---- src/extract.py | 18 ++++++---- tests/conftest.py | 5 ++- tests/openai_stub.py | 39 ++++++++++++++++++++++ tests/test_agent.py | 17 ++++++++++ tests/test_cli.py | 9 +++++ tests/test_config.py | 4 +-- tests/test_extract.py | 29 ++++++++++++++++ 12 files changed, 221 insertions(+), 22 deletions(-) create mode 100644 docs/decisions.md create mode 100644 tests/openai_stub.py diff --git a/README.md b/README.md index e99a85c..d3dda6d 100644 --- a/README.md +++ b/README.md @@ -66,7 +66,7 @@ Right now three projects have a full extracted cost, all of them withdrawn solar - 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 +- OpenAI's gpt-6-luna for cost extraction and the agent, with its reasoning mode off, and text-embedding-3-small for the embeddings ([why these models](docs/decisions.md#models-gpt-6-luna-with-reasoning-off)) - DuckDB for the structured queue panel - Chroma for the local vector store - gridstatus and the LBNL Queued Up dataset for the queue data diff --git a/docs/decisions.md b/docs/decisions.md new file mode 100644 index 0000000..4de0834 --- /dev/null +++ b/docs/decisions.md @@ -0,0 +1,78 @@ +# Design decisions + +This file records the main choices behind the agent: what I decided, what I considered instead, the evidence, and what is still uncertain. + +## Models: gpt-6-luna with reasoning off + +**Decision.** The agent and the cost extraction both use OpenAI's `gpt-6-luna`. +- Reasoning is switched off (`reasoning_effort` set to `none`) and the temperature is 0. +- Requests go through OpenAI's Chat Completions API. +- The study reports are embedded with `text-embedding-3-small`. Embedding turns each passage into a list of numbers, so that passages with similar meaning can be found by search. + +The model names and prices live in `src/config.py`. + +**Why.** + +- **The jobs are narrow.** The model has two jobs: copying figures from a few passages of a study report into a fixed set of fields, and choosing which of two tools to call to answer a question. A small, fast model should handle both. +- **It is OpenAI's replacement, and the cheapest.** OpenAI names `gpt-6-luna` as the replacement for `gpt-4.1` and `gpt-4.1-mini`, which it shuts down on 14 January 2027. It describes it as its most efficient model for focused, high-volume tasks. OpenAI charges by the token, a chunk of text of a few characters. `gpt-6-luna` costs $0.10 per million input tokens and $0.50 per million output tokens. That makes it the cheapest chat model on OpenAI's price list that isn't scheduled for retirement. +- **Reasoning off keeps the old behaviour and cost.** `gpt-6-luna` is a reasoning model: unless told otherwise, it thinks in hidden steps before it answers, and those steps are billed as output tokens. OpenAI's migration advice is to keep the reasoning effort the replaced model effectively had. The models it replaces don't reason, so `none` keeps the behaviour closest to theirs. +- **It is the only setting the agent can use.** With reasoning on, `gpt-6-luna` refuses tool calls on Chat Completions, which the agent needs, and it refuses temperature 0. + +**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 tasks a small model should manage. I would switch only if the evaluation shows the small model failing. +- **Reasoning on at `low`.** OpenAI suggests `low` for extraction when a model reasons. It adds output tokens and rules out temperature 0. It also blocks the agent's tool calls on Chat Completions, so the agent would have to move to the Responses API. I'd test it for extraction if the extracted figures come out wrong. +- **OpenAI's newer Responses API.** It is what OpenAI recommends for reasoning with tools, and newer releases of the `langchain-openai` library send `gpt-6` tool calls there by themselves. Moving would mean upgrading that library and handling a different message format. That is a bigger change, with no benefit 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. + +**Evidence.** + +- I read OpenAI's [deprecations page](https://platform.openai.com/docs/deprecations), [pricing page](https://platform.openai.com/docs/pricing), [gpt-6-luna model page](https://platform.openai.com/docs/models/gpt-6-luna) and [GPT-6 guide](https://developers.openai.com/api/docs/guides/latest-model/gpt-6-astra) on 28 November 2026. +- Offline tests check that every request carries the settings above: reasoning off, temperature 0 and, for the agent, both tools. + +**Uncertain.** + +- **Extraction accuracy.** How accurately `gpt-6-luna` reads costs from these reports is measured by the extraction check against figures I read by hand. +- **Repeatability.** Temperature 0 makes answers less random, but not identical from run to run. +- **Token estimates.** The `tiktoken` library, which counts tokens offline, has no entry for `gpt-6-luna`. So the free estimates before a run assume the `o200k_base` encoding, which `tiktoken` uses for OpenAI's `gpt-4o`, `gpt-4.1` and `gpt-5` models. Paid runs report the token counts OpenAI measured. + +## The agent's database queries cannot reach files + +**Decision.** The agent answers questions with SQL, a language for querying tables, that it writes itself. Every such query runs against a read-only copy of the queue table, with DuckDB's external access switched off (`enable_external_access = false`). DuckDB is the database that holds the table. + +**Why.** + +- **The study text could steer the agent.** The agent reads passages from study reports, and a passage could contain text written to steer it, known as prompt injection. +- **By default, DuckDB's SQL can read files and web addresses.** For example, `read_text('.env')` returns the file that holds the OpenAI key. +- **With external access off, every file and network function fails.** Normal queries on the table still work. + +**Alternatives.** + +- **Checking each query against a list of allowed tables and functions.** DuckDB has many functions that read files, so a list like this is easy to get wrong. +- **Copying the table into a fresh in-memory database for each query.** That only helps if external access is also off, and then the copy adds nothing. +- **Keeping the key out of the environment.** That protects the key but not other files. + +**Evidence.** + +- Tests check that `read_text`, `read_csv` and a quoted file path are refused. +- A separate review tried the other ways DuckDB offers to reach files and the web, and every one was refused. They included `read_blob`, the JSON and Parquet readers, `glob`, `query()`, installing an extension and web addresses. +- The queries the evaluation uses still work. + +**Trade-off.** The agent can't read any outside file, even a harmless one. It never needs to, because everything it queries is in the table. + +## Rebuilding the queue table keeps the extracted costs + +**Decision.** +- The table of extracted study figures (`study_extracts`) is created along with the queue table and survives a rebuild. +- Each rebuild recalculates every project's `cost_per_kw` from it. It uses 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 queue data if the study gives none. + +**Why.** The extraction skips projects it has already done, so it doesn't pay twice for the same study. Without this step, rebuilding the queue table left every cost blank, and the extraction would never fill them in again. + +**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 query tool describes, and makes every cost question more complex. +- **Recalculating in Python by calling the extraction code.** The queue-building module would then depend on the extraction module, which already depends on it. + +**Trade-off.** The ratio is written twice, in Python and in SQL. A test checks that both give the same costs, whether the study gives its megawatts, omits them or gives zero. diff --git a/src/agent.py b/src/agent.py index 9acccb3..49d3c24 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, 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 @@ -81,7 +81,12 @@ def build_agent(checkpointer: BaseCheckpointSaver | None = None) -> CompiledStat 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=0, + reasoning_effort=REASONING_EFFORT, + ) 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 8d1246b..3fc7ec6 100644 --- a/src/config.py +++ b/src/config.py @@ -19,14 +19,20 @@ 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://platform.openai.com/docs/pricing as of 28 November 2026. gpt-6-luna charges more for +# prompts over 272,000 input tokens, far beyond any request here, and bills its reasoning as +# output. 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, "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, and it works +# like the non-reasoning models it replaced. a swapped chat model has to accept it too. +REASONING_EFFORT = "none" + def token_cost(model: str, input_tokens: int, output_tokens: int) -> float: """Dollar cost for the given token counts at a model's list price. @@ -56,8 +62,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..4b726e7 100644 --- a/src/extract.py +++ b/src/extract.py @@ -1,7 +1,7 @@ """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. @@ -19,7 +19,7 @@ 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, require_key_for_paid_run, settings, token_cost from src.ingest_pdfs import existing_queue_ids, open_store from src.ingest_queue import ( CREATE_STUDY_EXTRACTS_TABLE, @@ -60,8 +60,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. @@ -322,8 +323,13 @@ 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) + # zero temperature, this is a factual extraction task and should vary as little as possible. + chat = ChatOpenAI( + model=settings.extract_model, + api_key=settings.openai_api_key, + temperature=0, + reasoning_effort=REASONING_EFFORT, + ) 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. diff --git a/tests/conftest.py b/tests/conftest.py index a63ad42..0372a5c 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,9 @@ 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) # 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/openai_stub.py b/tests/openai_stub.py new file mode 100644 index 0000000..478c02f --- /dev/null +++ b/tests/openai_stub.py @@ -0,0 +1,39 @@ +"""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. + """ + + 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"], + "choices": [ + { + "index": 0, + "message": {"role": "assistant", "content": self.content}, + "finish_reason": "stop", + } + ], + "usage": {"prompt_tokens": 50, "completion_tokens": 5, "total_tokens": 55}, + }, + ) diff --git a/tests/test_agent.py b/tests/test_agent.py index d94e481..f94d588 100644 --- a/tests/test_agent.py +++ b/tests/test_agent.py @@ -2,6 +2,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 ( @@ -14,6 +15,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): @@ -326,3 +328,18 @@ 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 {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..fed964e 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -123,8 +123,8 @@ 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_raises_for_a_model_with_no_listed_price() -> None: diff --git a/tests/test_extract.py b/tests/test_extract.py index cb976df..6126290 100644 --- a/tests/test_extract.py +++ b/tests/test_extract.py @@ -7,6 +7,7 @@ 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 @@ -33,6 +34,7 @@ query_projects, read_fixture, ) +from tests.openai_stub import StubOpenAI @pytest.fixture @@ -281,6 +283,33 @@ 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 for the call, and the summary carries that measured count. + assert summary["input_tokens"] == 50 + 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["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) + + @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 From 1a68b5702ea14f2efe8a8488c6698e1e2b207f1a Mon Sep 17 00:00:00 2001 From: Azeem Ayman <110621518+aymanazeem@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:58:56 +0000 Subject: [PATCH 2/4] Price prompt cache tokens and correct the model notes gpt-6-luna writes any prompt of 1,024 tokens or more to OpenAI's prompt cache by default. It bills those tokens at 1.25 times the input rate, and tokens read back from the cache at a tenth of it. The cost lines priced every prompt token as plain input, so they under-reported new prompts. - token_cost takes the cache read and write counts, and usage_cost prices the usage metadata a reply reports. Extraction and the evaluation sum the usage with LangChain's add_usage and price each reply as it arrives, so a model with no price stops a run after one call. - The free extraction estimate is an upper bound at the cache write rate. - The missing-price error says how to fix a stale model line in .env. - docs/decisions.md explains temperature, OpenAI's two interfaces and the token encoding, describes the agent's job in full, links the caching guide and the deployment checklist, and corrects the price ratios. - The README lists OpenAI's pricing and deprecations pages. - Tests clear OPENAI_PROXY, which ChatOpenAI refuses next to a stub client. 133 tests pass offline with an empty tiktoken cache. The stub extraction test fails on the previous code, which reported $0.0000075 instead of $0.0000085. --- README.md | 2 ++ docs/decisions.md | 34 +++++++++++--------- src/config.py | 60 +++++++++++++++++++++++++++++------- src/extract.py | 54 ++++++++++++++++++++------------ tests/conftest.py | 2 ++ tests/eval_questions.py | 49 +++++++++++++++-------------- tests/openai_stub.py | 11 +++++-- tests/test_config.py | 23 +++++++++++++- tests/test_eval_questions.py | 4 +-- tests/test_extract.py | 17 ++++++---- 10 files changed, 174 insertions(+), 82 deletions(-) diff --git a/README.md b/README.md index d3dda6d..d182f37 100644 --- a/README.md +++ b/README.md @@ -166,3 +166,5 @@ make eval DRY_RUN=false - 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 +- OpenAI API pricing, the source of the model prices in src/config.py, https://platform.openai.com/docs/pricing +- OpenAI model deprecations, the shutdown dates behind the choice of models, https://platform.openai.com/docs/deprecations diff --git a/docs/decisions.md b/docs/decisions.md index 4de0834..b3d5a8d 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -5,41 +5,45 @@ This file records the main choices behind the agent: what I decided, what I cons ## Models: gpt-6-luna with reasoning off **Decision.** The agent and the cost extraction both use OpenAI's `gpt-6-luna`. -- Reasoning is switched off (`reasoning_effort` set to `none`) and the temperature is 0. -- Requests go through OpenAI's Chat Completions API. +- Reasoning is switched off (`reasoning_effort` set to `none`). +- The temperature, which sets how much randomness the model adds when it picks its words, is 0. +- Requests go through Chat Completions, the older of OpenAI's two interfaces for sending a conversation to a model. The newer one is the Responses API. - The study reports are embedded with `text-embedding-3-small`. Embedding turns each passage into a list of numbers, so that passages with similar meaning can be found by search. The model names and prices live in `src/config.py`. **Why.** -- **The jobs are narrow.** The model has two jobs: copying figures from a few passages of a study report into a fixed set of fields, and choosing which of two tools to call to answer a question. A small, fast model should handle both. +- **The jobs suit a small model.** The model has two jobs. + - In the extraction, it copies figures from a few passages of a study report into a fixed set of fields. A small, fast model should manage this. + - As the agent, it chooses between two tools, writes the database query or the search for each, and writes an answer that cites its evidence. That includes the risk factors that could lead a project to withdraw from the queue. The evaluation questions measure how well it does this. - **It is OpenAI's replacement, and the cheapest.** OpenAI names `gpt-6-luna` as the replacement for `gpt-4.1` and `gpt-4.1-mini`, which it shuts down on 14 January 2027. It describes it as its most efficient model for focused, high-volume tasks. OpenAI charges by the token, a chunk of text of a few characters. `gpt-6-luna` costs $0.10 per million input tokens and $0.50 per million output tokens. That makes it the cheapest chat model on OpenAI's price list that isn't scheduled for retirement. -- **Reasoning off keeps the old behaviour and cost.** `gpt-6-luna` is a reasoning model: unless told otherwise, it thinks in hidden steps before it answers, and those steps are billed as output tokens. OpenAI's migration advice is to keep the reasoning effort the replaced model effectively had. The models it replaces don't reason, so `none` keeps the behaviour closest to theirs. -- **It is the only setting the agent can use.** With reasoning on, `gpt-6-luna` refuses tool calls on Chat Completions, which the agent needs, and it refuses temperature 0. +- **Reasoning off suits these jobs.** `gpt-6-luna` is a reasoning model: unless told otherwise, it thinks in hidden steps before it answers, and those steps are billed as output tokens. Copying figures and querying a table need little of that. OpenAI's advice when moving to its GPT-6 models is to keep the reasoning effort of the model being replaced, and `gpt-4.1` and `gpt-4.1-mini` don't reason at all. +- **It is the only setting the agent can use on Chat Completions.** With reasoning on, `gpt-6-luna` refuses tool calls there, which the agent needs, and it refuses temperature 0. **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 tasks a small model should manage. I would switch only if the evaluation shows the small model failing. -- **Reasoning on at `low`.** OpenAI suggests `low` for extraction when a model reasons. It adds output tokens and rules out temperature 0. It also blocks the agent's tool calls on Chat Completions, so the agent would have to move to the Responses API. I'd test it for extraction if the extracted figures come out wrong. -- **OpenAI's newer Responses API.** It is what OpenAI recommends for reasoning with tools, and newer releases of the `langchain-openai` library send `gpt-6` tool calls there by themselves. Moving would mean upgrading that library and handling a different message format. That is a bigger change, with no benefit while reasoning is off. +- **`gpt-5.6-luna`**, OpenAI's listed replacement for `gpt-4.1-nano`. It costs $0.20 per million input tokens and $1.20 per million output tokens: twice as much for input, 2.4 times as much for output. It is also 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. `gpt-6-sol` could take over with no other change, but `gpt-6.1-terra` can call tools only through the Responses API. I would 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.md) suggests `low` when a job is mostly extraction. It adds output tokens and rules out temperature 0. It also blocks the agent's tool calls on Chat Completions, so the agent would have to move to the Responses API. I'd test it for extraction if the extracted figures come out wrong. +- **The Responses API.** OpenAI recommends it for reasoning with tools. The version of the `langchain-openai` library this project pins can use it with one setting, and newer releases send `gpt-6` tool calls there by themselves. 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. **Evidence.** -- I read OpenAI's [deprecations page](https://platform.openai.com/docs/deprecations), [pricing page](https://platform.openai.com/docs/pricing), [gpt-6-luna model page](https://platform.openai.com/docs/models/gpt-6-luna) and [GPT-6 guide](https://developers.openai.com/api/docs/guides/latest-model/gpt-6-astra) on 28 November 2026. -- Offline tests check that every request carries the settings above: reasoning off, temperature 0 and, for the agent, both tools. +- I read OpenAI's [deprecations page](https://platform.openai.com/docs/deprecations), [pricing page](https://platform.openai.com/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) and [deployment checklist](https://developers.openai.com/api/docs/guides/deployment-checklist.md) on 28 November 2026. +- Offline tests check that the requests carry the settings above: reasoning off, temperature 0, sent to Chat Completions and, for the agent, both tools. **Uncertain.** -- **Extraction accuracy.** How accurately `gpt-6-luna` reads costs from these reports is measured by the extraction check against figures I read by hand. +- **Extraction accuracy.** I measure how accurately `gpt-6-luna` reads costs from these reports by comparing the costs it extracts for three projects with the figures I read from their study reports by hand. +- **Answer quality.** Whether the agent picks the right tool, writes a correct query and grounds its answer in the evidence is measured by the evaluation questions (`make eval`). - **Repeatability.** Temperature 0 makes answers less random, but not identical from run to run. -- **Token estimates.** The `tiktoken` library, which counts tokens offline, has no entry for `gpt-6-luna`. So the free estimates before a run assume the `o200k_base` encoding, which `tiktoken` uses for OpenAI's `gpt-4o`, `gpt-4.1` and `gpt-5` models. Paid runs report the token counts OpenAI measured. +- **Free estimates.** The `tiktoken` library, which counts tokens offline, has no entry for `gpt-6-luna`. So the free estimates count tokens with `o200k_base`, the way of splitting text into tokens that `tiktoken` uses for OpenAI's `gpt-4o`, `gpt-4.1` and `gpt-5` models. OpenAI also keeps the start of any prompt of 1,024 tokens or more in a cache. It bills tokens written to that cache at $0.125 per million and tokens read back from it at $0.01, against $0.10 for plain input. So the estimate before an extraction run is an upper bound that prices every prompt token at the write rate. Paid runs report the token counts OpenAI measured and price the cached tokens at their own rates. ## The agent's database queries cannot reach files -**Decision.** The agent answers questions with SQL, a language for querying tables, that it writes itself. Every such query runs against a read-only copy of the queue table, with DuckDB's external access switched off (`enable_external_access = false`). DuckDB is the database that holds the table. +**Decision.** The agent answers questions with SQL, a language for querying tables, that it writes itself. Every such query runs on a read-only connection to the queue database, with DuckDB's external access switched off (`enable_external_access = false`). DuckDB is the database that holds the table. **Why.** @@ -67,7 +71,7 @@ The model names and prices live in `src/config.py`. - The table of extracted study figures (`study_extracts`) is created along with the queue table and survives a rebuild. - Each rebuild recalculates every project's `cost_per_kw` from it. It uses 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 queue data if the study gives none. -**Why.** The extraction skips projects it has already done, so it doesn't pay twice for the same study. Without this step, rebuilding the queue table left every cost blank, and the extraction would never fill them in again. +**Why.** The extraction skips projects it has already done, so it doesn't pay twice for the same study. Without this step, rebuilding the queue table would leave every cost blank, and the extraction would never fill them in again. **Alternatives.** diff --git a/src/config.py b/src/config.py index 3fc7ec6..4f5b3d1 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 @@ -20,30 +21,67 @@ # 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. standard tier, from -# https://platform.openai.com/docs/pricing as of 28 November 2026. gpt-6-luna charges more for -# prompts over 272,000 input tokens, far beyond any request here, and bills its reasoning as -# output. the embedding model bills input only. +# https://platform.openai.com/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-6-luna": {"input": 0.10, "output": 0.50}, + "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, and it works -# like the non-reasoning models it replaced. a swapped chat model has to accept it too. +# 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: +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 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): diff --git a/src/extract.py b/src/extract.py index 4b726e7..adea371 100644 --- a/src/extract.py +++ b/src/extract.py @@ -15,11 +15,18 @@ 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 REASONING_EFFORT, require_key_for_paid_run, settings, token_cost +from src.config import ( + REASONING_EFFORT, + require_key_for_paid_run, + settings, + token_cost, + usage_cost, +) from src.ingest_pdfs import existing_queue_ids, open_store from src.ingest_queue import ( CREATE_STUDY_EXTRACTS_TABLE, @@ -196,23 +203,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]: @@ -276,8 +281,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) + """An upper bound on 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. This prices every input token 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]: @@ -316,7 +327,7 @@ def _preview_extraction(store: Chroma, pending: list[str]) -> dict[str, float]: print(prompt) print( f"{len(pending)} projects pending, estimated input tokens {input_tokens}, " - f"estimated cost ${cost:.4f}" + f"estimated cost at most ${cost:.4f}" ) return {"projects": len(pending), "input_tokens": input_tokens, "cost": cost} @@ -337,14 +348,15 @@ 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) + cost = 0.0 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) + # priced as each reply arrives, so a model with no price stops the run after one call. + cost += usage_cost(settings.extract_model, call_usage) if extract is None: # nothing is stored, so the project stays pending for the next run. continue @@ -352,12 +364,14 @@ 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) + 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 0372a5c..62bc6eb 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -20,6 +20,8 @@ def offline_and_unpaid(monkeypatch): # 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..a5563d9 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, 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: @@ -298,14 +296,12 @@ def run_eval(questions: list[EvalQuestion]) -> None: # 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 +315,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 index 478c02f..8fba1ba 100644 --- a/tests/openai_stub.py +++ b/tests/openai_stub.py @@ -8,7 +8,8 @@ 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. + Pass http_client to ChatOpenAI and its requests go here instead of over the network. Each reply + reports 50 input tokens, 40 of them written to the prompt cache, and 5 output tokens. """ def __init__(self, content: str) -> None: @@ -27,6 +28,7 @@ def _answer(self, request: httpx.Request) -> httpx.Response: "object": "chat.completion", "created": 0, "model": self.bodies[-1]["model"], + "service_tier": "default", "choices": [ { "index": 0, @@ -34,6 +36,11 @@ def _answer(self, request: httpx.Request) -> httpx.Response: "finish_reason": "stop", } ], - "usage": {"prompt_tokens": 50, "completion_tokens": 5, "total_tokens": 55}, + "usage": { + "prompt_tokens": 50, + "completion_tokens": 5, + "total_tokens": 55, + "prompt_tokens_details": {"cached_tokens": 0, "cache_write_tokens": 40}, + }, }, ) diff --git a/tests/test_config.py b/tests/test_config.py index fed964e..28546c9 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. @@ -127,8 +129,27 @@ def test_token_cost_reads_the_price_from_the_model_table() -> None: 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: + # openai's worked example: 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), + ) + expected = token_cost("gpt-6-luna", 12_000, 100, cache_read_tokens=4_000, cache_write_tokens=7_000) + assert usage_cost("gpt-6-luna", usage) == pytest.approx(expected) + 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..9211b89 100644 --- a/tests/test_eval_questions.py +++ b/tests/test_eval_questions.py @@ -60,11 +60,11 @@ 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) + assert (usage["input_tokens"], usage["output_tokens"]) == (500, 50) def test_a_question_stopped_at_the_step_limit_fails_every_check(looping_agent, capsys) -> None: diff --git a/tests/test_extract.py b/tests/test_extract.py index 6126290..a07c715 100644 --- a/tests/test_extract.py +++ b/tests/test_extract.py @@ -183,7 +183,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 @@ -191,21 +191,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: @@ -300,8 +304,9 @@ def test_extraction_asks_with_reasoning_off_for_a_reply_in_the_schema( summary = extract_all() assert summary["projects"] == 1 - # the stub reports 50 input tokens for the call, and the summary carries that measured count. + # the stub reports 50 input tokens, 40 of them written to the prompt cache, and 5 output tokens. assert summary["input_tokens"] == 50 + assert summary["cost"] == pytest.approx((10 * 0.10 + 40 * 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) From f265262bdf2146786a1a36b96f2872e6bf1b2abb Mon Sep 17 00:00:00 2001 From: Azeem Ayman <110621518+aymanazeem@users.noreply.github.com> Date: Sun, 29 Nov 2026 04:13:14 +0000 Subject: [PATCH 3/4] Pin the standard service tier and check prices before paying - Both chat requests name OpenAI's standard service tier, whose prices MODEL_PRICES lists. Left unset, a request takes the tier set in the OpenAI project, and langchain-openai renames the cache counts of priority and flex replies, so the reported cost would be wrong. - Extraction and the evaluation check the model's price before the first paid call, so an unpriced model costs nothing. Extraction prices the summed usage once, at the end. - The free extraction figure is called an estimate, not a maximum. It leaves out the schema sent with each request and assumes one prompt length for every project. - The stub reports cache reads as well as writes, the cost tests use literal dollar figures, and the evaluation test covers its cache line. - docs/decisions.md records the service tier, explains prompts and the cache, and lists switching off cache writes as an alternative. The README cites the prompt caching guide. 135 tests pass offline with an empty tiktoken cache. --- README.md | 1 + docs/decisions.md | 15 ++++++++++----- src/agent.py | 3 ++- src/config.py | 9 +++++++++ src/extract.py | 14 ++++++++------ tests/eval_questions.py | 3 ++- tests/openai_stub.py | 5 +++-- tests/test_agent.py | 1 + tests/test_config.py | 9 +++++---- tests/test_eval_questions.py | 27 ++++++++++++++++++++++++--- tests/test_extract.py | 27 +++++++++++++++++++++++++-- 11 files changed, 90 insertions(+), 24 deletions(-) diff --git a/README.md b/README.md index d182f37..dd047f8 100644 --- a/README.md +++ b/README.md @@ -168,3 +168,4 @@ make eval DRY_RUN=false - Gorman et al., grid connection barriers, Joule 2024 - OpenAI API pricing, the source of the model prices in src/config.py, https://platform.openai.com/docs/pricing - OpenAI model deprecations, the shutdown dates behind the choice of models, https://platform.openai.com/docs/deprecations +- OpenAI prompt caching guide, the source of the cache read and write rates, https://developers.openai.com/api/docs/guides/prompt-caching diff --git a/docs/decisions.md b/docs/decisions.md index b3d5a8d..fe89437 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -8,6 +8,7 @@ This file records the main choices behind the agent: what I decided, what I cons - Reasoning is switched off (`reasoning_effort` set to `none`). - The temperature, which sets how much randomness the model adds when it picks its words, is 0. - Requests go through Chat Completions, the older of OpenAI's two interfaces for sending a conversation to a model. The newer one is the Responses API. +- Requests ask for OpenAI's standard service tier. OpenAI also sells faster and slower processing at other prices, and a request that doesn't name a tier gets whichever one is set in the OpenAI account's project settings. Naming it keeps the bill at the prices `src/config.py` lists. - The study reports are embedded with `text-embedding-3-small`. Embedding turns each passage into a list of numbers, so that passages with similar meaning can be found by search. The model names and prices live in `src/config.py`. @@ -18,28 +19,32 @@ The model names and prices live in `src/config.py`. - In the extraction, it copies figures from a few passages of a study report into a fixed set of fields. A small, fast model should manage this. - As the agent, it chooses between two tools, writes the database query or the search for each, and writes an answer that cites its evidence. That includes the risk factors that could lead a project to withdraw from the queue. The evaluation questions measure how well it does this. - **It is OpenAI's replacement, and the cheapest.** OpenAI names `gpt-6-luna` as the replacement for `gpt-4.1` and `gpt-4.1-mini`, which it shuts down on 14 January 2027. It describes it as its most efficient model for focused, high-volume tasks. OpenAI charges by the token, a chunk of text of a few characters. `gpt-6-luna` costs $0.10 per million input tokens and $0.50 per million output tokens. That makes it the cheapest chat model on OpenAI's price list that isn't scheduled for retirement. -- **Reasoning off suits these jobs.** `gpt-6-luna` is a reasoning model: unless told otherwise, it thinks in hidden steps before it answers, and those steps are billed as output tokens. Copying figures and querying a table need little of that. OpenAI's advice when moving to its GPT-6 models is to keep the reasoning effort of the model being replaced, and `gpt-4.1` and `gpt-4.1-mini` don't reason at all. +- **Reasoning off suits these jobs.** `gpt-6-luna` is a reasoning model: unless told otherwise, it thinks in hidden steps before it answers, and those steps are billed as output tokens. Copying figures and querying a table need little of that. OpenAI's advice, when moving work to GPT-6 from a model that doesn't reason, such as `gpt-4.1`, is to keep reasoning off. - **It is the only setting the agent can use on Chat Completions.** With reasoning on, `gpt-6-luna` refuses tool calls there, which the agent needs, and it refuses temperature 0. **Alternatives.** - **`gpt-5.6-luna`**, OpenAI's listed replacement for `gpt-4.1-nano`. It costs $0.20 per million input tokens and $1.20 per million output tokens: twice as much for input, 2.4 times as much for output. It is also 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. `gpt-6-sol` could take over with no other change, but `gpt-6.1-terra` can call tools only through the Responses API. I would switch only if the evaluation shows the small model failing. +- **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. `gpt-6-sol` works with the same settings once its prices are added to `src/config.py`, but `gpt-6.1-terra` can call tools only through the Responses API. I would 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.md) suggests `low` when a job is mostly extraction. It adds output tokens and rules out temperature 0. It also blocks the agent's tool calls on Chat Completions, so the agent would have to move to the Responses API. I'd test it for extraction if the extracted figures come out wrong. - **The Responses API.** OpenAI recommends it for reasoning with tools. The version of the `langchain-openai` library this project pins can use it with one setting, and newer releases send `gpt-6` tool calls there by themselves. 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 cache writes for the extraction.** OpenAI caches long prompts, the text sent to the model, by default, as described under "Free estimates" below. Each extraction prompt is used once, so writing it to the cache only adds a quarter to its input price. A request can switch the writes off. I left them on, because the saving is small at this scale and it would be one more request setting to maintain and test. **Evidence.** -- I read OpenAI's [deprecations page](https://platform.openai.com/docs/deprecations), [pricing page](https://platform.openai.com/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) and [deployment checklist](https://developers.openai.com/api/docs/guides/deployment-checklist.md) on 28 November 2026. -- Offline tests check that the requests carry the settings above: reasoning off, temperature 0, sent to Chat Completions and, for the agent, both tools. +- I read OpenAI's [deprecations page](https://platform.openai.com/docs/deprecations), [pricing page](https://platform.openai.com/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.md) and [Chat Completions reference](https://platform.openai.com/docs/api-reference/chat/create) on 28 November 2026. +- Offline tests check that the requests carry the settings above: reasoning off, temperature 0, the standard service tier, sent to Chat Completions and, for the agent, both tools. **Uncertain.** - **Extraction accuracy.** I measure how accurately `gpt-6-luna` reads costs from these reports by comparing the costs it extracts for three projects with the figures I read from their study reports by hand. - **Answer quality.** Whether the agent picks the right tool, writes a correct query and grounds its answer in the evidence is measured by the evaluation questions (`make eval`). - **Repeatability.** Temperature 0 makes answers less random, but not identical from run to run. -- **Free estimates.** The `tiktoken` library, which counts tokens offline, has no entry for `gpt-6-luna`. So the free estimates count tokens with `o200k_base`, the way of splitting text into tokens that `tiktoken` uses for OpenAI's `gpt-4o`, `gpt-4.1` and `gpt-5` models. OpenAI also keeps the start of any prompt of 1,024 tokens or more in a cache. It bills tokens written to that cache at $0.125 per million and tokens read back from it at $0.01, against $0.10 for plain input. So the estimate before an extraction run is an upper bound that prices every prompt token at the write rate. Paid runs report the token counts OpenAI measured and price the cached tokens at their own rates. +- **Free estimates.** The estimate before an extraction run is rough. It counts the tokens in the first project's prompt and assumes every project's prompt is that long. It allows a fixed amount for each reply, and leaves out the description of the reply's fields that goes with each request. + - **Counting tokens.** The `tiktoken` library, which counts tokens offline, has no entry for `gpt-6-luna`. So the estimate counts them with `o200k_base`, the way of splitting text into tokens that `tiktoken` uses for OpenAI's `gpt-4o`, `gpt-4.1` and `gpt-5` models. + - **Pricing them.** OpenAI keeps the start of any prompt of 1,024 tokens or more in a cache, a short-term store that makes a repeat of the same text cheaper. It bills tokens written to the cache at $0.125 per million and tokens read back from it at $0.01, against $0.10 for plain input. The estimate prices every prompt token at the write rate, since each project's prompt is new. + - **Paid runs** report the token counts OpenAI measured, and price the cached tokens at their own rates. ## The agent's database queries cannot reach files diff --git a/src/agent.py b/src/agent.py index 49d3c24..bf648af 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 REASONING_EFFORT, settings +from src.config import REASONING_EFFORT, SERVICE_TIER, 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 @@ -86,6 +86,7 @@ def build_agent(checkpointer: BaseCheckpointSaver | None = None) -> CompiledStat api_key=settings.openai_api_key, temperature=0, 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}) diff --git a/src/config.py b/src/config.py index 4f5b3d1..b754d5e 100644 --- a/src/config.py +++ b/src/config.py @@ -36,6 +36,10 @@ # chat model has to do both with reasoning off, as gpt-6-sol does. REASONING_EFFORT = "none" +# 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" + def token_cost( model: str, @@ -66,6 +70,11 @@ def token_cost( ) / 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. diff --git a/src/extract.py b/src/extract.py index adea371..348b6e5 100644 --- a/src/extract.py +++ b/src/extract.py @@ -22,7 +22,9 @@ from src.config import ( REASONING_EFFORT, + SERVICE_TIER, require_key_for_paid_run, + require_price, settings, token_cost, usage_cost, @@ -281,10 +283,10 @@ def _extract_encoding() -> tiktoken.Encoding: def _estimate_cost(input_tokens: int, output_tokens: int) -> float: - """An upper bound on the dollar cost of these token counts at the extract model's list price. + """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. This prices every input token at that cache write rate. + 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 @@ -327,19 +329,21 @@ def _preview_extraction(store: Chroma, pending: list[str]) -> dict[str, float]: print(prompt) print( f"{len(pending)} projects pending, estimated input tokens {input_tokens}, " - f"estimated cost at most ${cost:.4f}" + f"estimated cost ${cost:.4f}" ) return {"projects": len(pending), "input_tokens": input_tokens, "cost": cost} 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.""" + require_price(settings.extract_model) # zero temperature, this is a factual extraction task and should vary as little as possible. chat = ChatOpenAI( model=settings.extract_model, api_key=settings.openai_api_key, temperature=0, 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) @@ -349,14 +353,11 @@ def _run_extraction(store: Chroma, pending: list[str]) -> dict[str, float]: extracted = 0 usage = add_usage(None, None) - cost = 0.0 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_usage = extract_for_project(chain, queue_id, prompt) usage = add_usage(usage, call_usage) - # priced as each reply arrives, so a model with no price stops the run after one call. - cost += usage_cost(settings.extract_model, call_usage) if extract is None: # nothing is stored, so the project stays pending for the next run. continue @@ -364,6 +365,7 @@ 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 = usage_cost(settings.extract_model, usage) cached = usage.get("input_token_details") or {} print( f"extracted {extracted} of {len(pending)} projects, measured input tokens " diff --git a/tests/eval_questions.py b/tests/eval_questions.py index a5563d9..b5d6b18 100644 --- a/tests/eval_questions.py +++ b/tests/eval_questions.py @@ -18,7 +18,7 @@ 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, usage_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 @@ -292,6 +292,7 @@ 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. diff --git a/tests/openai_stub.py b/tests/openai_stub.py index 8fba1ba..23d27b8 100644 --- a/tests/openai_stub.py +++ b/tests/openai_stub.py @@ -9,7 +9,8 @@ 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, 40 of them written to the prompt cache, and 5 output tokens. + 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: @@ -40,7 +41,7 @@ def _answer(self, request: httpx.Request) -> httpx.Response: "prompt_tokens": 50, "completion_tokens": 5, "total_tokens": 55, - "prompt_tokens_details": {"cached_tokens": 0, "cache_write_tokens": 40}, + "prompt_tokens_details": {"cached_tokens": 10, "cache_write_tokens": 30}, }, }, ) diff --git a/tests/test_agent.py b/tests/test_agent.py index f94d588..5f59249 100644 --- a/tests/test_agent.py +++ b/tests/test_agent.py @@ -342,4 +342,5 @@ def test_the_agent_asks_with_reasoning_off_and_both_tools_on_chat_completions(mo 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_config.py b/tests/test_config.py index 28546c9..cd7d148 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -130,8 +130,9 @@ def test_token_cost_reads_the_price_from_the_model_table() -> None: def test_token_cost_bills_cache_reads_and_writes_at_their_own_rates() -> None: - # openai's worked example: 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. + # 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) @@ -143,8 +144,8 @@ def test_usage_cost_reads_the_cache_counts_from_langchain_usage_metadata() -> No total_tokens=12_100, input_token_details=InputTokenDetails(cache_read=4_000, cache_creation=7_000), ) - expected = token_cost("gpt-6-luna", 12_000, 100, cache_read_tokens=4_000, cache_write_tokens=7_000) - assert usage_cost("gpt-6-luna", usage) == pytest.approx(expected) + # $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 diff --git a/tests/test_eval_questions.py b/tests/test_eval_questions.py index 9211b89..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)]) @@ -63,8 +72,9 @@ def test_a_question_stopped_at_the_step_limit_still_counts_its_tokens(looping_ag 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. + # 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 a07c715..aa043a3 100644 --- a/tests/test_extract.py +++ b/tests/test_extract.py @@ -304,17 +304,40 @@ def test_extraction_asks_with_reasoning_off_for_a_reply_in_the_schema( summary = extract_all() assert summary["projects"] == 1 - # the stub reports 50 input tokens, 40 of them written to the prompt cache, and 5 output tokens. + # 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 + 40 * 0.125 + 5 * 0.50) / 1_000_000) + 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 From dd22c3c43253c870b333dd4316df12db6a815f5e Mon Sep 17 00:00:00 2001 From: Azeem Ayman <110621518+aymanazeem@users.noreply.github.com> Date: Mon, 30 Nov 2026 21:43:13 +0000 Subject: [PATCH 4/4] Say plainly what hasn't been checked live, and count the schema in the estimate The README and the decision record now say that no request has gone to gpt-6-luna, so neither OpenAI accepting the settings nor the reported costs have been checked against the live API. The decision record attributes each model claim to the OpenAI page it comes from, and notes that the newer Sol models can't switch reasoning off. The three projects to check by hand are described as outside the default sample. The extraction dry run now adds the reply schema's tokens to each prompt, and a test pins the estimate's token count and its cache-write pricing. Temperature moves into src/config.py beside the other request settings. --- README.md | 4 ++-- docs/decisions.md | 21 +++++++++++---------- docs/future_work.md | 2 +- src/agent.py | 5 ++--- src/config.py | 4 ++++ src/extract.py | 12 +++++++++--- tests/test_extract.py | 19 +++++++++++++++++++ 7 files changed, 48 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index 7a1858c..f5ff471 100644 --- a/README.md +++ b/README.md @@ -113,7 +113,7 @@ Nothing calls OpenAI until you set `DRY_RUN` to false. In a dry run, `make embed - **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). -- **The paid steps haven't run yet.** Embedding the reports, extracting their costs and the evaluation all call OpenAI's paid models. So I haven't yet measured how accurately the model extracts costs, how well the agent answers, or what either costs. The agent and the extraction use `gpt-6-luna` ([why](docs/decisions.md#the-models-gpt-6-luna-with-reasoning-off)). The offline tests check the requests the code sends, not OpenAI's replies. +- **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%. @@ -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-6-luna`, with its reasoning 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. +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 diff --git a/docs/decisions.md b/docs/decisions.md index ffbcef1..28ac704 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -30,32 +30,33 @@ This file records the main choices behind the agent: what I decided, what I cons - 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, 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. +- 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 advises keeping reasoning off when moving work from a model that doesn't reason, such as `gpt-4.1-mini`. -- **It is the only setting the agent can use on Chat Completions.** With reasoning on, `gpt-6-luna` refuses tool calls there, which the agent needs, and refuses temperature 0. +- **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. `gpt-6-sol` works with the same settings once its prices are added to `src/config.py`, but `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.md) 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 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. +- **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 add less than a cent. +- **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.md) and [Chat Completions reference](https://platform.openai.com/docs/api-reference/chat/create) on 28 November 2026. +- 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.** -- **How well it works.** I haven't yet run the paid steps with `gpt-6-luna`. I'll check the extraction by comparing the costs it extracts for three projects (AC2-093, AF1-236 and AF2-353) with the figures I read from their reports 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. +- **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 allows a fixed amount for each reply, and leaves out the description of the reply's fields that goes with each request. 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. +- **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 diff --git a/docs/future_work.md b/docs/future_work.md index 1e54dd5..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 -- **Run the paid steps.** Embed the reports, extract their costs, check three of them (AC2-093, AF1-236 and AF2-353) against the figures I read from their reports by hand, and run the evaluation. This needs OpenAI credits. +- **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 657e9fe..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 REASONING_EFFORT, SERVICE_TIER, 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,11 +83,10 @@ 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, + temperature=TEMPERATURE, reasoning_effort=REASONING_EFFORT, service_tier=SERVICE_TIER, ) diff --git a/src/config.py b/src/config.py index d413b82..936608d 100644 --- a/src/config.py +++ b/src/config.py @@ -40,6 +40,10 @@ # 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, diff --git a/src/extract.py b/src/extract.py index 348b6e5..2c9c51d 100644 --- a/src/extract.py +++ b/src/extract.py @@ -8,6 +8,7 @@ """ import argparse +import json from pathlib import Path import duckdb @@ -23,6 +24,7 @@ from src.config import ( REASONING_EFFORT, SERVICE_TIER, + TEMPERATURE, require_key_for_paid_run, require_price, settings, @@ -123,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. @@ -320,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) @@ -337,11 +344,10 @@ 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.""" require_price(settings.extract_model) - # zero temperature, this is a factual extraction task and should vary as little as possible. chat = ChatOpenAI( model=settings.extract_model, api_key=settings.openai_api_key, - temperature=0, + temperature=TEMPERATURE, reasoning_effort=REASONING_EFFORT, service_tier=SERVICE_TIER, ) diff --git a/tests/test_extract.py b/tests/test_extract.py index aa043a3..9ba8a11 100644 --- a/tests/test_extract.py +++ b/tests/test_extract.py @@ -1,8 +1,10 @@ +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 @@ -12,6 +14,7 @@ from src.config import settings from src.extract import ( + ESTIMATED_OUTPUT_TOKENS, StudyExtract, already_extracted_queue_ids, build_prompt, @@ -260,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: