Metadata-Version: 2.4
Name: kv-bisect
Version: 1.2.0
Summary: Debug RAG failures by finding a smaller set of retrieved passages that still reproduces the failure.
License: MIT
Project-URL: Repository, https://github.com/Zchu-arch/kv-bisect
Project-URL: Issues, https://github.com/Zchu-arch/kv-bisect/issues
Project-URL: Documentation, https://github.com/Zchu-arch/kv-bisect#readme
Project-URL: Changelog, https://github.com/Zchu-arch/kv-bisect/blob/main/CHANGELOG.md
Keywords: llm,rag,kv-cache,prefix-caching,prompt-debugging,context-attribution,delta-debugging,vllm,sglang
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Debuggers
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Typing :: Typed
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: hf
Requires-Dist: torch>=2.1.0; extra == "hf"
Requires-Dist: transformers>=4.44.0; extra == "hf"
Requires-Dist: accelerate>=0.33.0; extra == "hf"
Provides-Extra: surrogates
Requires-Dist: numpy>=1.26.0; extra == "surrogates"
Provides-Extra: dev
Requires-Dist: pytest>=8.0.0; extra == "dev"
Dynamic: license-file

# 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](https://rajpurkar.github.io/SQuAD-explorer/) 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](examples/rag-chat/) or [try the offline walkthrough in your browser](https://zchu-arch.github.io/kv-bisect/).

## Install

Python 3.10 or later:

```sh
python -m pip install https://github.com/Zchu-arch/kv-bisect/releases/download/v1.2.0/kv_bisect-1.2.0-py3-none-any.whl
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](docs/regression-suites.md). Existing Promptfoo projects can import the same full and reduced requests.

## 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](https://raw.githubusercontent.com/Zchu-arch/kv-bisect/v1.2.0/examples/rag-chat/request.json) and [passages.json](https://raw.githubusercontent.com/Zchu-arch/kv-bisect/v1.2.0/examples/rag-chat/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.

```sh
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](https://creativecommons.org/licenses/by-sa/4.0/). [Dataset and model details](examples/rag-chat/source.json)

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](https://raw.githubusercontent.com/Zchu-arch/kv-bisect/v1.2.0/examples/rag-chat/tesla/case.json) and [fix.txt](https://raw.githubusercontent.com/Zchu-arch/kv-bisect/v1.2.0/examples/rag-chat/tesla/fix.txt) into the same directory and point replay at the same model:

```sh
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:

```python
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](examples/05_json_equality/) runs locally. From its directory:

```sh
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

```python
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())
```

```text
[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`:

```json
{
  "chunks": [
    "Project Aurora uses the Zurich lab.",
    "The office opens at nine.",
    "The Zurich lab's access code is R17."
  ]
}
```

```sh
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:

```sh
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](examples/03_huggingface_local_kv.py). 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](examples/01_quickstart.py)
- [OpenAI-compatible endpoint example](examples/02_openai_vllm_prefix_cache.py)
- [Interactive walkthrough](docs/index.html) — open the file locally and step through either example in English or Chinese.

See the [release history](CHANGELOG.md) and [maintenance guide](CONTRIBUTING.md). Released under the [MIT License](LICENSE).
