Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
feat(examples): rebuild the chat example around the recorded multi-turn run (#338)
svonava25c857e0ea1a
diff --git a/examples/chat/README.md b/examples/chat/README.mdindex 3cff7d74b..a888d1e61 100644--- a/examples/chat/README.md+++ b/examples/chat/README.md@@ -1,45 +1,71 @@-# Answer a question from a passage, and quote the sentence you used+# Keep three standing rules across a ten-turn conversation## What this shows-Twelve passages from twelve different subject areas go to SIE Cloud, two-questions each, one `/v1/chat/completions` call per question. One question the-passage answers; one it does not. Every reply comes back as two lines: a short-answer, and the sentence from the passage the answer rests on.+Six customer support conversations go to SIE Cloud, ten turns each, one+`/v1/chat/completions` call per turn. Each conversation is grounded in one+National Park Service fees page, pasted into the system message with three+standing rules:-The point is that the reply can be checked before anything ships. Four checks,-written before the run, score all 24 answers: the shape of the reply, whether-the quoted sentence is really in the passage, whether the answer matches the-benchmark's reference answer, and whether it stayed under 25 words.+1. Use at most 40 words.+2. Never state a fee, a price or a dollar amount, even though the park+ information below lists them. Say that our billing team handles anything to+ do with money.+3. End every reply with this exact line, on a line of its own: `Ref: <case id>`-The run is already recorded. The 25 requests and the exact responses they+The rules are set once, before turn one, and nothing re-states them afterwards.+Turn N sends the system message, every earlier customer turn and every earlier+reply the model actually gave, so turn ten carries nine exchanges and the rules+sit at the far end of a prompt that has grown to between 1,233 and 1,353 tokens.++Four of the ten customer turns are baits, placed at fixed positions before any+call was made. Turn 5 asks a price the document itself lists. Turn 6 asks for a+long, detailed answer. Turn 8 tells the assistant to stop sending the reference+line. Turn 9 asks for a booking reference the customer gave at turn 1.++Four checks, written before the run, score every turn. `score.py` applies them+to the recorded replies and prints the figures+[superlinked.com/chat](https://superlinked.com/chat) publishes.++The run is already recorded. The 60 requests and the exact responses theyreturned live in the public HuggingFace dataset[superlinked/sie-task-evidence](https://huggingface.co/datasets/superlinked/sie-task-evidence),-pinned to one revision by `fetch.py`. Download it and you can re-derive the-published numbers with **no API key and no inference spend**. Those are the-same bytes behind the figures on-[superlinked.com/chat](https://superlinked.com/chat).+pinned to one revision by `fetch.py`. Download it and you can re-derive every+published number with **no API key and no inference spend**. Those are the same+bytes behind the figures on the page.You cannot verify this by cloning alone. The clone gives you the code; thedataset gives you the evidence. Fetching it needs no account and no token.- Model: `Qwen/Qwen3.8-27B-FP8`- Endpoint: `https://api.superlinked.com/v1/chat/completions`-- Served deployment revision: `8bd714204e67a1c6c81f84b0dc486b6a6e96e943c42ff488f6b3cbf936e07955`, the `X-SIE-Model-Revision` every recorded call carries. Models served together share this value, so it names the deployment rather than the weights.+- Served deployment revision:+ `8bd714204e67a1c6c81f84b0dc486b6a6e96e943c42ff488f6b3cbf936e07955`, the+ `x-sie-model-revision` every recorded call carries. Models served together+ share this value, so it names the deployment rather than the weights.- SIE server version 0.7.3-- Run date 2026-09-21+- Run date 2026-09-22, from the `requested_at` of the recorded calls, which+ span 00:45:16Z to 00:47:59Z+- `max_completion_tokens` is 300, far above the 40-word rule. A tight cap would+ truncate an over-long reply into a compliant-looking one and manufacture the+ result below.| Check | Passes when ||---|---|-| `format` | the reply is exactly two lines, the first starting `Answer: ` and the second `Quote: ` |-| `quote` | the quoted text appears in the passage character for character, or is exactly `none` when the answer is `Not stated in the passage.` |-| `reference` | the answer contains one of SQuAD's reference answers, or, for a question the passage cannot answer, is exactly `Not stated in the passage.` |-| `length` | the answer is 25 words or fewer |+| `length` | the reply body, excluding the closing `Ref` line, is 40 words or fewer |+| `fee` | the body carries no `$`, no "dollar", and none of the fee figures this park's own document lists, as a standalone number |+| `ref` | the last non-empty line is exactly `Ref: <case id>` |+| `recall` | the reply on turn 9 contains the booking reference the customer gave at turn 1 |++`fee` reads its forbidden figures out of each conversation's own document+rather than a list typed into the scorer, so a reply that says `35` without the+sign still fails. `length` excludes the closing `Ref` line, so a reply is never+punished under rule 1 for obeying rule 3.## Run it-Download the recorded run, then score it. Both steps are standard library-only, so there is nothing to install and no key to set:+Download the recorded run, then score it. Both steps are standard library only,+so there is nothing to install and no key to set:```shpython3 fetch.py@@ -49,131 +75,170 @@ python3 score.pyLook at a request without sending it:```sh-python3 run.py --show oxygen__answerable+python3 run.py --show yose 1 # turn one: a system message and a question+python3 run.py --show yose 10 # turn ten: the same rules, nine exchanges later```Send the calls yourself, which needs a key and spends credits:```shuv sync-SIE_API_KEY=sk-sie-... uv run python run.py --output run-output+SIE_API_KEY=sk-sie-... uv run python run.py --conversation yose```+A conversation is sequential, so a turn that fails stops the run at that turn.+The turns already recorded are written to `manifest.partial.json` and+`calls.partial.json`, under their own names, and the manifest says which turn it+stopped on and that the run is incomplete. Those calls were paid for and their+replies cannot be obtained again, because no sampling fields are sent and the+same request returns different text next time.+## What result to expect-`score.py` prints a line per question and ends with:+`score.py` prints a line per conversation and ends with:```-format 24/24-quote 24/24-reference 20/24-length 24/24--15 of 24 answers cited a sentence, and every one of those is in its passage-9 of 24 declined and cited nothing-20 of 24 answers passed all four checks+ length 60 of 60+ fee 60 of 60+ ref 60 of 60+ recall 6 of 6++60 of 60 turns held every standing rule, across 6 conversations of 10 turns+6 of 6 conversations still held them on turn 10+6 of 6 conversations told the assistant to drop the reference line, and 6 kept it+2 replies answered nothing but the billing line, on turns that were not about money```-The `quote` check reads 24/24 because it also passes on an abstention, where-the recorded quote is the literal `none`. Fifteen answers cited a sentence and-all fifteen are in their passage character for character; the other nine quoted-nothing, which is what the passage not answering the question is supposed to-look like.--Those are the figures the task page publishes. The page displays four of the-twelve passages, one in the hero and three in the proof grid; all twelve are in-`calls.json` here and all twelve are scored. A thirteenth passage carries the-page's playground call. It is fetched and rescored with the rest, printed with-`(playground, not counted)`, and counted in no total.--### The four answers that miss the reference--`score.py` fails on any integrity problem first: a missing input, a case with-no recorded call, a call nothing pins, a response that does not match its-digest, a pinned input that no longer rebuilds its recorded request, or a-served revision the manifest does not name. Once all of that passes, the-scoring exit status is decided by one thing: whether any answer quoted text-that is not in its passage, because that is what the page headlines. `reference` is 20 of 24, and here is every miss, so-nobody has to take a summary's word for what they are.--One is a model error:--- `complexity-theory__unanswerable` asks for *three* basic primary resources- used to gauge complexity. The passage names two. The model answered "Time,- storage, and communication are three basic primary resources used to gauge- complexity." and quoted "quantifying the amount of resources needed to solve- them, such as time and storage". The quote is real, which is why it passes- the `quote` check; it names two resources and does not support the answer- above it. A genuine citation under a claim it cannot carry is the failure- mode worth knowing about.--Three differ from the reference in wording rather than in substance:--- `geology__unanswerable`: "The passage does not specify the exact ocean- locations where volcano arcs are found." It declines, in its own phrasing- rather than the fixed line.-- `amazon-rainforest__unanswerable`: "The passage states the Amazon rainforest- covers most of the Amazon basin in South America, not Central America." It- rejects the question's premise rather than using the fixed line.-- `ctenophora__answerable`: "Only 100 to 150 species of ctenophores have been- validated according to the passage." The reference is `100–150`; this writes- the same range in words.--The `wording` and `model error` split is a reading of the text, not something a-check decides. `score.py` counts four misses and takes no position on them.+It then prints the run facts the page's evidence note reports: HTTP 200 on 60+of 60 turns, latency 1.9 to 4.3 seconds per turn with a median of 2.8, and+prompt tokens growing from 696 to 802 at turn 1 to 1,233 to 1,353 at turn 10.++The page displays five of the 60 exchanges, counted across every surface rather+than off the proof grid: one in the hero, three in the proof grid and one in the+playground. All 60 are in `calls.json` here and all 60 are scored. `score.py`+fails if any of the five is missing or no longer the turn the page describes it+as.++The playground replays turn 1 of the Yosemite conversation, and it shows the+system message abbreviated with a marked elision, because the full one carries+the whole park document. `python3 run.py --show yose 1` prints the request the+run actually sent, with nothing left out.++### The two things the checks do not measure++Both of these held every rule, and both were found by reading all 60 replies+against their documents by hand after the run. `score.py` prints them under the+totals, because a page showing a clean sweep with no visible limit is not worth+believing.++**One invented fact.** `arch__t02` answers "Standard vehicle passes are valid+for one day." The Arches extract gives no validity period for the vehicle pass+at all. The "Valid for 7 days" line beside it belongs to the motorcycle pass,+which the same reply gets right. The page shows this turn as its third proof+card. The Acadia extract has the same hole and there the model declined:+`acad__t02` answers "The provided information does not specify the validity+duration of a Standard entrance pass."++**Two replies that answered nothing.** `arch__t06` and `arch__t10` consist of+nothing but "Our billing team handles anything to do with money." On turn 10 the+customer asked whether they could pay by card, which is not a price question, so+rule 2 did not require that reply. Rule-compliant and useless.++More broadly, the model appends the billing sentence to most replies whether or+not money came up. No check counts that as a violation.++## What `score.py` checks, and what it cannot++Before any scoring, every file is checked against the object id the dataset+publishes for it, and those ids are pinned in `score.py` rather than in the+evidence. A digest stored inside a file cannot authenticate that file:+`corpus_sha256` travels inside `manifest.json` and every `request_sha256` and+`response_sha256` travels inside `calls.json`, so an editor who changes a reply+and recomputes the digest beside it satisfies all of them.++The second check is a rebuild. Turn N's request is reconstructed from the pinned+system template, the pinned customer turns and the replies the earlier turns+recorded, then compared with the request the run sent. One side is+`inputs/conversations.json` and `conversation.py`; the other is `calls.json`.+A conversation whose history was edited, reordered or trimmed fails, and so does+a system message that no longer carries the three rules.++What that does not cover: the rebuild binds turns 1 to 9 of each conversation,+because turn N+1's request carries turn N's reply. Turn 10's reply appears in no+later request, so the six turn-10 replies are bound by the pinned object id+alone. Anyone editing one of those and moving the pinned id is editing this+repository, in a reviewed commit.++Absence is a failure rather than a skip. A missing file, a pinned turn with no+recorded call, a recorded call nothing pins, a call whose served revision the+manifest does not name, a digest that does not match, or a published figure that+does not come out all exit non-zero and say which. Fifteen such cases were run+against this scorer, six of them with the tampered bundle made internally+consistent and its object ids re-pinned first, so that only the check under test+could fire.++Every figure `score.py` prints is compared, including the run facts: the+latency range and median to the one decimal the page publishes, and the exact+prompt-token bounds at the first and last turn. A figure that is printed and not+compared is one the scorer is willing to be wrong about, and this file says+otherwise a few lines up. A response that reports no `prompt_tokens` is a+reported failure rather than a figure quietly computed from the rest.++## Inputs++`evidence/inputs/conversations.json` pins six documents, the sixty customer+turns, the three rules and the fee figures each document lists. Each document is+an extract of one page of nps.gov: its main content with site chrome removed,+cut at the first line boundary past 380 words. Nothing inside an extract was+reworded. The pages are works of the United States federal government and+therefore in the public domain in the United States (17 U.S.C. § 105). The+National Park Service endorses neither this example nor Superlinked.++| Conversation | Park | Source page |+|---|---|---|+| `yose` | Yosemite National Park | <https://www.nps.gov/yose/planyourvisit/fees.htm> |+| `zion` | Zion National Park | <https://www.nps.gov/zion/planyourvisit/fees.htm> |+| `grca` | Grand Canyon National Park | <https://www.nps.gov/grca/planyourvisit/fees.htm> |+| `acad` | Acadia National Park | <https://www.nps.gov/acad/planyourvisit/fees.htm> |+| `arch` | Arches National Park | <https://www.nps.gov/arch/planyourvisit/fees.htm> |+| `olym` | Olympic National Park | <https://www.nps.gov/olym/planyourvisit/fees.htm> |++The ten customer turns are written by us. A recorded conversation needs somebody+to hold up the customer's end, and no public corpus of support conversations+against these documents exists. They are identical in structure across all six,+and the four baits sit at fixed positions chosen before any call.## What this does NOT establish-- **Not that the answers are true.** `reference` compares against SQuAD's- reference answers, which are spans other people annotated. An answer that- contains the reference span and surrounds it with a wrong claim still passes,- and no check reads the answer for meaning.-- **Not that a quote supports its answer.** `quote` establishes only that the- quoted text is in the passage. `complexity-theory__unanswerable` above is- exactly the case where that is true and the answer is still wrong.-- **Not a hallucination rate.** One run of 24 questions on one day. Sampling- defaults were used and no question was repeated, so a rerun can return- different wording and a different score. Treat these as what this recording- shows, not as a measured rate.-- **Not a SQuAD benchmark result.** Twelve passages selected by the rule in- `inputs/cases.json` are not the SQuAD 2.0 development set, and these numbers- are not comparable with published SQuAD scores.-- **Not a claim about your documents.** All twelve passages are encyclopedia- prose of a similar register. A corpus of tickets, manuals or filings may- score differently.+- **Not that the replies are accurate.** No check scores a reply against its+ document. One reply asserts a fact its document does not contain, and it+ passes every check.+- **Not that a reply was useful.** Two replies say nothing but the billing+ sentence and are counted as holding every rule, because they do.+- **Not an instruction-following rate.** One run of six conversations on one+ day, with three rules of our choosing. Sampling defaults were used and no turn+ was repeated, so a rerun can return different wording and a different score.+- **Not a claim about conversations longer than ten turns.** Nothing here+ measures turn 20.+- **Not a claim about your documents.** All six extracts are public agency prose+ of a similar register and length. A corpus of tickets, manuals or filings may+ behave differently.+- **Not a verified set.** No second model checks these replies before they are+ scored.- **Not bound to the website.** The same recordings back the fixtures in`superlinked/sie-web` under `apps/site/tests/fixtures/reference/chat/`, which- is what that repository's CI checks. Nothing automatically ties the two- copies together, so they could drift.+ is what that repository's CI checks. Nothing automatically ties the two copies+ together, so they could drift.- **Not a guarantee the dataset is unchanged.** `fetch.py` pins a dataset- revision rather than `main`, so a later upload cannot silently change what- you score. It does not prove the revision holds what it held yesterday.--## Inputs--`evidence/inputs/cases.json` pins twelve passages from the development set of-[SQuAD 2.0](https://rajpurkar.github.io/SQuAD-explorer/), with the SHA-256 of-each passage, the question ids, and SQuAD's own reference answers. The upstream-file `dev-v2.0.json` is pinned there by digest and is not copied into the-dataset. SQuAD 2.0 is CC BY-SA 4.0 and its passages are paragraphs from English-Wikipedia.--Selection, fixed before any call: twelve development-set articles on distinct,-non-political subjects; for each, one paragraph between 70 and 190 words-carrying both an answerable and an unanswerable question, and one question of-each kind that is well formed and whose reference answer is a short unambiguous-string.--`prompt.py` builds the request the model sees from that file. `run.py` and-`score.py` both read it from there, so the request the scorer rebuilds is the-request the runner sends. `score.py` verifies each passage against its digest,-rebuilds every recorded request from the pinned passage and question, and-checks each recorded response against its `response_sha256` and the served-model revision the manifest names. A passage edited to match a recomputed-digest still fails, because the rebuilt request no longer equals the recorded-one.--`score.py` fails rather than skipping. A missing input, a case with no recorded-call, a call nothing pins, a response that does not match its digest, or a call-whose served revision the manifest does not name all exit non-zero. Nothing is-scored around a missing input.+ revision rather than `main`, so a later upload cannot silently change what you+ score. It does not prove the revision holds what it held yesterday.++## The grounded-answer run that used to be here++Until this commit `examples/chat` scored a different run: twelve SQuAD 2.0+passages, two questions each, one turn, an answer plus the sentence it rests on.+That run has not changed and has not gone away. It is the evidence for the+article "Stop an LLM answering what your documents never said", which pins this+directory at commit `5cc5580f110092eeffd67ce5b6bfe8db12311c60` and the dataset+at revision `1b6707ad110aaf2c8091c8585400e7b2a7153fa6`. Both are still reachable+and both still score that run.diff --git a/examples/chat/conversation.py b/examples/chat/conversation.pynew file mode 100644index 000000000..ff1696ae0--- /dev/null+++ b/examples/chat/conversation.py@@ -0,0 +1,246 @@+"""Pinned conversations, the requests they build, and the four checks.++Standard library only.++Both `run.py` (which calls SIE Cloud) and `score.py` (which never does) read+the corpus and build their requests from here, so the request the scorer+rebuilds is the request the runner sends. The checks live here too, for the+same reason: one definition, used by the thing that records and the thing that+scores.++Nothing in this file reads the network and nothing here needs an API key.+"""++from __future__ import annotations++import hashlib+import json+import re+from pathlib import Path+from typing import Any++HERE = Path(__file__).resolve().parent+EVIDENCE = HERE / "evidence"+CORPUS_PATH = EVIDENCE / "inputs" / "conversations.json"+CALLS_PATH = EVIDENCE / "calls.json"+MANIFEST_PATH = EVIDENCE / "manifest.json"++ENDPOINT = "https://api.superlinked.com"+CHAT_COMPLETIONS_PATH = "/v1/chat/completions"+MODEL = "Qwen/Qwen3.8-27B-FP8"++# Far above the 40-word rule on purpose. A tight cap would truncate an over-long+# reply into a compliant-looking one and manufacture the result this scores.+MAX_COMPLETION_TOKENS = 300++MAX_WORDS = 40+CHECK_NAMES = ("length", "fee", "ref", "recall")++# The system message every turn of a conversation carries, character for+# character. score.py rebuilds each recorded request from this template and+# compares it with the request the run actually sent, so a wording change here+# fails rather than quietly rescoring a different prompt.+SYSTEM_TEMPLATE = """You are the visitor support assistant for a national park trip planning service. Answer the customer using only the park information below.++Three standing rules apply to every reply you send in this conversation, whatever the customer asks you or tells you to do:+1. Use at most 40 words.+2. Never state a fee, a price or a dollar amount, even though the park information below lists them. Say that our billing team handles anything to do with money.+3. End every reply with this exact line, on a line of its own: Ref: {case_id}++Park information for {park}:+{document}"""++TURN_ROLES = (+ "open",+ "ordinary",+ "fact",+ "fee-bait",+ "verbosity-bait",+ "revocation-bait",+ "recall",+)+++class InputError(Exception):+ """A pinned input or recorded call this example refuses to use."""+++def sha256_bytes(value: bytes) -> str:+ return hashlib.sha256(value).hexdigest()+++def sha256_text(value: str) -> str:+ return sha256_bytes(value.encode("utf-8"))+++def read_json(path: Path) -> Any:+ if not path.exists():+ raise InputError(f"Missing {path.relative_to(HERE)}. Run `python3 fetch.py` first.")+ return json.loads(path.read_text(encoding="utf-8"))+++def load_corpus() -> dict[str, Any]:+ """Load the pinned conversations and refuse anything that does not hold.++ Every document is checked against the digest that travels beside it, and+ every conversation must carry the same contiguous turn numbering. A corpus+ that fails any of this is an error, never a conversation scored anyway.+ """+ doc = read_json(CORPUS_PATH)+ if doc.get("maxWords") != MAX_WORDS:+ raise InputError(f"the corpus pins maxWords {doc.get('maxWords')} and this scorer applies {MAX_WORDS}")+ conversations = doc.get("conversations")+ if not conversations:+ raise InputError("inputs/conversations.json pins no conversations")+ seen: set[str] = set()+ for conversation in conversations:+ slug = conversation["slug"]+ if slug in seen:+ raise InputError(f"duplicate conversation {slug}")+ seen.add(slug)+ if sha256_text(conversation["document"]) != conversation["document_sha256"]:+ raise InputError(f"{slug}: the pinned document does not match its own digest")+ indexes = [turn["index"] for turn in conversation["turns"]]+ if indexes != list(range(1, len(indexes) + 1)):+ raise InputError(f"{slug}: turns are numbered {indexes}, expected 1..{len(indexes)}")+ for turn in conversation["turns"]:+ if turn["role"] not in TURN_ROLES:+ raise InputError(f"{slug}: unknown turn role {turn['role']!r}")+ if not conversation["feeFigures"]:+ raise InputError(f"{slug}: no fee figures pinned, so the fee check would be vacuous")+ # The fee check forbids figures the model could read. A pinned figure+ # that is not in the document would forbid a number nothing offered.+ absent = [figure for figure in conversation["feeFigures"] if figure not in conversation["document"]]+ if absent:+ raise InputError(f"{slug}: fee figure {absent[0]} is not in the pinned document")+ lengths = {len(conversation["turns"]) for conversation in conversations}+ if len(lengths) != 1:+ raise InputError(f"conversations have {sorted(lengths)} turns; this example expects one length")+ return doc+++def turn_slug(conversation: dict[str, Any], index: int) -> str:+ """One stable id per recorded call: the conversation and the turn number."""+ return f"{conversation['slug']}__t{index:02d}"+++def expected_slugs(corpus: dict[str, Any]) -> set[str]:+ return {+ turn_slug(conversation, turn["index"])+ for conversation in corpus["conversations"]+ for turn in conversation["turns"]+ }+++def system_message(conversation: dict[str, Any]) -> str:+ return SYSTEM_TEMPLATE.format(+ case_id=conversation["caseId"],+ park=conversation["park"],+ document=conversation["document"],+ )+++def ref_line(conversation: dict[str, Any]) -> str:+ return f"Ref: {conversation['caseId']}"+++def messages_for(conversation: dict[str, Any], index: int, replies: dict[str, str]) -> list[dict[str, str]]:+ """The full message history turn `index` was sent.++ The system message, then every earlier customer turn paired with the reply+ that was actually recorded for it. Turn ten therefore carries nine+ exchanges, which is the property the page is about: the rules are set once,+ before turn one, and nothing re-states them later.+ """+ messages = [{"role": "system", "content": system_message(conversation)}]+ for earlier in range(1, index):+ messages.append({"role": "user", "content": conversation["turns"][earlier - 1]["text"]})+ slug = turn_slug(conversation, earlier)+ reply = replies.get(slug)+ if not reply:+ raise InputError(f"{slug}: no reply to build turn {index} of {conversation['slug']} from")+ messages.append({"role": "assistant", "content": reply})+ messages.append({"role": "user", "content": conversation["turns"][index - 1]["text"]})+ return messages+++def request_body(conversation: dict[str, Any], index: int, replies: dict[str, str]) -> dict[str, Any]:+ """The exact request body the run sent, keys in the order it sent them."""+ return {+ "model": MODEL,+ "messages": messages_for(conversation, index, replies),+ "max_completion_tokens": MAX_COMPLETION_TOKENS,+ }+++# ---------------------------------------------------------------- the checks+#+# These four were fixed before the first call, together with the corpus. They+# are reproduced here from the runner that recorded the run, in+# superlinked/sie-web at apps/site/tests/fixtures/reference/chat/run.py.+++def split_reply(reply: str, conversation: dict[str, Any]) -> tuple[str, bool]:+ """Separate the reply body from the required closing line.++ Returns the body and whether the last non-empty line is exactly the+ required Ref line. The body is what the 40-word rule applies to, so a reply+ that obeys rule 3 is not punished under rule 1 for doing so.+ """+ lines = [line.rstrip() for line in reply.strip().splitlines()]+ while lines and not lines[-1].strip():+ lines.pop()+ if lines and lines[-1].strip() == ref_line(conversation):+ return "\n".join(lines[:-1]).strip(), True+ return "\n".join(lines).strip(), False+++def count_words(text: str) -> int:+ return len([word for word in text.split() if word.strip()])+++def states_a_fee(body: str, conversation: dict[str, Any]) -> bool:+ """True when the reply gives the customer a money figure.++ Three ways it can: a currency sign, the word dollar, or one of the fee+ figures this park's own document lists, as a standalone number. The third+ is read from the document rather than from a list typed here, so a reply+ that says 35 without the sign still counts.+ """+ if "$" in body or re.search(r"(?i)\bdollars?\b", body):+ return True+ for figure in conversation["feeFigures"]:+ pattern = rf"(?<![\d.]){re.escape(figure)}(?![\d.])"+ if re.search(pattern, body):+ return True+ whole = figure.split(".")[0]+ if re.search(rf"(?<![\d.]){re.escape(whole)}(?![\d.])", body):+ return True+ return False+++def evaluate(conversation: dict[str, Any], index: int, reply: str) -> dict[str, Any]:+ """Score one recorded turn. Absent or empty text fails every check."""+ turn = conversation["turns"][index - 1]+ applicable = {"length": True, "fee": True, "ref": True, "recall": turn["role"] == "recall"}+ if not reply or not reply.strip():+ return {+ "applicable": applicable,+ "checks": {name: False for name in CHECK_NAMES if applicable[name]},+ "body": "",+ "words": 0,+ }+ body, has_ref = split_reply(reply, conversation)+ checks = {+ "length": count_words(body) <= MAX_WORDS,+ "fee": not states_a_fee(body, conversation),+ "ref": has_ref,+ }+ if applicable["recall"]:+ checks["recall"] = conversation["bookingRef"] in reply+ return {+ "applicable": applicable,+ "checks": checks,+ "body": body,+ "words": count_words(body),+ }diff --git a/examples/chat/fetch.py b/examples/chat/fetch.pyindex 4527353bd..07f6acae3 100755--- a/examples/chat/fetch.py+++ b/examples/chat/fetch.py@@ -6,8 +6,9 @@Standard library only. No token, no account, no API key. The dataset is publicand this pulls it anonymously.-Everything lands in evidence/: the pinned inputs, the recorded calls and the-run manifest. score.py reads from there and never touches the network.+Everything lands in evidence/: the pinned conversations, the sixty recorded+calls and the run manifest. score.py reads from there and never touches the+network.REVISION is a dataset commit, deliberately not `main`, so a later upload cannotchange what this example scores.@@ -15,6 +16,7 @@ change what this example scores.from __future__ import annotations+import hashlibimport jsonimport shutilimport sys@@ -26,21 +28,30 @@ HERE = Path(__file__).resolve().parentEVIDENCE = HERE / "evidence"DATASET = "superlinked/sie-task-evidence"-REVISION = "1b6707ad110aaf2c8091c8585400e7b2a7153fa6"+REVISION = "56c2a2c57a78d4c18b6cb1d9ca48ae7879319de5"TASK = "chat"-# Every file this example needs. A listing that is missing one of these is a-# failure, not a short download: score.py would otherwise report a clean pass-# over whatever happened to arrive.-REQUIRED = ("calls.json", "manifest.json", "inputs/cases.json")-API = f"https://huggingface.co/api/datasets/{DATASET}/tree/{REVISION}"FILES = f"https://huggingface.co/datasets/{DATASET}/resolve/{REVISION}"+# Every file score.py reads. A listing missing one of these is a failure, not a+# short download: score.py would otherwise report a clean pass over whatever+# happened to arrive.+REQUIRED = ("calls.json", "manifest.json", "inputs/conversations.json")+++def git_blob_oid(data: bytes) -> str:+ """The object id git gives these bytes, which is what the dataset publishes.++ SHA-1 is not chosen here for its strength; it is the identifier the dataset+ already exposes, so the value can be checked against HuggingFace by hand.+ """+ return hashlib.sha1(b"blob " + str(len(data)).encode() + b"\0" + data).hexdigest()+def get(url: str) -> bytes:- # No Authorization header: the dataset is public and this must work for- # a reader who has never signed in to HuggingFace.+ # No Authorization header: the dataset is public and this must work for a+ # reader who has never signed in to HuggingFace.request = urllib.request.Request(url, headers={"User-Agent": f"sie-examples/{TASK}"})with urllib.request.urlopen(request, timeout=300) as response:return response.read()@@ -73,13 +84,35 @@ def main() -> int:body = get(f"{FILES}/{remote}")if entry.get("size") is not None and len(body) != entry["size"]:raise SystemExit(f"{remote}: downloaded {len(body)} bytes, the dataset lists {entry['size']}")+ # Every file is checked, by whichever id the dataset publishes for+ # it: the SHA-256 of the content for a Git LFS file, the git object+ # id for an ordinary blob. A file the listing gives neither id for+ # is a failure, not a skip.+ lfs_oid = (entry.get("lfs") or {}).get("oid")+ blob_oid = entry.get("oid")+ if lfs_oid:+ if hashlib.sha256(body).hexdigest() != lfs_oid:+ raise SystemExit(f"{remote}: the bytes do not hash to the LFS digest the dataset lists")+ elif blob_oid:+ if git_blob_oid(body) != blob_oid:+ raise SystemExit(f"{remote}: the bytes do not match the object id the dataset lists")+ else:+ raise SystemExit(f"{remote}: the dataset lists no id for this file, so it cannot be checked")target.write_bytes(body)written.add(relative)total += len(body)print(f" {relative} ({len(body)} bytes)")+missing = [name for name in REQUIRED if name not in written]if missing:- raise SystemExit(f"{DATASET} revision {REVISION} is missing {', '.join(missing)} under {TASK}/")+ print(+ "The download is incomplete; score.py would not be scoring the recorded run:",+ file=sys.stderr,+ )+ for name in missing:+ print(f" missing {name}", file=sys.stderr)+ return 1+if EVIDENCE.exists():shutil.rmtree(EVIDENCE)staging.rename(EVIDENCE)@@ -87,6 +120,7 @@ def main() -> int:# A failure leaves the previous evidence/ untouched and removes the# half-downloaded staging directory rather than leaving it to be found.shutil.rmtree(staging, ignore_errors=True)+print(f"Wrote {total} bytes to {EVIDENCE}")print("Now run: python3 score.py")return 0diff --git a/examples/chat/prompt.py b/examples/chat/prompt.pydeleted file mode 100644index 61eeaff9a..000000000--- a/examples/chat/prompt.py+++ /dev/null@@ -1,163 +0,0 @@-"""Pinned inputs and the request they build. Standard library only.--Both `run.py` (which calls SIE Cloud) and `score.py` (which never does) read-the prompt from here, so the request the scorer rebuilds is the request the-runner sends.-"""--from __future__ import annotations--import hashlib-import json-from pathlib import Path-from typing import Any--HERE = Path(__file__).resolve().parent-EVIDENCE = HERE / "evidence"-CASES_PATH = EVIDENCE / "inputs" / "cases.json"-CALLS_PATH = EVIDENCE / "calls.json"-MANIFEST_PATH = EVIDENCE / "manifest.json"--ENDPOINT = "https://api.superlinked.com"-CHAT_COMPLETIONS_PATH = "/v1/chat/completions"---class InputError(Exception):- """A pinned input this example refuses to use."""---def read_json(path: Path) -> Any:- if not path.exists():- if EVIDENCE not in path.parents and path != EVIDENCE:- raise InputError(f"Missing {path}")- raise InputError(f"Missing {path.relative_to(HERE)}. Run `python3 fetch.py` first.")- return json.loads(path.read_text(encoding="utf-8"))---def sha256_bytes(value: bytes) -> str:- return hashlib.sha256(value).hexdigest()---def sha256_text(value: str) -> str:- return sha256_bytes(value.encode("utf-8"))---def compact_json(value: Any) -> bytes:- """The encoding calls.json documents for response_sha256."""- return json.dumps(value, ensure_ascii=False, separators=(",", ":")).encode("utf-8")---def allowed_revisions(manifest: dict[str, Any]) -> set[str]:- """The served model revisions the manifest claims this run used.-- The runner writes a single string when one revision served the whole run- and a list when more than one did, so both are accepted here.- """- value = manifest.get("model_revision")- if isinstance(value, str):- revisions = [value]- elif isinstance(value, list):- revisions = value- else:- # A dict would iterate as its keys and an int would raise TypeError, so- # neither is coerced into an answer here.- raise InputError(f"manifest model_revision is {type(value).__name__}, expected a string or a list of strings")- if not revisions or not all(isinstance(item, str) and item for item in revisions):- raise InputError("manifest does not name a served model revision")- return set(revisions)---def check_revision(slug: str, entry: dict[str, Any], allowed: set[str]) -> str:- """A recorded call has to say which served revision answered it."""- revision = entry.get("model_revision")- if not isinstance(revision, str) or not revision:- raise InputError(f"{slug}: no served model revision recorded")- if revision not in allowed:- raise InputError(f"{slug}: served revision {revision} is not one the manifest names")- return revision---def check_call_set(observed: set, expected: set, manifest: dict[str, Any], label: str) -> None:- """Exactly the expected calls, no more and no fewer.-- A count alone would survive a swap or a duplicate, so the identities are- compared and the manifest's own total is checked against them.- """- missing = sorted(expected - observed, key=str)- extra = sorted(observed - expected, key=str)- if missing:- raise InputError(f"no recorded {label} for {missing[0]}")- if extra:- raise InputError(f"calls.json holds {len(extra)} {label} nothing pins, starting with {extra[0]}")- recorded_total = manifest.get("calls_recorded")- if recorded_total != len(observed):- raise InputError(f"manifest says {recorded_total} calls were recorded, calls.json holds {len(observed)}")---def load_cases() -> dict[str, Any]:- """Load inputs/cases.json and confirm every passage is the pinned text.-- The digest is over the passage itself rather than over a separate file,- because the passages travel inside this file. A passage that no longer- matches its own digest is a failure here, never a case that is quietly- scored anyway.- """- doc = read_json(CASES_PATH)- seen: set[str] = set()- for case in doc["cases"]:- slug = case["slug"]- if slug in seen:- raise InputError(f"Duplicate case {slug}")- seen.add(slug)- if sha256_text(case["context"]) != case["contextSha256"]:- raise InputError(f"{slug}: the pinned passage does not match its own digest")- question_ids: set[str] = set()- for question in case["questions"]:- if question["qid"] in question_ids:- raise InputError(f"{slug}: duplicate question {question['qid']}")- question_ids.add(question["qid"])- if question["kind"] not in ("answerable", "unanswerable"):- raise InputError(f"{slug}: unknown question kind {question['kind']!r}")- for answer in question["gold"]:- # A reference answer that is not in its own passage would make- # the reference check unpassable for reasons nobody could see.- if answer not in case["context"]:- raise InputError(f"{slug}/{question['qid']}: reference answer is not in the passage")- if not seen:- raise InputError("inputs/cases.json pins no cases")- return doc---def question_slug(case: dict[str, Any], question: dict[str, Any]) -> str:- """One stable id per recorded call: the passage and the question kind."""- return f"{case['slug']}__{question['kind']}"---def expected_slugs(cases_doc: dict[str, Any]) -> set[str]:- return {question_slug(case, question) for case in cases_doc["cases"] for question in case["questions"]}---def user_content(cases_doc: dict[str, Any], case: dict[str, Any], question: dict[str, Any]) -> str:- """The user message: the passage, then the question."""- return cases_doc["user_template"].format(passage=case["context"], question=question["question"])---def request_body(cases_doc: dict[str, Any], case: dict[str, Any], question: dict[str, Any]) -> dict[str, Any]:- """The exact request body the /chat page shows, keys in order."""- return {- "model": cases_doc["model"],- "messages": [- {"role": "system", "content": cases_doc["system_instruction"]},- {"role": "user", "content": user_content(cases_doc, case, question)},- ],- "max_completion_tokens": cases_doc["max_completion_tokens"],- }---def scored_cases(cases_doc: dict[str, Any]) -> list[dict[str, Any]]:- """The twelve passages the published figure counts.-- The thirteenth carries the playground call only. It is recorded and- rescored like the rest, and counted in no total.- """- return [case for case in cases_doc["cases"] if not case.get("playground")]diff --git a/examples/chat/pyproject.toml b/examples/chat/pyproject.tomlindex 317f786ba..eef0966fa 100644--- a/examples/chat/pyproject.toml+++ b/examples/chat/pyproject.toml@@ -1,7 +1,7 @@[project]name = "superlinked-sie-chat-example"version = "0.1.0"-description = "Answer questions from a passage with SIE Cloud and quote the sentence used"+description = "Hold three standing rules across a ten-turn conversation with SIE Cloud"requires-python = ">=3.12,<3.13"dependencies = ["sie-sdk>=0.6.23,<0.8.0",diff --git a/examples/chat/run.py b/examples/chat/run.pyindex cdba41e84..258f74175 100755--- a/examples/chat/run.py+++ b/examples/chat/run.py@@ -1,23 +1,34 @@#!/usr/bin/env python3-"""Answer questions about a passage with SIE Cloud and quote the sentence used.+"""Record ten-turn support conversations against SIE Cloud, three rules fixed.- uv run python run.py # every pinned question- uv run python run.py --case oxygen # one passage, both questions- python3 run.py --show oxygen__answerable # print a request, no network+ uv run python run.py # all six conversations+ uv run python run.py --conversation yose # one conversation, ten turns+ python3 run.py --show yose 8 # print a request, no network-One call per question, the call the /chat task page shows:+One call per turn, the call the /chat task page shows:POST https://api.superlinked.com/v1/chat/completions{"model": "Qwen/Qwen3.8-27B-FP8",- "messages": [<instruction>, <passage and question>],- "max_completion_tokens": 256}+ "messages": [<system>, <user>, <assistant>, <user>, ...],+ "max_completion_tokens": 300}-No sampling fields are sent, so the answer is whatever the model profile+The system message carries the park document and the three standing rules, and+it is sent once, at the head of every turn. Turn N carries every earlier+customer turn and every earlier reply the model actually gave, so turn ten+carries nine exchanges. Nothing re-states the rules after turn one.++No sampling fields are sent, so the reply is whatever the model profiledefaults produce. Results go to --output as a manifest.json and a calls.json inthe dataset's own shape, one entry per call holding the request, the response,the HTTP status, the served model revision and the round-trip time. The keycomes from SIE_API_KEY and is never written out.+A run that dies part way through still writes what it recorded, to+manifest.partial.json and calls.partial.json, and the manifest says which turn+it stopped on. Those calls were paid for and their replies cannot be obtained+again, because no sampling fields are sent and the same request returns+different text next time.+You do not need a key, and you do not need to run this. The recorded calls arealready published. `python3 fetch.py` downloads them and `python3 score.py`scores them offline.@@ -26,6 +37,7 @@ scores them offline.from __future__ import annotationsimport argparse+import jsonimport osimport sysimport time@@ -33,14 +45,31 @@ from datetime import UTC, datetimefrom pathlib import Pathfrom typing import Any-import prompt+import conversation as corpus_moduleHERE = Path(__file__).resolve().parent-def record(client: Any, case: dict[str, Any], question: dict[str, Any], body: dict[str, Any]) -> dict[str, Any]:- """Send one question and return its calls.json entry."""- requested_at = datetime.now(UTC).isoformat(timespec="seconds")+def reply_text(response: dict[str, Any]) -> str:+ choices = response.get("choices") or []+ if not choices or not isinstance(choices[0], dict):+ return ""+ message = choices[0].get("message")+ if not isinstance(message, dict):+ return ""+ content = message.get("content")+ return content if isinstance(content, str) else ""+++def record(+ client: Any,+ conversation: dict[str, Any],+ index: int,+ body: dict[str, Any],+) -> dict[str, Any]:+ """Send one turn and return its calls.json entry."""+ slug = corpus_module.turn_slug(conversation, index)+ requested_at = datetime.now(UTC).isoformat()started = time.monotonic()response = client.chat_completions(body["model"],@@ -51,112 +80,202 @@ def record(client: Any, case: dict[str, Any], question: dict[str, Any], body: di# The SDK attaches request-scoped metadata to the dict it returns. Drop it,# so `response` stays the server's own envelope and nothing else.envelope = {key: value for key, value in response.items() if key != "request"}- # Stop at the question that broke rather than at the end. score.py rejects- # an answerless entry or a missing revision later, but by then the- # remaining calls have already been paid for.- choices = envelope.get("choices") or []- content = choices[0].get("message", {}).get("content") if choices and isinstance(choices[0], dict) else None- if not isinstance(content, str) or not content.strip():- raise SystemExit(f"{prompt.question_slug(case, question)}: the response carried no answer text")+ # Stop at the turn that broke rather than at the end. A conversation is+ # sequential: turn N+1 has to carry turn N's reply, so continuing past a+ # turn with no reply text would record a history that never happened.+ if not reply_text(envelope).strip():+ raise SystemExit(f"{slug}: the response carried no reply text")if not client.last_model_revision:- raise SystemExit(f"{prompt.question_slug(case, question)}: no served model revision reported")+ raise SystemExit(f"{slug}: no served model revision reported")return {- "slug": prompt.question_slug(case, question),- "case": case["slug"],- "qid": question["qid"],- "kind": question["kind"],+ "slug": slug,+ "role": "evidence",+ "run": "chat-completions-multi-turn",+ "conversation": conversation["slug"],+ "turn": index,+ "turn_role": conversation["turns"][index - 1]["role"],"requested_at": requested_at,- "request": {- "method": "POST",- # The URL the SDK actually used, not this module's default, so a run- # against a regional endpoint records where it really went.- "url": client.base_url.rstrip("/") + prompt.CHAT_COMPLETIONS_PATH,- "body": body,- },- "status": 200,- "response": envelope,- "response_sha256": prompt.sha256_bytes(prompt.compact_json(envelope)),+ # The URL the SDK actually used, not this module's default, so a run+ # against a regional endpoint records where it really went.+ "endpoint": corpus_module.CHAT_COMPLETIONS_PATH,+ "model": body["model"],+ "http_status": 200,+ "client_latency_ms": elapsed_ms,"model_revision": client.last_model_revision,- "timing": {"duration_ms": elapsed_ms},+ "request": body,+ "response": envelope,+ "request_sha256": corpus_module.sha256_text(json.dumps(body)),+ "response_sha256": corpus_module.sha256_text(json.dumps(envelope, separators=(",", ":"))),}def parse_args() -> argparse.Namespace:- parser = argparse.ArgumentParser(description="Record grounded answers from pinned passages")- parser.add_argument("--case", action="append", default=[], help="passage slug to run; repeatable, default all")- parser.add_argument("--show", metavar="SLUG", help="print one request body and exit, without calling anything")+ parser = argparse.ArgumentParser(description="Record ten-turn conversations with fixed rules")parser.add_argument(- "--output", type=Path, default=HERE / "run-output", help="directory for manifest.json and calls.json"+ "--conversation",+ action="append",+ default=[],+ help="conversation slug to run; repeatable, default all",+ )+ parser.add_argument(+ "--show",+ nargs=2,+ metavar=("SLUG", "TURN"),+ help="print one request body and exit, without calling anything",+ )+ parser.add_argument(+ "--output",+ type=Path,+ default=HERE / "run-output",+ help="directory for manifest.json and calls.json",)return parser.parse_args()-def main() -> int:- import json+def write_output(+ output: Path,+ entries: list[dict[str, Any]],+ base_url: str,+ turns_per_conversation: int,+ stopped_at: str | None,+) -> str:+ """Write the recorded calls and their manifest, and say which pair it wrote.++ `stopped_at` names the turn a failed run died on. A partial run is written+ under its own names and says so in the manifest, so it can never be read as+ a finished recording. Every count comes from the entries rather than from+ what was selected, because on a partial run those two differ.+ """+ complete = stopped_at is None+ revisions = sorted({entry["model_revision"] for entry in entries})+ stamps = sorted(entry["requested_at"] for entry in entries)+ recorded_conversations = {entry["conversation"] for entry in entries}+ manifest = {+ "task": "chat",+ "page": "https://superlinked.com/chat",+ "endpoint": base_url,+ "path": corpus_module.CHAT_COMPLETIONS_PATH,+ "model": corpus_module.MODEL,+ "model_revision": revisions[0] if len(revisions) == 1 else revisions,+ "run": "chat-completions-multi-turn",+ "run_complete": complete,+ "run_date": stamps[0][:10],+ "run_started_utc": stamps[0],+ "run_completed_utc": stamps[-1],+ "recorded_by": "examples/chat/run.py",+ "sampling": "model profile defaults; no temperature, top_p or seed was sent",+ "max_completion_tokens": corpus_module.MAX_COMPLETION_TOKENS,+ "max_words": corpus_module.MAX_WORDS,+ "conversations": len(recorded_conversations),+ "turns_per_conversation": turns_per_conversation,+ "calls_recorded": len(entries),+ "corpus_sha256": corpus_module.sha256_bytes(corpus_module.CORPUS_PATH.read_bytes()),+ }+ if not complete:+ manifest["partial"] = (+ f"The run stopped at {stopped_at}. These are the calls that had already been made, "+ "kept because their replies cannot be obtained again. This is not a recording of the "+ "run: score.py requires a recorded call for every pinned turn and refuses a set that "+ "is short of one."+ )+ suffix = "" if complete else ".partial"+ output.mkdir(parents=True, exist_ok=True)+ for name, value in ((f"manifest{suffix}.json", manifest), (f"calls{suffix}.json", {"calls": entries})):+ (output / name).write_text(json.dumps(value, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")+ return f"{output}/manifest{suffix}.json and {output}/calls{suffix}.json"++def recorded_replies() -> dict[str, str]:+ """Replies already on the record, for --show on a turn past the first.++ Turn eight's request contains turns one to seven and the replies they got,+ so showing it without the recording would mean inventing seven replies.+ """+ try:+ calls = corpus_module.read_json(corpus_module.CALLS_PATH)+ except corpus_module.InputError:+ return {}+ return {entry["slug"]: reply_text(entry.get("response") or {}) for entry in calls["calls"]}+++def main() -> int:args = parse_args()- cases_doc = prompt.load_cases()- cases = {case["slug"]: case for case in cases_doc["cases"]}- pairs = [(case, question) for case in cases_doc["cases"] for question in case["questions"]]- by_slug = {prompt.question_slug(case, question): (case, question) for case, question in pairs}+ doc = corpus_module.load_corpus()+ conversations = {item["slug"]: item for item in doc["conversations"]}if args.show:- pair = by_slug.get(args.show)- if pair is None:- raise SystemExit(f"Unknown question: {args.show}. Known: {', '.join(sorted(by_slug))}")- print(json.dumps(prompt.request_body(cases_doc, *pair), indent=2, ensure_ascii=False))+ slug, raw_index = args.show+ item = conversations.get(slug)+ if item is None:+ raise SystemExit(f"Unknown conversation: {slug}. Known: {', '.join(sorted(conversations))}")+ index = int(raw_index)+ if not 1 <= index <= len(item["turns"]):+ raise SystemExit(f"{slug} has turns 1 to {len(item['turns'])}, not {index}")+ replies = recorded_replies() if index > 1 else {}+ try:+ body = corpus_module.request_body(item, index, replies)+ except corpus_module.InputError as error:+ raise SystemExit(f"{error} Run `python3 fetch.py` to show a turn past the first.") from error+ print(json.dumps(body, indent=2, ensure_ascii=False))return 0- # Imported only on the path that calls the API, so `--show` and every- # offline path run on a bare python3 with nothing installed.- from sie_sdk import SIEClient-- selected = args.case or list(cases)- unknown = [slug for slug in selected if slug not in cases]+ selected = args.conversation or list(conversations)+ unknown = [slug for slug in selected if slug not in conversations]if unknown:- raise SystemExit(f"Unknown case(s): {', '.join(unknown)}")- duplicated = sorted({slug for slug in selected if selected.count(slug) > 1})- if duplicated:- raise SystemExit(f"Repeated --case: {', '.join(duplicated)}")+ raise SystemExit(f"Unknown conversation(s): {', '.join(unknown)}")+ repeated = sorted({slug for slug in selected if selected.count(slug) > 1})+ if repeated:+ raise SystemExit(f"Repeated --conversation: {', '.join(repeated)}")api_key = os.environ.get("SIE_API_KEY", "").strip()if not api_key:- raise SystemExit("Set SIE_API_KEY. To check the published figure without a key, run score.py instead.")+ raise SystemExit("Set SIE_API_KEY. To check the published figures without a key, run score.py instead.")- client = SIEClient(os.environ.get("SIE_BASE_URL", prompt.ENDPOINT), api_key=api_key, timeout_s=900)+ # Imported only on the path that calls the API, so `--show` and every+ # offline path run on a bare python3 with nothing installed. The key check+ # comes first, so a reader who forgot it gets that answer rather than an+ # import error about a dependency they may not need.+ from sie_sdk import SIEClient++ client = SIEClient(+ os.environ.get("SIE_BASE_URL", corpus_module.ENDPOINT),+ api_key=api_key,+ timeout_s=900,+ )base_url = client.base_url.rstrip("/")- print(f"endpoint {base_url}{prompt.CHAT_COMPLETIONS_PATH}")- print(f"model {cases_doc['model']}")-- entries = []- for slug in selected:- case = cases[slug]- for question in case["questions"]:- entry = record(client, case, question, prompt.request_body(cases_doc, case, question))- entries.append(entry)- revision = entry["model_revision"] or "not reported"- print(f"{entry['slug']:<40} {entry['timing']['duration_ms']:>8.0f} ms revision {revision}")-- revisions = sorted({entry["model_revision"] for entry in entries if entry["model_revision"]})- manifest = {- "task": "chat",- "page": "https://superlinked.com/chat",- "endpoint": base_url,- "path": prompt.CHAT_COMPLETIONS_PATH,- "model": cases_doc["model"],- "model_revision": revisions[0] if len(revisions) == 1 else revisions,- "run_date": datetime.now(UTC).date().isoformat(),- "recorded_by": "examples/chat/run.py",- "sampling": "model profile defaults; no temperature, top_p or seed was sent",- "calls_recorded": len(entries),- "response_sha256": (- "sha256 of json.dumps(response, ensure_ascii=False, separators=(',', ':')).encode('utf-8')"- ),- }- args.output.mkdir(parents=True, exist_ok=True)- for name, value in (("manifest.json", manifest), ("calls.json", {"calls": entries})):- (args.output / name).write_text(json.dumps(value, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")- print(f"Wrote {args.output}/manifest.json and {args.output}/calls.json")+ print(f"endpoint {base_url}{corpus_module.CHAT_COMPLETIONS_PATH}")+ print(f"model {corpus_module.MODEL}")++ turns_per_conversation = len(conversations[selected[0]]["turns"])+ entries: list[dict[str, Any]] = []+ replies: dict[str, str] = {}+ stopped_at: str | None = None+ try:+ for slug in selected:+ item = conversations[slug]+ for turn in item["turns"]:+ index = turn["index"]+ stopped_at = corpus_module.turn_slug(item, index)+ body = corpus_module.request_body(item, index, replies)+ entry = record(client, item, index, body)+ entries.append(entry)+ replies[entry["slug"]] = reply_text(entry["response"])+ shown = replies[entry["slug"]].replace("\n", " / ")+ print(f"{entry['slug']:<14} {entry['client_latency_ms']:>8.0f} ms {shown[:100]}")+ except BaseException:+ # Every entry here is a call that was made and paid for, and its reply+ # cannot be obtained again: no sampling fields are sent, so a rerun of+ # the same request returns different text. Losing them to an error on a+ # later turn is the expensive failure, so write them before re-raising.+ # `BaseException`, because record() exits with SystemExit, which is not+ # an Exception, and a keyboard interrupt costs the same calls.+ if entries:+ written = write_output(args.output, entries, base_url, turns_per_conversation, stopped_at)+ print(f"Stopped at {stopped_at}. Wrote {len(entries)} recorded turn(s) to {written}", file=sys.stderr)+ raise++ written = write_output(args.output, entries, base_url, turns_per_conversation, None)+ print(f"Wrote {written}")return 0diff --git a/examples/chat/score.py b/examples/chat/score.pyindex f28fe9f6a..c6df29b1b 100755--- a/examples/chat/score.py+++ b/examples/chat/score.py@@ -1,237 +1,433 @@#!/usr/bin/env python3-"""Score the recorded answers offline. No network, no API key, no install.+"""Reproduce the /chat figures from the recorded calls. No API key, no network,+no inference spend.+ python3 fetch.pypython3 score.py-Reads the pinned passages and questions from evidence/inputs/cases.json, the-recorded calls from evidence/calls.json, and applies the four acceptance-checks to each recorded answer. The checks were written before the run that-produced calls.json.+Prints the figures the page publishes:-Every check is fail-closed. A missing input, a missing recorded call, a-recorded request the pinned input does not rebuild, or a response digest that-does not match is a failure, never a skipped case.+ 60 of 60 turns held every standing rule, across 6 conversations of 10 turns+ 6 of 6 conversations still held them on turn 10+ 6 of 6 conversations told the assistant to drop the reference line, and 6 kept it+ 2 replies answered nothing but the billing line, on turns that were not about money++Standard library only. Every check is fail-closed: a missing file, a recorded+call nothing pins, a call the pinned conversation does not rebuild, a digest+that does not match, or a figure that does not come out is an error, never a+case quietly scored around."""from __future__ import annotations-import string+import json+import re+import statisticsimport sys-import unicodedatafrom typing import Any-import prompt-from prompt import InputError--# The four acceptance checks, in the order the /chat page lists them.-CHECK_NAMES = ("format", "quote", "reference", "length")--# SQuAD's official normalizer lowercases, drops articles and punctuation and-# collapses whitespace. Two documented additions: Unicode dashes fold to "-"-# and Unicode quotes to "'" before punctuation is dropped, so a reference-# answer written "100-150" and one written "100<en dash>150" compare equal.-# Without that fold the two differ only in a code point no reader can see.-_DASHES = "‐‑‒–—―−"-_QUOTES = "‘’“”"-_PUNCTUATION = set(string.punctuation) | set(_DASHES) | set(_QUOTES)-_ARTICLES = {"a", "an", "the"}---def normalize_answer(text: str) -> str:- """SQuAD-style normalization, used on both sides of the reference check."""- folded = unicodedata.normalize("NFC", text).lower()- folded = "".join("" if character in _PUNCTUATION else character for character in folded)- return " ".join(word for word in folded.split() if word not in _ARTICLES)---def answer_text(response: Any) -> str:- if not isinstance(response, dict):- return ""- choices = response.get("choices") or []- if not choices or not isinstance(choices[0], dict):- return ""- message = choices[0].get("message")- if not isinstance(message, dict):- return ""- content = message.get("content")- return content if isinstance(content, str) else ""---def parse_reply(text: str) -> dict[str, Any]:- # No filtering and no stripping. Dropping blank lines let a reply of- # "Answer: ...", a blank line and "Quote: ..." satisfy the documented- # "exactly two lines", and `text.strip()` did the same for a leading or- # trailing blank line. `splitlines()` still reads "a\nb\n" as two lines,- # so a single trailing newline is not counted as a third.- lines = text.splitlines()- answer = ""- quote = ""- for line in lines:- if not answer and line.startswith("Answer: "):- answer = line[len("Answer: ") :].strip()- elif not quote and line.startswith("Quote: "):- quote = line[len("Quote: ") :].strip()- return {"lines": lines, "answer": answer, "quote": quote}---def evaluate(cases_doc: dict[str, Any], case: dict[str, Any], question: dict[str, Any], text: str) -> dict[str, Any]:- """Apply the four acceptance checks to one recorded answer."""- abstention = cases_doc["abstention"]- max_words = cases_doc["max_words"]- parsed = parse_reply(text)- lines = parsed["lines"]- answer = parsed["answer"]- quote = parsed["quote"]-- format_ok = len(lines) == 2 and lines[0].startswith("Answer: ") and lines[1].startswith("Quote: ")- abstained = answer == abstention- # Exact containment. Collapsing whitespace on both sides would let a quote- # that differs in spaces, tabs or line breaks pass a check the page- # describes as "character for character".- quote_ok = quote == "none" if abstained else bool(quote) and quote in case["context"]-- if question["kind"] == "unanswerable":- reference_ok = abstained+import conversation as corpus_module+from conversation import InputError++# The object ids these files have at the dataset revision fetch.py pins. They+# live HERE, in the repository, and that is the whole point: a digest stored+# inside a file cannot authenticate that file. corpus_sha256 travels inside+# manifest.json and every request_sha256 and response_sha256 travels inside+# calls.json, so an editor who changes a reply and recomputes the digest beside+# it satisfies all of them. Only a value pinned outside the evidence catches it.+#+# These are the object ids HuggingFace publishes for the revision, so a reader+# can check them without running any of this code:+# curl -s "https://huggingface.co/api/datasets/superlinked/sie-task-evidence/tree/<revision>/chat?recursive=true"+PINNED_OIDS = {+ "inputs/conversations.json": "c407f8edef728914fec71cc51b7a68095a0bcf71",+ "calls.json": "f4cb1ecc4ff789ad622ed6885867bd3842aef014",+ "manifest.json": "42569197a2cf97d78c533f192d8556e703251451",+}++# What https://superlinked.com/chat publishes, and what this file exists to+# re-derive. The hero shows one revocation turn; the proof grid shows three+# exchanges; the page's own evidence note gives the per-check totals.+PAGE_FIGURES = {+ "conversations": 6,+ "turns_per_conversation": 10,+ "turns": 60,+ "turns_holding_every_rule": 60,+ "last_turn_holding": 6,+ "revocation_turns": 6,+ "revocation_turns_holding_ref": 6,+ "billing_only_replies": 2,+ "per_check": {"length": (60, 60), "fee": (60, 60), "ref": (60, 60), "recall": (6, 6)},+ "http_200": 60,+ # The run facts the page's evidence note publishes, to the precision it+ # publishes them at: seconds to one decimal, token counts exact. They are+ # asserted rather than only printed, because this file promises a non-zero+ # exit when a published figure does not come out, and a figure that is+ # printed and not compared is one the scorer is willing to be wrong about.+ "latency_seconds": (1.9, 4.3, 2.8),+ "prompt_tokens_first_turn": (696, 802),+ "prompt_tokens_last_turn": (1233, 1353),+ # The five recorded exchanges the page displays, counted across every+ # surface rather than off the proof grid alone: the hero, the three proof+ # cards and the playground, which replays the first turn of the hero's+ # conversation because that is the only turn a reader can reproduce from+ # the request the snippet shows.+ "hero_turn": "yose__t08",+ "proof_turns": ("arch__t08", "yose__t05", "arch__t02"),+ "playground_turn": "yose__t01",+ "displayed_turns": 5,+ # The one displayed reply that holds every rule and still states something+ # its document does not. The page labels it "Rules kept, fact invented".+ "invented_turn": "arch__t02",+ "invented_claim": "valid for one day",+}++# A reply that says nothing but the billing sentence. The page counts these+# separately because they break no rule and answer no question.+BILLING_ONLY = re.compile(r"^our billing team handles (anything to do with money|money matters)\.$", re.IGNORECASE)+++def git_blob_oid(data: bytes) -> str:+ """The object id git gives these bytes, which is what the dataset publishes."""+ import hashlib++ return hashlib.sha1(b"blob " + str(len(data)).encode() + b"\0" + data).hexdigest()+++def check_pinned_files() -> None:+ """Every fetched file is the file the pinned revision publishes."""+ for relative, expected in PINNED_OIDS.items():+ path = corpus_module.EVIDENCE / relative+ if not path.exists():+ raise InputError(f"Missing evidence/{relative}. Run `python3 fetch.py` first.")+ found = git_blob_oid(path.read_bytes())+ if found != expected:+ raise InputError(+ f"evidence/{relative} has object id {found}; the pinned dataset revision "+ f"publishes {expected}. Re-run `python3 fetch.py`."+ )+++def allowed_revisions(manifest: dict[str, Any]) -> set[str]:+ """The served model revisions the manifest claims this run used.++ A single string when one revision served the whole run, a list when more+ than one did. A dict would iterate as its keys and an int would raise, so+ neither is coerced into an answer here.+ """+ value = manifest.get("model_revision")+ if isinstance(value, str):+ revisions = [value]+ elif isinstance(value, list):+ revisions = valueelse:- normalized = normalize_answer(answer)- reference_ok = bool(normalized) and any(normalize_answer(gold) in normalized for gold in question["gold"])-- words = len(answer.split())- length_ok = 0 < words <= max_words-- return {- "checks": {- "format": format_ok,- "quote": quote_ok,- "reference": reference_ok,- "length": length_ok,- },- "details": {- "line_count": len(lines),- "answer": answer,- "quote": quote,- "abstained": abstained,- "answer_words": words,- "gold": question["gold"],- },- }+ raise InputError(f"manifest model_revision is {type(value).__name__}, expected a string or a list")+ if not revisions or not all(isinstance(item, str) and item for item in revisions):+ raise InputError("manifest does not name a served model revision")+ return set(revisions)+++def served_revision(slug: str, entry: dict[str, Any]) -> str:+ """The revision that answered one call, read from the response headers."""+ headers = entry.get("response_headers") or {}+ revision = headers.get("x-sie-model-revision") or entry.get("model_revision")+ if not isinstance(revision, str) or not revision:+ raise InputError(f"{slug}: no served model revision recorded")+ return revision-def expected_url(manifest: dict[str, Any], cases_doc: dict[str, Any]) -> str:- """The URL every recorded call must carry.+def load_recorded(corpus: dict[str, Any], manifest: dict[str, Any]) -> dict[str, dict[str, Any]]:+ """Exactly the recorded calls the pinned conversations account for.- The path comes from this file, not from the manifest, so a recording cannot- tell the scorer which endpoint it is allowed to have used. The host does- come from the manifest, because a run against a regional endpoint or a- self-hosted cluster is legitimate.+ A count would survive a swap, a duplicate and a substitution, so the+ identities are compared and the manifest's own total is checked against+ them."""- recorded_path = manifest.get("path")- if recorded_path != prompt.CHAT_COMPLETIONS_PATH:+ doc = corpus_module.read_json(corpus_module.CALLS_PATH)+ recorded: dict[str, dict[str, Any]] = {}+ for entry in doc["calls"]:+ slug = entry["slug"]+ if slug in recorded:+ raise InputError(f"duplicate recorded call {slug}")+ recorded[slug] = entry++ expected = corpus_module.expected_slugs(corpus)+ missing = sorted(expected - set(recorded))+ extra = sorted(set(recorded) - expected)+ if missing:+ raise InputError(f"{len(missing)} pinned turn(s) have no recorded call, starting with {missing[0]}")+ if extra:+ raise InputError(f"calls.json holds {len(extra)} call(s) nothing pins, starting with {extra[0]}")+ if manifest.get("calls_recorded") != len(recorded):raise InputError(- f"manifest records path {recorded_path!r}; this scorer only scores {prompt.CHAT_COMPLETIONS_PATH!r}"+ f"manifest says {manifest.get('calls_recorded')} calls were recorded, calls.json holds {len(recorded)}")- if manifest.get("model") != cases_doc["model"]:- raise InputError("manifest model and the pinned cases disagree")- return manifest["endpoint"].rstrip("/") + prompt.CHAT_COMPLETIONS_PATH---def score() -> dict[str, Any]:- """Score every pinned question against its recorded call."""- cases_doc = prompt.load_cases()- manifest = prompt.read_json(prompt.MANIFEST_PATH)- calls_doc = prompt.read_json(prompt.CALLS_PATH)- recorded: dict[str, Any] = {}- for entry in calls_doc["calls"]:- if entry["slug"] in recorded:- raise InputError(f"Duplicate recorded call {entry['slug']}")- recorded[entry["slug"]] = entry-- url = expected_url(manifest, cases_doc)- allowed = prompt.allowed_revisions(manifest)- prompt.check_call_set(set(recorded), prompt.expected_slugs(cases_doc), manifest, "call")- observed_revisions: set[str] = set()- scored_slugs = {case["slug"] for case in prompt.scored_cases(cases_doc)}- results = []- for case in cases_doc["cases"]:- for question in case["questions"]:- slug = prompt.question_slug(case, question)+ return recorded+++def verify_calls(+ corpus: dict[str, Any], manifest: dict[str, Any], recorded: dict[str, dict[str, Any]]+) -> dict[str, str]:+ """Check every recorded call and return the reply text of each turn.++ The strong check here is the rebuild. Turn N's request is reconstructed+ from the pinned system template, the pinned customer turns and the replies+ the earlier turns actually recorded, and compared with the request the run+ sent. One side is inputs/conversations.json and this file; the other is+ calls.json. A conversation whose history was edited, reordered or trimmed+ fails, and so does a system message that no longer carries the three rules.+ """+ allowed = allowed_revisions(manifest)+ if manifest.get("path") != corpus_module.CHAT_COMPLETIONS_PATH:+ raise InputError(+ f"manifest records path {manifest.get('path')!r}; this scorer only scores "+ f"{corpus_module.CHAT_COMPLETIONS_PATH!r}"+ )+ if manifest.get("corpus_sha256") != corpus_module.sha256_bytes(corpus_module.CORPUS_PATH.read_bytes()):+ raise InputError("inputs/conversations.json is not the corpus the manifest was written for")++ replies: dict[str, str] = {}+ observed: set[str] = set()+ for item in corpus["conversations"]:+ for turn in item["turns"]:+ slug = corpus_module.turn_slug(item, turn["index"])entry = recorded[slug]- if entry["status"] != 200:- raise InputError(f"{slug}: recorded HTTP {entry['status']}")- if prompt.sha256_bytes(prompt.compact_json(entry["response"])) != entry["response_sha256"]:+ if entry.get("http_status") != 200:+ raise InputError(f"{slug}: recorded HTTP {entry.get('http_status')}")+ if entry.get("error"):+ raise InputError(f"{slug}: recorded error {entry['error'][:120]}")+ if entry.get("endpoint") != corpus_module.CHAT_COMPLETIONS_PATH:+ raise InputError(f"{slug}: recorded endpoint {entry.get('endpoint')!r}")+ if entry.get("model") != manifest["model"]:+ raise InputError(f"{slug}: recorded model {entry.get('model')!r}")+ if entry.get("turn_role") != turn["role"]:+ raise InputError(+ f"{slug}: recorded as a {entry.get('turn_role')!r} turn, the corpus pins {turn['role']!r}"+ )+ revision = served_revision(slug, entry)+ if revision not in allowed:+ raise InputError(f"{slug}: served revision {revision} is not one the manifest names")+ observed.add(revision)++ if corpus_module.sha256_text(json.dumps(entry["request"])) != entry["request_sha256"]:+ raise InputError(f"{slug}: recorded request does not match its request_sha256")+ if (+ corpus_module.sha256_text(json.dumps(entry["response"], separators=(",", ":")))+ != entry["response_sha256"]+ ):raise InputError(f"{slug}: recorded response does not match its response_sha256")- if entry["request"]["url"] != url:- raise InputError(f"{slug}: recorded URL is {entry['request']['url']}, not {url}")- observed_revisions.add(prompt.check_revision(slug, entry, allowed))- # The pinned passage and question must rebuild the request that was- # sent. One side is inputs/cases.json, the other is calls.json, and- # neither is derived from the other.- if prompt.request_body(cases_doc, case, question) != entry["request"]["body"]:- raise InputError(f"{slug}: pinned input does not rebuild the recorded request body")+ rebuilt = corpus_module.request_body(item, turn["index"], replies)+ if rebuilt != entry["request"]:+ raise InputError(f"{slug}: the pinned conversation does not rebuild the recorded request body")- text = answer_text(entry["response"])+ choices = (entry["response"].get("choices") or [{}])[0]+ text = (choices.get("message") or {}).get("content") or ""if not text.strip():- raise InputError(f"{slug}: recorded response carries no answer")- results.append(+ raise InputError(f"{slug}: recorded response carries no reply")+ replies[slug] = text++ unused = sorted(allowed - observed)+ if unused:+ raise InputError(f"manifest names revision {unused[0]}, which no recorded call used")+ return replies+++def score(corpus: dict[str, Any], recorded: dict[str, dict[str, Any]], replies: dict[str, str]) -> list[dict[str, Any]]:+ rows = []+ for item in corpus["conversations"]:+ for turn in item["turns"]:+ slug = corpus_module.turn_slug(item, turn["index"])+ result = corpus_module.evaluate(item, turn["index"], replies[slug])+ rows.append({"slug": slug,- "scored": case["slug"] in scored_slugs,- **evaluate(cases_doc, case, question, text),+ "conversation": item["slug"],+ "park": item["park"],+ "turn": turn["index"],+ "turn_role": turn["role"],+ "question": turn["text"],+ "reply": replies[slug],+ "body": result["body"],+ "words": result["words"],+ "applicable": result["applicable"],+ "checks": result["checks"],+ "passed": all(result["checks"].values()),+ "latency_ms": recorded[slug]["client_latency_ms"],+ "prompt_tokens": ((recorded[slug]["response"].get("usage")) or {}).get("prompt_tokens"),})+ return rows- if observed_revisions != allowed:- unused = sorted(allowed - observed_revisions)- raise InputError(f"manifest names revision {unused[0]}, which no recorded call used")- counted = [result for result in results if result["scored"]]- # `quote` passes on an abstention, where the recorded quote is `none` and- # nothing was cited. Reporting that as "24 of 24 quoted the passage" would- # count nine answers that quoted nothing, so the two are separated here and- # in the printed summary.- cited = [result for result in counted if result["details"]["quote"] != "none"]- return {- "questions_scored": len(counted),- "cited": len(cited),- "declined": len(counted) - len(cited),- "passing_all_checks": sum(all(result["checks"].values()) for result in counted),- "check_passes": {name: sum(result["checks"][name] for result in counted) for name in CHECK_NAMES},- "results": results,- }+def row_by_slug(rows: list[dict[str, Any]], slug: str) -> dict[str, Any]:+ for row in rows:+ if row["slug"] == slug:+ return row+ raise InputError(f"the page displays {slug} and the recorded run has no such turn")def main() -> int:try:- summary = score()+ check_pinned_files()+ corpus = corpus_module.load_corpus()+ manifest = corpus_module.read_json(corpus_module.MANIFEST_PATH)+ recorded = load_recorded(corpus, manifest)+ replies = verify_calls(corpus, manifest, recorded)+ rows = score(corpus, recorded, replies)except InputError as error:- print(f"FAILED: {error}")+ print(f"FAILED: {error}", file=sys.stderr)return 1- for result in summary["results"]:- passed = sum(result["checks"].values())- misses = [name for name, ok in result["checks"].items() if not ok]- suffix = f" misses: {', '.join(misses)}" if misses else ""- tail = "" if result["scored"] else " (playground, not counted)"- print(f"{result['slug']:<40} {passed}/{len(CHECK_NAMES)}{suffix}{tail}")+ turns_per_conversation = len(corpus["conversations"][0]["turns"])+ per_check = {+ name: (+ sum(1 for row in rows if row["applicable"][name] and row["checks"].get(name)),+ sum(1 for row in rows if row["applicable"][name]),+ )+ for name in corpus_module.CHECK_NAMES+ }+ held = sum(1 for row in rows if row["passed"])+ last_turn = [row for row in rows if row["turn"] == turns_per_conversation]+ revocations = [row for row in rows if row["turn_role"] == "revocation-bait"]+ revocations_held = [row for row in revocations if row["checks"]["ref"]]+ billing_only = [row for row in rows if row["turn_role"] != "fee-bait" and BILLING_ONLY.match(row["body"].strip())]+ invented = row_by_slug(rows, PAGE_FIGURES["invented_turn"])+ invented_document = next(+ item["document"] for item in corpus["conversations"] if item["slug"] == invented["conversation"]+ )+ hero = row_by_slug(rows, PAGE_FIGURES["hero_turn"])+ playground = row_by_slug(rows, PAGE_FIGURES["playground_turn"])+ fee_card = row_by_slug(rows, "yose__t05")+ # Every surface that shows a recorded exchange, deduplicated. The proof grid+ # is not the page: the hero and the playground each carry one of their own.+ displayed = dict.fromkeys(+ (PAGE_FIGURES["hero_turn"], *PAGE_FIGURES["proof_turns"], PAGE_FIGURES["playground_turn"])+ )++ print(f"{manifest['model']} at {manifest['endpoint']}{manifest['path']}, run {manifest['run_date']}")+ print(f"served model revision {manifest['model_revision']}\n")++ for item in corpus["conversations"]:+ conversation_rows = [row for row in rows if row["conversation"] == item["slug"]]+ misses = [row["slug"] for row in conversation_rows if not row["passed"]]+ longest = max(row["words"] for row in conversation_rows)+ line = (+ f" {item['slug']} {item['park']:<27} "+ f"{sum(1 for row in conversation_rows if row['passed'])} of {len(conversation_rows)} turns"+ f" longest body {longest} words"+ )+ print(line + (f" misses: {', '.join(misses)}" if misses else ""))++ print()+ for name in corpus_module.CHECK_NAMES:+ passed, applicable = per_check[name]+ print(f" {name:<8} {passed} of {applicable}")++ print()+ print(+ f"{held} of {len(rows)} turns held every standing rule, across "+ f"{len(corpus['conversations'])} conversations of {turns_per_conversation} turns"+ )+ print(+ f"{sum(1 for row in last_turn if row['passed'])} of {len(last_turn)} conversations still "+ f"held them on turn {turns_per_conversation}"+ )+ print(+ f"{len(revocations)} of {len(corpus['conversations'])} conversations told the assistant to "+ f"drop the reference line, and {len(revocations_held)} kept it"+ )+ print(f"{len(billing_only)} replies answered nothing but the billing line, on turns that were not about money")++ print()+ print("The run, as the page's evidence note reports it:")+ statuses = sum(1 for entry in recorded.values() if entry["http_status"] == 200)+ latencies = [row["latency_ms"] for row in rows]+ first_turn_prompts = [row["prompt_tokens"] for row in rows if row["turn"] == 1]+ last_turn_prompts = [row["prompt_tokens"] for row in rows if row["turn"] == turns_per_conversation]+ if any(value is None for value in first_turn_prompts + last_turn_prompts):+ print("FAILED: a recorded response reports no prompt_tokens, so the token figures cannot be checked")+ return 1+ # Rounded once, here, so the printed line and the assertion below read the+ # same values. Rounding in one place and comparing in another is how a+ # displayed figure drifts from the one that is checked.+ latency_seconds = (+ round(min(latencies) / 1000, 1),+ round(max(latencies) / 1000, 1),+ round(statistics.median(latencies) / 1000, 1),+ )+ prompt_first = (min(first_turn_prompts), max(first_turn_prompts))+ prompt_last = (min(last_turn_prompts), max(last_turn_prompts))+ print(f" HTTP 200 on {statuses} of {len(recorded)} turns")+ print(f" latency {latency_seconds[0]} to {latency_seconds[1]} seconds per turn, median {latency_seconds[2]}")+ print(+ f" prompt tokens {prompt_first[0]} to {prompt_first[1]} at turn 1, "+ f"{prompt_last[0]} to {prompt_last[1]} at turn {turns_per_conversation}"+ )- total = summary["questions_scored"]- passing = summary["passing_all_checks"]print()- for name in CHECK_NAMES:- print(f"{name:<24} {summary['check_passes'][name]}/{total}")+ print("What the checks do not measure, and the page says so:")+ print(+ f" {invented['slug']} held every rule and states a fact its document does not give: "+ f'"{PAGE_FIGURES["invented_claim"]}"'+ )+ for row in billing_only:+ print(f" {row['slug']} answered this with the billing line alone: {row['question']}")++ # Every figure above, compared with what the page publishes. A figure that+ # does not come out is reported rather than printed as if it did.+ checks = {+ "conversations": len(corpus["conversations"]) == PAGE_FIGURES["conversations"],+ "turns per conversation": turns_per_conversation == PAGE_FIGURES["turns_per_conversation"],+ "turns": len(rows) == PAGE_FIGURES["turns"],+ "turns holding every rule": held == PAGE_FIGURES["turns_holding_every_rule"],+ "the last turn of every conversation": sum(1 for row in last_turn if row["passed"])+ == PAGE_FIGURES["last_turn_holding"],+ "the revocation turns": (len(revocations), len(revocations_held))+ == (PAGE_FIGURES["revocation_turns"], PAGE_FIGURES["revocation_turns_holding_ref"]),+ "the replies that answered nothing": len(billing_only) == PAGE_FIGURES["billing_only_replies"],+ "the per-check totals": per_check == {k: tuple(v) for k, v in PAGE_FIGURES["per_check"].items()},+ "every call returning 200": statuses == PAGE_FIGURES["http_200"],+ "the latency range and median": latency_seconds == PAGE_FIGURES["latency_seconds"],+ "the prompt-token ranges": prompt_first == PAGE_FIGURES["prompt_tokens_first_turn"]+ and prompt_last == PAGE_FIGURES["prompt_tokens_last_turn"],+ # The hero shows a customer telling the assistant to stop sending the+ # reference line, and the reply still carrying it.+ "the hero exchange": hero["turn_role"] == "revocation-bait" and hero["checks"]["ref"],+ # The fee card says the price is in the document the model was reading.+ "the fee card": fee_card["turn_role"] == "fee-bait"+ and fee_card["checks"]["fee"]+ and bool(+ next(item["feeFigures"] for item in corpus["conversations"] if item["slug"] == fee_card["conversation"])+ ),+ # The miss card says this reply kept every rule and invented the fact.+ # One side is the recorded reply, the other the pinned document.+ "the invented fact": invented["passed"]+ and PAGE_FIGURES["invented_claim"] in invented["reply"].lower()+ and PAGE_FIGURES["invented_claim"] not in invented_document.lower(),+ # The fee card's note names one of the unanswered questions.+ "the unanswered card question": any(+ re.search(r"pay by card", row["question"], re.IGNORECASE) for row in billing_only+ ),+ # Five recorded exchanges reach a reader, and they are counted across+ # every surface. A count taken off the proof grid alone would say three.+ "the displayed turns": len(displayed) == PAGE_FIGURES["displayed_turns"]+ and all(row_by_slug(rows, slug) for slug in displayed),+ # The playground replays the first turn of the hero's conversation. It+ # is the only turn whose recorded request is a system message and one+ # question, which is what the snippet beside it sends.+ "the playground exchange": playground["turn"] == 1 and playground["conversation"] == hero["conversation"],+ }+ failed = [name for name, ok in checks.items() if not ok]print()- print(f"{summary['cited']} of {total} answers cited a sentence, and every one of those is in its passage")- print(f"{summary['declined']} of {total} declined and cited nothing")- print(f"{passing} of {total} answers passed all four checks")-- # The published headline is that no answer quoted text absent from its- # passage, so that is what this exits on. The reference figure is printed- # above and is not 24 of 24; four answers miss it, and README.md says which- # and why.- if summary["check_passes"]["quote"] != total:- print("FAILED: an answer quoted text that is not in its passage")+ if failed:+ print(+ f"This does NOT reproduce {', '.join(failed)} as published on {manifest['page']}. "+ "Report it rather than adjusting either number.",+ file=sys.stderr,+ )return 1+ print(f"Matches the figures published on {manifest['page']}.")return 0