kv-bisect
Find which retrieved passages reproduce a wrong answer from your RAG service. Give kv-bisect the actual Chat Completions request, the passage text and the answer you want to reproduce. It reruns the request with passages removed and saves a smaller case you can replay after a fix.
In a SQuAD example, Qwen was asked who lost to the Broncos. The four passages included the correct answer, Pittsburgh Steelers, but the model said Seattle Seahawks. Testing all 16 subsets revealed two different pairs that could reproduce the wrong answer: original passages 1 and 3, and 1 and 4. Download the case inputs or try the offline walkthrough in your browser.
Install
Python 3.10 or later:
python -m pip install kv-bisect
kv-bisect demo
The demo is local and deterministic. It needs no model, GPU or API key. To install from a source checkout, run python -m pip install . from the repository root.
For a team regression suite, run cases locally or in CI. Existing Promptfoo projects can import the same full and reduced requests.
Reduce a failing Promptfoo test
Already have a failing eval? Reuse its prompt, provider and assertion. From your Promptfoo project with the npm package installed locally:
python -m pip install "kv-bisect[promptfoo]"
kv-bisect promptfoo-reduce promptfooconfig.yaml --results failed.json --row 1 --var context --write-back
Add --match output to track the exact wrong answer from the failed row, including capitalization, spaces and punctuation. The JSON report shows the outputs for the full, empty and reduced inputs. If the original is already minimal, the command reports the comparison and leaves the suite as it is.
failed.json is the JSON output of promptfoo eval -o failed.json. Choose the failing row (starting at 1) and the test variable containing its passages. You can also select by test description using --test "Current refund window". The original stays in the suite and the smaller test runs alongside it on the next ordinary Promptfoo eval. Worked example and supported configurations
Reproduce a wrong answer from a chat request
Save the JSON body your application sent to an OpenAI-compatible Chat Completions endpoint as request.json. Use a request with one text completion. Both ordinary responses and SSE streams with a completed text answer are supported. For a custom prompt format, save the passage spans as a JSON array of strings in passages.json. Each span must appear exactly once, in the listed order, within the same message's text. Include the label or separator that should be removed with each passage. Use --message-index to select a message by its zero-based position if multiple messages match.
To try the worked example, download request.json and passages.json into one directory. The request specifies Qwen/Qwen2.5-0.5B-Instruct. Use an endpoint serving that model or use a captured request and known wrong answer from your own service.
kv-bisect rag-capture request.json --passages passages.json --wrong-answer "Seattle Seahawks" --base-url http://localhost:8000/v1 --out bug.json --reduced-out reduced.json
kv-bisect rag-replay bug.json --base-url http://localhost:8000/v1
If your prompt already uses standalone [Document N] headers followed by a final Question: ... line, you can omit --passages passages.json. For an authenticated service set OPENAI_API_KEY for that endpoint. The example passages come from SQuAD 1.1 by Rajpurkar et al., under CC BY-SA 4.0. Dataset and model details
The first command sends candidate requests to the selected endpoint, keeping the surrounding prompt, other messages and request parameters intact. reduced.json is a Chat Completions request you can inspect or send directly. bug.json holds the full input for replay. Answer matching ignores case and leading or trailing whitespace. Punctuation and wording count. Different model weights, templates or decoding settings may change the original answer.
Use --search first to get one verified reproduction at lower cost. The default --search coverage also looks for alternative passage sets and checks single deletions of the full request. Capture can exhaustively check small inputs when the budget permits. This four-passage example takes 18 calls: 16 subsets plus one fresh check each for the full and chosen reduced input. The default --max-calls 128 permits exhaustive checks through six passages. Seven passages require 130 calls for exhaustive coverage with the default confirmation count. A budget-limited search can return partial coverage. An unstable or unreproduced failure does not produce a new bundle. Replay checks each of its two inputs twice by default.
Verify a prompt fix
On a second SQuAD question about the year Nikola Tesla evaded the draft, the same Qwen model answered 1879 with all four passages. Passage 4 alone reproduced the wrong year. Changing only the system instruction made the model answer 1874 on the full request and UNKNOWN on the single passage, which lacked the supporting evidence. The revised instruction asks the model to check the actor and action against the same piece of evidence.
To repeat this check, download the captured case.json and fix.txt into the same directory and point replay at the same model:
kv-bisect rag-replay case.json --base-url http://localhost:8000/v1 --system-prompt-file fix.txt --expect-answer "1874" --reduced-answer "UNKNOWN"
With just --expect-answer, both requests must return that answer. --system-prompt-file replaces the single, separate system message for replay. Other messages and parameters stay intact. Set --model to test a different model identifier. Before sharing a bundle, inspect the full request for private passages, instructions or customer data.
Inspect a captured case
Read the result. The passages that reproduce an answer together can differ from the passages whose removal changes the answer in the full request. Inspect diagnosis.witnesses for reproducing sets and diagnosis.full_deletions for answers obtained after omitting one passage from the original request. Both use zero-based indices. The report says whether all witnesses and all full-input deletions were checked. A cleared wrong answer may still be a different wrong answer.
Use your existing Python client. Pass a function that accepts the Chat Completions request body and returns the assistant's answer text. For an already-configured OpenAI-compatible Python client:
import json
from pathlib import Path
from kv_bisect.rag import capture_chat, replay_chat
request = json.loads(Path("request.json").read_text(encoding="utf-8"))
passages = json.loads(Path("passages.json").read_text(encoding="utf-8"))
def complete(body):
return client.chat.completions.create(**body).choices[0].message.content
case = capture_chat(request, passages, "Seattle Seahawks", complete)
print(case["diagnosis"]["witnesses"])
if case["indices"] is not None and case["diagnosis"]["status"] != "unstable_reproduction":
print(replay_chat(case, complete)["observed"])
Reduce other ordered JSON records
Use capture and replay with your own checker. Start with the JSON request your application actually evaluated and point to the ordered array you want to shrink. For a RAG request this might be the passages that reached the model. For a validator it might be the batch of records it processed. Everything outside that array keeps its JSON value. Retained elements keep their order, types, and any IDs already present. Array positions in the reduced request shift as usual.
The JSON equality example runs locally. From its directory:
kv-bisect capture request.json --at /data --out case.json -- python check.py
kv-bisect replay case.json --expect reproduced -- python check.py
kv-bisect replay case.json --expect healthy -- python check.py --fixed
Replay runs both the original batch and the reduced input through the updated validator. This catches changes that fix only the small example.
Write a checker. The command after -- receives one JSON request on standard input and returns one word on standard output with process exit code 0. Write diagnostics to standard error. Each invocation starts a new process. For an expensive model, have the checker call your already-running service.
| Verdict | Meaning |
|---|---|
reproduced |
This specific failure occurred. |
healthy |
The application satisfied the expected behavior for this input. |
other |
A different or unexpected result occurred. |
invalid |
Deleting records made this input inapplicable to the check. |
Only reproduced keeps a candidate during search. Nonzero checker exits, timeouts and malformed output stop the command with exit code 2. For replay, exit 0 means both inputs met the expectation on every attempt. Exit 1 means a verdict differed. The JSON output reports observations separately for the original and reduced requests. Define what healthy means per input: after a RAG fix, the full request might need the correct answer while a reduced request missing the evidence should abstain.
Capture and share. The bundle holds the original request, the array's JSON Pointer, the retained zero-based positions, and check counts. It contains no checker command. Give a colleague the bundle and the trusted checker, application version and environment details needed to reproduce the run. A bundle contains the full request even when only two records remain; use shareable data or redact and recapture before sending it.
Use an empty pointer for a top-level array; /a~1b selects the key a/b. Group records that must travel together before capture, e.g. a tool call and its result. If IDs are positional in the application, make them explicit in records before capture. The tool preserves JSON values, not original wire bytes. Starting from logs requires identifying the records actually consumed.
Capture and replay each make two fresh checks per final input by default. Change --repeat for more observations, --timeout for the per-call limit, and capture --max-calls for the total call budget (default 256). Capture aborts if fresh final checks disagree with the search. Repeated agreement is observational evidence. Invalid subsets, nondeterminism and differences in the application environment limit what the reduced case can establish.
Use your own check
from kv_bisect import bisect
passages = [
"Charter: Headquarters is in Linz.",
"Interim notice: Headquarters is in Graz.",
"Menu: Lunch starts at noon.",
"Retraction: The interim notice is cancelled.",
]
def reproduces_linz(context):
charter = "Headquarters is in Linz." in context
notice = "Headquarters is in Graz." in context
retracted = "interim notice is cancelled" in context
return charter and (not notice or retracted)
result = bisect(passages, check_fn=reproduces_linz)
print(result.format_minimal_context())
[Document 1]
Charter: Headquarters is in Linz.
For a real failure, replace reproduces_linz with a function that runs your pipeline on the supplied context and returns True when the behavior recurs. Keep the question and model settings fixed. The full input must pass your check. If the empty context also passes, the result contains zero passages.
For a deterministic check, the result is 1-minimal: it passes, and removing any one retained passage makes it fail. Other passing sets can exist, including smaller ones. To look for alternatives, use bisect(..., find_all=True, max_witnesses=4) and inspect result.all_witnesses. Python indices start at zero; result.one_based_docs matches the document numbers printed in the context.
Enumeration stops at the witness budget. If removing material can turn a failing context into a passing one, the search can also miss alternative sets when it skips a failing branch.
Run a saved case from the command line
Save the following as case.json:
{
"chunks": [
"Project Aurora uses the Zurich lab.",
"The office opens at nine.",
"The Zurich lab's access code is R17."
]
}
kv-bisect run case.json --contains "Aurora && R17" --json-out result.json
This local text check keeps documents 1 and 3. The JSON report includes their original numbers, zero-based indices, and text. For an existing regression script, use kv-bisect run case.json --cmd "python reproduce.py". The script reads the candidate file at the path in KV_BISECT_CONTEXT_FILE and exits with code 0 when it reproduces the behavior.
With --find-all, the terminal lists the document numbers of each set found. The JSON field all_witnesses contains the same sets as zero-based indices, matching Python’s result.all_witnesses. For example, [[0], [2]] means that document 1 alone and document 3 alone both pass the check.
Run a passage list against a model
For a running OpenAI-compatible Chat Completions server, replace YOUR_SERVED_MODEL with the model ID configured on that server:
kv-bisect run case.json --model YOUR_SERVED_MODEL --base-url http://localhost:8000/v1 --query "What access code does Project Aurora need?" --contains "R17" --standalone-seal
With --model, the check looks for the substring in the model's answer. The client sends the selected passages and question to the configured endpoint. Set OPENAI_API_KEY to the credential intended for that endpoint. With --standalone-seal, the default API client issues additional verification requests. The Python result exposes the verification mode and call count as standalone_mode and standalone_calls.
For a local Hugging Face causal language model, run python -m pip install ".[hf]" from the repository root and see the local model example. It scores candidate contexts using a sliced KV cache when all layers retain the original prefix. For rolling or truncated caches it evaluates the full candidate. The offline compatibility tests use Qwen2 on CPU.
Read the cache numbers
The demo's prefix-reuse numbers estimate how many passage tokens a cache could reuse under its accounting model. Actual cache hits depend on the server. The API-reported cache line and JSON fields server_cached_tokens and server_prompt_tokens cover the current search, including its verification requests. The one-time full-context request used to initialize the oracle is excluded. The counters stay at zero when the server omits usage.
Examples and license
- Python quickstart
- OpenAI-compatible endpoint example
- Interactive walkthrough — open the file locally and step through either example in English or Chinese.
See the release history and maintenance guide. Released under the MIT License.
Metadata
Release files for kv-bisect 1.4.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| kv_bisect-1.4.0.tar.gz | 91.2 kB | With provenance | Details for kv_bisect-1.4.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| kv_bisect-1.4.0-py3-none-any.whl | Python 3 | none | any | Details for kv_bisect-1.4.0-py3-none-any.whl |
Total release size: 154.6 kB
Release files / kv_bisect-1.4.0.tar.gz
| Download URL | kv_bisect-1.4.0.tar.gz |
|---|---|
| Size | 91.2 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
9f612a33ae56d8d38c6a0e1e4de19987326328358503cc2d9345295f4c9b297b
|
|
BLAKE2b-256 checksum How to use checksums |
7c5eea241925ef46e799d98db07f996f90c52524e2231682502a9ab782092e29
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 4, 2026.
Transparency logRelease files / kv_bisect-1.4.0-py3-none-any.whl
| Download URL | kv_bisect-1.4.0-py3-none-any.whl |
|---|---|
| Size | 63.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
6831f5028e704aaefca9e11fedba8cdbb2adcaf08ad51a8935795d229614d58d
|
|
BLAKE2b-256 checksum How to use checksums |
45493b532b8743ae693fcd3ce02177bc677bfeefaffc1b6375a573eb9a5afaec
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 4, 2026.
Transparency logSecurity for kv-bisect 1.4.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for kv_bisect-1.4.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 4, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.