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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,11 +85,12 @@ DRY_RUN=false python -m src.cli chat

`make app` opens a chat page at http://127.0.0.1:8000. It listens only on your computer, and each browser tab keeps its own conversation. Press Ctrl+C in the terminal to stop it. It stops once any answer in progress has finished.

**Adding a report.** To add another project's report, save it as `data/raw/pdfs/<queue ID>.pdf`, with the queue ID written exactly as in the panel, and run `make embed` again. It skips reports it has already embedded. For example, for AF1-236:
**Adding a report.** To add another project's report, save it as `data/raw/pdfs/<queue ID>.pdf`, with the queue ID written exactly as in the panel. Then run `make embed` again, and `make extract` to read its costs. Both skip reports they have already done. For example, for AF1-236:

```
curl -fo data/raw/pdfs/AF1-236.pdf https://www.pjm.com/pjmfiles/pub/planning/project-queues/impact_studies/af1236_imp.pdf
make embed DRY_RUN=false
make extract DRY_RUN=false
```

**PJM's live queue.** To build the panel from PJM's live queue instead of Berkeley Lab's data, put a free PJM Data Miner API key in `PJM_API_KEY` in `.env`, then run `python -m src.ingest_queue --source gridstatus`. I haven't tested this route.
Expand All @@ -106,7 +107,7 @@ Nothing calls OpenAI until you set `DRY_RUN` to false. In a dry run, `make embed

`make test` runs the offline tests. They use small sample files in `data/fixtures/`, and stand-ins for the model and the network, so they need no key, no network and no downloads. GitHub runs them on Python 3.11 and 3.14 for every pull request.

`make eval DRY_RUN=false` puts six questions to the real agent. It prints each answer, the result of each check, and the tokens and cost. The checks test, for example, that the agent used the right tool, stated the right count, and didn't present one line of a report as a project's total. Some checks compare answers with the extracted costs. With no extracted costs, two of them are skipped, and two others pass whatever the answer says, because there is nothing to compare with. One question is about AF1-236, whose report isn't in the default sample; the Quickstart shows how to add it. I haven't run the evaluation yet, because it needs the paid steps first.
`make eval DRY_RUN=false` puts six questions to the real agent. It prints each answer, the result of each check, and the tokens and cost. The checks test, for example, that the agent used the right tool, stated the right count, and didn't present one line of a report as a project's total. Four checks compare answers with the extracted costs. Until there are costs to compare with, the evaluation skips these checks and says so, rather than passing them. One of them is about AF1-236, whose report isn't in the default sample, so it stays skipped until you add that report and extract its costs (see the Quickstart). The wind question's check follows the panel too: until a wind project's extracted cost is above $300 per kW, it expects the answer to say there is none. I haven't run the evaluation yet, because it needs the paid steps first.

## Limitations

Expand Down
1 change: 0 additions & 1 deletion docs/future_work.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ Changes I plan or propose, starting with the most urgent.

- **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.

## Method

Expand Down
78 changes: 61 additions & 17 deletions tests/eval_questions.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
Run this by hand, it is not part of the automatic suite because it calls the api. Each question
records what a good answer should contain, checked with a plain assertion where that is honest
and left for the reader to judge where the question is open ended. Ground truth for the checks
comes from the panel itself, so the eval tracks whatever has been extracted. Set DRY_RUN to
comes from the panel itself, so the eval tracks whatever has been extracted, and a check whose
figures have not been extracted yet is reported as skipped rather than run. Set DRY_RUN to
false and provide a key, then run python -m tests.eval_questions. In dry run it walks the same
questions against the canned answers for free, which confirms the wiring without spending.
"""
Expand All @@ -25,18 +26,32 @@
# a check reads the final answer and the tools that ran, and returns whether it held.
Check = Callable[[str, list[str]], bool]

NO_COSTS = "no project has an extracted cost above zero yet"
COSTLY_WIND_LABEL = "names each wind project above 300 dollars per kW"


@dataclass
class Skip:
"""Stands in for a check whose figures the panel doesn't have yet, so it can't pass by default."""

reason: str


@dataclass
class EvalQuestion:
prompt: str
checks: list[tuple[str, Check]]
checks: list[tuple[str, Check | Skip]]
note: str = ""


def _mentions(text: str) -> Check:
return lambda answer, tools: text.lower() in answer.lower()


def _mentions_all(texts: list[str]) -> Check:
return lambda answer, tools: all(text.lower() in answer.lower() for text in texts)


def _states_number(value: int) -> Check:
# models write large counts with thousands separators, so strip them before matching.
return lambda answer, tools: str(value) in answer.replace(",", "")
Expand Down Expand Up @@ -145,6 +160,13 @@ def _costed_ranking() -> list[str]:
return [row["queue_id"] for row in rows]


def _costly_wind() -> list[str]:
rows = query_projects(
"SELECT queue_id FROM projects WHERE fuel_type = 'wind' AND cost_per_kw > 300 ORDER BY queue_id"
)
return [row["queue_id"] for row in rows]


def _study_total_usd(queue_id: str) -> float | None:
"""The extracted network upgrade total for one project, used as the panel truth for grounding."""
rows = query_projects(
Expand All @@ -158,27 +180,36 @@ def build_questions() -> list[EvalQuestion]:
"""Assemble the question set, wiring each check to the current panel figures."""
solar_count, solar_mw = _withdrawn_solar()
ranking = _costed_ranking()
top = ranking[0] if ranking else ""
top = ranking[0] if ranking else None
af1_total = _study_total_usd("AF1-236")
top_total = _study_total_usd(top) if top else None
costly_wind = _costly_wind()

document_checks = [
("routes to search_studies", _used_tool("search_studies")),
("names the project", _mentions("AF1-236")),
("speaks to upgrades", _mentions("upgrade")),
(
"cites the upgrade total, not a component",
_cites_total_near(af1_total) if af1_total is not None
else Skip("AF1-236 has no extracted cost yet"),
),
]
if af1_total is not None:
document_checks.append(("cites the upgrade total, not a component", _cites_total_near(af1_total)))

combined_checks = [
("reads the panel", _used_tool("query_queue")),
("reads the studies", _used_tool("search_studies")),
("names the top project", _mentions(top)),
("names the top project", _mentions(top) if top else Skip(NO_COSTS)),
(
"does not pass a component off as the total",
_no_wrong_total(top_total) if top_total is not None else Skip(NO_COSTS),
),
]
if top_total is not None:
combined_checks.append(
("does not pass a component off as the total", _no_wrong_total(top_total))
)

wind_check = (
(COSTLY_WIND_LABEL, _mentions_all(costly_wind)) if costly_wind
else ("admits there is no such evidence", _admits_no_evidence())
)

return [
EvalQuestion(
Expand Down Expand Up @@ -225,11 +256,13 @@ def build_questions() -> list[EvalQuestion]:
"Which wind projects in the panel have a known network upgrade cost per kW above "
"300, and what drives it?"
),
checks=[
("reads the panel", _used_tool("query_queue")),
("admits there is no such evidence", _admits_no_evidence()),
],
note="no wind project has an extracted cost, so a good answer says so rather than inventing one.",
checks=[("reads the panel", _used_tool("query_queue")), wind_check],
note=(
f"panel truth, wind projects above 300 dollars per kW are {costly_wind}."
if costly_wind
else "no wind project has an extracted cost above 300 dollars per kW, so a good answer says "
"so rather than inventing one."
),
),
EvalQuestion(
prompt=(
Expand All @@ -238,7 +271,7 @@ def build_questions() -> list[EvalQuestion]:
),
checks=[
("reads the panel", _used_tool("query_queue")),
("lists them in cost order", _lists_in_order(ranking)),
("lists them in cost order", _lists_in_order(ranking) if ranking else Skip(NO_COSTS)),
],
note=f"panel truth, cost order is {ranking or 'none yet'}.",
),
Expand Down Expand Up @@ -288,6 +321,12 @@ def run_wiring_pass(questions: list[EvalQuestion]) -> None:
print(f"[{index}] {question.prompt}")
print(f" {ask(question.prompt)}\n")
print(f"{len(questions)} questions wired. checks and cost print only in a real run.")
skipped = sum(isinstance(check, Skip) for question in questions for _, check in question.checks)
if skipped:
print(
f"{skipped} {'check' if skipped == 1 else 'checks'} would be skipped, with nothing in "
"the panel to compare with yet."
)


def run_eval(questions: list[EvalQuestion]) -> None:
Expand All @@ -300,6 +339,7 @@ def run_eval(questions: list[EvalQuestion]) -> None:
total = add_usage(None, None)
passed = 0
total_checks = 0
skipped = 0
for index, question in enumerate(questions, start=1):
answer, tools, usage = answer_question(agent, question.prompt)
total = add_usage(total, usage)
Expand All @@ -310,6 +350,10 @@ def run_eval(questions: list[EvalQuestion]) -> None:
print(f" note, {question.note}")
print(f" answer, {STEP_LIMIT_REPLY if answer is None else answer}")
for label, check in question.checks:
if isinstance(check, Skip):
skipped += 1
print(f" [skip] {label}, {check.reason}")
continue
# a stopped question has no answer, so even a check that something is absent fails.
ok = answer is not None and check(answer, tools)
passed += int(ok)
Expand All @@ -322,7 +366,7 @@ def run_eval(questions: list[EvalQuestion]) -> None:
)

cached = total.get("input_token_details") or {}
print(f"checks passed {passed} of {total_checks}")
print(f"checks passed {passed} of {total_checks}" + (f", {skipped} skipped" if skipped else ""))
print(
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']}, "
Expand Down
88 changes: 87 additions & 1 deletion tests/test_eval_questions.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,16 @@
import tests.eval_questions as eval_questions
from src.agent import STEP_LIMIT_REPLY, build_agent
from src.config import settings
from src.extract import StudyExtract, write_extract
from src.ingest_queue import build_projects_table, normalize_frame, read_fixture

COST_CHECKS = {
"cites the upgrade total, not a component",
"names the top project",
"does not pass a component off as the total",
"lists them in cost order",
}


class MeteredLoopingModel(BaseChatModel):
"""Always calls query_queue and reports the same usage for every reply.
Expand Down Expand Up @@ -49,9 +57,87 @@ def panel(tmp_path, monkeypatch):
build_projects_table(normalize_frame(read_fixture()), settings.queue_db_path)


def _all_checks() -> list[tuple[str, object]]:
return [pair for question in eval_questions.build_questions() for pair in question.checks]


def test_the_dry_run_walks_every_question_on_a_panel_with_no_extractions(panel, capsys) -> None:
eval_questions.main()
assert f"{len(eval_questions.build_questions())} questions wired" in capsys.readouterr().out
output = capsys.readouterr().out
assert f"{len(eval_questions.build_questions())} questions wired" in output
assert f"{len(COST_CHECKS)} checks would be skipped" in output


def test_with_no_extracted_costs_the_cost_checks_are_skipped_not_passed(panel) -> None:
checks = _all_checks()
skipped = {label for label, check in checks if isinstance(check, eval_questions.Skip)}
assert skipped == COST_CHECKS
assert "admits there is no such evidence" in dict(checks)


def test_with_extracted_costs_the_cost_checks_compare_with_the_panel(panel) -> None:
# z002 is a wind project in the sample panel, ac2115 a solar one: 400 and 100 dollars per kW.
write_extract(StudyExtract(queue_id="z002", studied_mw=200, total_network_upgrade_cost_usd=80e6))
write_extract(StudyExtract(queue_id="ac2115", studied_mw=150, total_network_upgrade_cost_usd=15e6))
checks = _all_checks()
skipped = {label for label, check in checks if isinstance(check, eval_questions.Skip)}
# no AF1-236 extract is written, so its check still has nothing to compare with.
assert skipped == {"cites the upgrade total, not a component"}

labelled = dict(checks)
assert labelled["lists them in cost order"]("z002 at 400, then ac2115 at 100", [])
assert not labelled["lists them in cost order"]("ac2115 at 100, then z002 at 400", [])
assert labelled["names the top project"]("z002 costs the most", [])
assert not labelled["names the top project"]("ac2115 costs the most", [])
# the top project's total is z002's $80 million, not ac2115's $15 million.
assert labelled["does not pass a component off as the total"](
"z002's total network upgrade cost is $80 million", []
)
assert not labelled["does not pass a component off as the total"](
"z002's total network upgrade cost is $2 million", []
)
# a wind project above 300 dollars per kW now exists, so a good answer names it.
assert "admits there is no such evidence" not in labelled
assert labelled[eval_questions.COSTLY_WIND_LABEL]("z002, at 400 dollars per kW", [])
assert not labelled[eval_questions.COSTLY_WIND_LABEL]("no wind project costs that much", [])


def test_the_wind_check_expects_only_wind_projects(panel) -> None:
# z006 is a gas project above 300 dollars per kW, so the answer needn't name it.
write_extract(StudyExtract(queue_id="z002", studied_mw=200, total_network_upgrade_cost_usd=80e6))
write_extract(StudyExtract(queue_id="z006", studied_mw=400, total_network_upgrade_cost_usd=200e6))
check = dict(_all_checks())[eval_questions.COSTLY_WIND_LABEL]
assert check("z002, at 400 dollars per kW", [])


def test_once_af1_236_has_an_extracted_total_its_check_compares_with_it(panel) -> None:
write_extract(
StudyExtract(queue_id="AF1-236", studied_mw=1210, total_network_upgrade_cost_usd=473_529_878)
)
check = dict(_all_checks())["cites the upgrade total, not a component"]
assert not isinstance(check, eval_questions.Skip)
assert check("the total network upgrade cost is $473.5 million", [])
assert not check("the total network upgrade cost is $12 million", [])


def test_the_dry_run_counts_one_skipped_check_in_the_singular(panel, capsys) -> None:
write_extract(StudyExtract(queue_id="z002", studied_mw=200, total_network_upgrade_cost_usd=80e6))
eval_questions.main()
assert "1 check would be skipped" in capsys.readouterr().out


def test_a_skipped_check_is_reported_and_left_out_of_the_count(looping_agent, capsys) -> None:
question = eval_questions.EvalQuestion(
prompt="loop",
checks=[
("used the structured tool", eval_questions._used_tool("query_queue")),
("names the top project", eval_questions.Skip(eval_questions.NO_COSTS)),
],
)
eval_questions.run_eval([question])
output = capsys.readouterr().out
assert f"[skip] names the top project, {eval_questions.NO_COSTS}" in output
assert "checks passed 0 of 1, 1 skipped" in output


def test_the_eval_without_a_panel_exits_with_a_plain_message(tmp_path, monkeypatch) -> None:
Expand Down