kv-bisect 1.2.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- kv_bisect-1.2.0/CHANGELOG.md +34 -0
- kv_bisect-1.2.0/CONTRIBUTING.md +23 -0
- kv_bisect-1.2.0/LICENSE +21 -0
- kv_bisect-1.2.0/MANIFEST.in +4 -0
- kv_bisect-1.2.0/PKG-INFO +214 -0
- kv_bisect-1.2.0/README.md +180 -0
- kv_bisect-1.2.0/docs/regression-suites.md +83 -0
- kv_bisect-1.2.0/examples/01_quickstart.py +17 -0
- kv_bisect-1.2.0/examples/02_openai_vllm_prefix_cache.py +24 -0
- kv_bisect-1.2.0/examples/03_huggingface_local_kv.py +28 -0
- kv_bisect-1.2.0/examples/04_squad_wrong_answer.py +61 -0
- kv_bisect-1.2.0/examples/05_json_equality/README.md +28 -0
- kv_bisect-1.2.0/examples/05_json_equality/check.py +74 -0
- kv_bisect-1.2.0/examples/05_json_equality/request.json +4 -0
- kv_bisect-1.2.0/examples/rag-chat/passages.json +6 -0
- kv_bisect-1.2.0/examples/rag-chat/request.json +15 -0
- kv_bisect-1.2.0/examples/rag-chat/source.json +22 -0
- kv_bisect-1.2.0/examples/rag-chat/tesla/case.json +85 -0
- kv_bisect-1.2.0/examples/rag-chat/tesla/fix.txt +1 -0
- kv_bisect-1.2.0/examples/rag-chat/tesla/source.json +24 -0
- kv_bisect-1.2.0/examples/rag-chat/tesla/suite.json +7 -0
- kv_bisect-1.2.0/pyproject.toml +66 -0
- kv_bisect-1.2.0/setup.cfg +4 -0
- kv_bisect-1.2.0/src/kv_bisect/__init__.py +62 -0
- kv_bisect-1.2.0/src/kv_bisect/__main__.py +5 -0
- kv_bisect-1.2.0/src/kv_bisect/algorithms.py +663 -0
- kv_bisect-1.2.0/src/kv_bisect/chat_http.py +97 -0
- kv_bisect-1.2.0/src/kv_bisect/cli.py +240 -0
- kv_bisect-1.2.0/src/kv_bisect/hf.py +286 -0
- kv_bisect-1.2.0/src/kv_bisect/oracle.py +592 -0
- kv_bisect-1.2.0/src/kv_bisect/promptfoo_bridge.py +28 -0
- kv_bisect-1.2.0/src/kv_bisect/py.typed +0 -0
- kv_bisect-1.2.0/src/kv_bisect/rag.py +181 -0
- kv_bisect-1.2.0/src/kv_bisect/rag_cli.py +84 -0
- kv_bisect-1.2.0/src/kv_bisect/rag_search.py +157 -0
- kv_bisect-1.2.0/src/kv_bisect/replay.py +208 -0
- kv_bisect-1.2.0/src/kv_bisect/suite.py +130 -0
- kv_bisect-1.2.0/src/kv_bisect/suite_cli.py +102 -0
- kv_bisect-1.2.0/src/kv_bisect/suite_reports.py +58 -0
- kv_bisect-1.2.0/src/kv_bisect/types.py +147 -0
- kv_bisect-1.2.0/src/kv_bisect.egg-info/PKG-INFO +214 -0
- kv_bisect-1.2.0/src/kv_bisect.egg-info/SOURCES.txt +50 -0
- kv_bisect-1.2.0/src/kv_bisect.egg-info/dependency_links.txt +1 -0
- kv_bisect-1.2.0/src/kv_bisect.egg-info/entry_points.txt +2 -0
- kv_bisect-1.2.0/src/kv_bisect.egg-info/requires.txt +11 -0
- kv_bisect-1.2.0/src/kv_bisect.egg-info/top_level.txt +1 -0
- kv_bisect-1.2.0/tests/test_hf_cache.py +73 -0
- kv_bisect-1.2.0/tests/test_kv_bisect.py +454 -0
- kv_bisect-1.2.0/tests/test_rag_chat.py +273 -0
- kv_bisect-1.2.0/tests/test_rag_search.py +115 -0
- kv_bisect-1.2.0/tests/test_replay.py +105 -0
- kv_bisect-1.2.0/tests/test_suite.py +141 -0
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 1.2.0
|
|
4
|
+
|
|
5
|
+
- Capture one verified reproduction with `rag-capture --search first` or investigate alternative reproductions with the existing coverage search.
|
|
6
|
+
- Replay logged Chat Completions requests that use streaming. A complete text answer requires a stop reason and the final SSE marker.
|
|
7
|
+
- Create, validate and run a suite of saved cases. Set an API-call ceiling before running and export JSON, JUnit XML and standalone HTML results.
|
|
8
|
+
- Run the same full and reduced requests in Promptfoo using a generated provider and assertions.
|
|
9
|
+
|
|
10
|
+
## 1.1.0
|
|
11
|
+
|
|
12
|
+
- Reproduce a wrong answer on an OpenAI-compatible Chat Completions service from the original request and a list of passage spans. Export the reduced request and a replay bundle.
|
|
13
|
+
- Check whether removing a passage from the full request changes the answer, and look for other passage sets that reproduce it. Keep observed outcomes and the search limits visible.
|
|
14
|
+
- Replay a captured RAG case against an updated service. Check the full and reduced requests against their expected answers, including cases where only the reduced input should lead to abstention.
|
|
15
|
+
|
|
16
|
+
- Capture a failing JSON request by shrinking one ordered array while preserving its surrounding fields. Reuse the existing search and save a portable, data-only case.
|
|
17
|
+
- Replay the original and reduced requests independently through a caller-supplied checker. Distinguish the target failure, healthy behavior, other outcomes, invalid inputs and checker faults.
|
|
18
|
+
- Limit checker calls and runtime and report repeated observations for each input. The existing `run --cmd` remains a binary text check. When combined with `--contains` it searches merged output, including stderr; use the structured checker when runner errors must abort.
|
|
19
|
+
|
|
20
|
+
## 1.0.1
|
|
21
|
+
|
|
22
|
+
- Verify the full input before searching when a custom oracle has no validated baseline.
|
|
23
|
+
- Preserve the model's sliding-window cache configuration and fall back to full evaluation when the original document prefix is unavailable.
|
|
24
|
+
- Reject missing model answers and blank substring targets. Keep request credentials scoped to the configured endpoint on redirects.
|
|
25
|
+
- Protect the input case from being overwritten by the CLI report.
|
|
26
|
+
- Label modeled token reuse as an estimate, and replay the recorded probes in the bilingual walkthrough.
|
|
27
|
+
|
|
28
|
+
## 1.0.0
|
|
29
|
+
|
|
30
|
+
First stable release. The Python package, CLI and JSON output support ordered context reduction, alternative witnesses, per-search API usage and optional independent verification.
|
|
31
|
+
|
|
32
|
+
- Reject malformed passage lists, empty text-search terms and invalid witness budgets.
|
|
33
|
+
- Count local Hugging Face prefix reuse using the document tape actually sliced during inference.
|
|
34
|
+
- Support the legacy and current Hugging Face model cache interfaces.
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# Maintaining kv-bisect
|
|
2
|
+
|
|
3
|
+
For a chat request, report the model identifier, backend version, expected answer, observed answer and `kv-bisect` version. A small public request and passage list are enough to start. For a custom checker, include the ordered records it reads and the verdict it returned. A replay bundle contains the original input: redact private passages and credentials and verify the sanitized case before posting.
|
|
4
|
+
|
|
5
|
+
## Test a change
|
|
6
|
+
|
|
7
|
+
From the repository root:
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
python -m pip install -e .
|
|
11
|
+
python -m unittest discover -s tests -v
|
|
12
|
+
kv-bisect demo
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Installing the `hf` extra enables the offline Qwen2 test. It uses a randomly initialized model on CPU. The API tests use a local HTTP server.
|
|
16
|
+
|
|
17
|
+
## Release a version
|
|
18
|
+
|
|
19
|
+
Use a patch release for compatible fixes, a minor release for additive features and a major release for breaking changes to documented Python calls, CLI behavior or JSON fields. Keep the core runtime dependency-free. A bug fix should include a regression that fails on the previous release.
|
|
20
|
+
|
|
21
|
+
Update the version in `pyproject.toml`, `src/kv_bisect/__init__.py`, the API client's user agent and the versioned documentation links. Add a changelog entry. Run the core and backend tests, build both distributions and install the wheel in a clean environment. After CI passes on the release commit, tag that commit and attach the wheel and source distribution to the matching GitHub Release.
|
|
22
|
+
|
|
23
|
+
The manual **Publish a GitHub release to PyPI** workflow can distribute those same files using PyPI trusted publishing. Configure the pending publisher on PyPI with repository `Zchu-arch/kv-bisect`, workflow `publish-pypi.yml`, and environment `pypi`. Run the workflow from `main` with the published tag. [PyPI trusted publishing](https://docs.pypi.org/trusted-publishers/creating-a-project-through-oidc/)
|
kv_bisect-1.2.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 kv-bisect Contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
kv_bisect-1.2.0/PKG-INFO
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: kv-bisect
|
|
3
|
+
Version: 1.2.0
|
|
4
|
+
Summary: Debug RAG failures by finding a smaller set of retrieved passages that still reproduces the failure.
|
|
5
|
+
License: MIT
|
|
6
|
+
Project-URL: Repository, https://github.com/Zchu-arch/kv-bisect
|
|
7
|
+
Project-URL: Issues, https://github.com/Zchu-arch/kv-bisect/issues
|
|
8
|
+
Project-URL: Documentation, https://github.com/Zchu-arch/kv-bisect#readme
|
|
9
|
+
Project-URL: Changelog, https://github.com/Zchu-arch/kv-bisect/blob/main/CHANGELOG.md
|
|
10
|
+
Keywords: llm,rag,kv-cache,prefix-caching,prompt-debugging,context-attribution,delta-debugging,vllm,sglang
|
|
11
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Intended Audience :: Science/Research
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Topic :: Software Development :: Debuggers
|
|
20
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
21
|
+
Classifier: Typing :: Typed
|
|
22
|
+
Requires-Python: >=3.10
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
License-File: LICENSE
|
|
25
|
+
Provides-Extra: hf
|
|
26
|
+
Requires-Dist: torch>=2.1.0; extra == "hf"
|
|
27
|
+
Requires-Dist: transformers>=4.44.0; extra == "hf"
|
|
28
|
+
Requires-Dist: accelerate>=0.33.0; extra == "hf"
|
|
29
|
+
Provides-Extra: surrogates
|
|
30
|
+
Requires-Dist: numpy>=1.26.0; extra == "surrogates"
|
|
31
|
+
Provides-Extra: dev
|
|
32
|
+
Requires-Dist: pytest>=8.0.0; extra == "dev"
|
|
33
|
+
Dynamic: license-file
|
|
34
|
+
|
|
35
|
+
# kv-bisect
|
|
36
|
+
|
|
37
|
+
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.
|
|
38
|
+
|
|
39
|
+
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/).
|
|
40
|
+
|
|
41
|
+
## Install
|
|
42
|
+
|
|
43
|
+
Python 3.10 or later:
|
|
44
|
+
|
|
45
|
+
```sh
|
|
46
|
+
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
|
|
47
|
+
kv-bisect demo
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
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.
|
|
51
|
+
|
|
52
|
+
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.
|
|
53
|
+
|
|
54
|
+
## Reproduce a wrong answer from a chat request
|
|
55
|
+
|
|
56
|
+
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.
|
|
57
|
+
|
|
58
|
+
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.
|
|
59
|
+
|
|
60
|
+
```sh
|
|
61
|
+
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
|
|
62
|
+
kv-bisect rag-replay bug.json --base-url http://localhost:8000/v1
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
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)
|
|
66
|
+
|
|
67
|
+
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.
|
|
68
|
+
|
|
69
|
+
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.
|
|
70
|
+
|
|
71
|
+
### Verify a prompt fix
|
|
72
|
+
|
|
73
|
+
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.
|
|
74
|
+
|
|
75
|
+
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:
|
|
76
|
+
|
|
77
|
+
```sh
|
|
78
|
+
kv-bisect rag-replay case.json --base-url http://localhost:8000/v1 --system-prompt-file fix.txt --expect-answer "1874" --reduced-answer "UNKNOWN"
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
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.
|
|
82
|
+
|
|
83
|
+
### Inspect a captured case
|
|
84
|
+
|
|
85
|
+
**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.
|
|
86
|
+
|
|
87
|
+
**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:
|
|
88
|
+
|
|
89
|
+
```python
|
|
90
|
+
import json
|
|
91
|
+
from pathlib import Path
|
|
92
|
+
from kv_bisect.rag import capture_chat, replay_chat
|
|
93
|
+
|
|
94
|
+
request = json.loads(Path("request.json").read_text(encoding="utf-8"))
|
|
95
|
+
passages = json.loads(Path("passages.json").read_text(encoding="utf-8"))
|
|
96
|
+
|
|
97
|
+
def complete(body):
|
|
98
|
+
return client.chat.completions.create(**body).choices[0].message.content
|
|
99
|
+
|
|
100
|
+
case = capture_chat(request, passages, "Seattle Seahawks", complete)
|
|
101
|
+
print(case["diagnosis"]["witnesses"])
|
|
102
|
+
if case["indices"] is not None and case["diagnosis"]["status"] != "unstable_reproduction":
|
|
103
|
+
print(replay_chat(case, complete)["observed"])
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
## Reduce other ordered JSON records
|
|
107
|
+
|
|
108
|
+
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.
|
|
109
|
+
|
|
110
|
+
The [JSON equality example](examples/05_json_equality/) runs locally. From its directory:
|
|
111
|
+
|
|
112
|
+
```sh
|
|
113
|
+
kv-bisect capture request.json --at /data --out case.json -- python check.py
|
|
114
|
+
kv-bisect replay case.json --expect reproduced -- python check.py
|
|
115
|
+
kv-bisect replay case.json --expect healthy -- python check.py --fixed
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
Replay runs both the original batch and the reduced input through the updated validator. This catches changes that fix only the small example.
|
|
119
|
+
|
|
120
|
+
**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.
|
|
121
|
+
|
|
122
|
+
| Verdict | Meaning |
|
|
123
|
+
| --- | --- |
|
|
124
|
+
| `reproduced` | This specific failure occurred. |
|
|
125
|
+
| `healthy` | The application satisfied the expected behavior for this input. |
|
|
126
|
+
| `other` | A different or unexpected result occurred. |
|
|
127
|
+
| `invalid` | Deleting records made this input inapplicable to the check. |
|
|
128
|
+
|
|
129
|
+
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.
|
|
130
|
+
|
|
131
|
+
**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.
|
|
132
|
+
|
|
133
|
+
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.
|
|
134
|
+
|
|
135
|
+
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.
|
|
136
|
+
|
|
137
|
+
## Use your own check
|
|
138
|
+
|
|
139
|
+
```python
|
|
140
|
+
from kv_bisect import bisect
|
|
141
|
+
|
|
142
|
+
passages = [
|
|
143
|
+
"Charter: Headquarters is in Linz.",
|
|
144
|
+
"Interim notice: Headquarters is in Graz.",
|
|
145
|
+
"Menu: Lunch starts at noon.",
|
|
146
|
+
"Retraction: The interim notice is cancelled.",
|
|
147
|
+
]
|
|
148
|
+
|
|
149
|
+
def reproduces_linz(context):
|
|
150
|
+
charter = "Headquarters is in Linz." in context
|
|
151
|
+
notice = "Headquarters is in Graz." in context
|
|
152
|
+
retracted = "interim notice is cancelled" in context
|
|
153
|
+
return charter and (not notice or retracted)
|
|
154
|
+
|
|
155
|
+
result = bisect(passages, check_fn=reproduces_linz)
|
|
156
|
+
print(result.format_minimal_context())
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
```text
|
|
160
|
+
[Document 1]
|
|
161
|
+
Charter: Headquarters is in Linz.
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
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.
|
|
165
|
+
|
|
166
|
+
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.
|
|
167
|
+
|
|
168
|
+
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.
|
|
169
|
+
|
|
170
|
+
## Run a saved case from the command line
|
|
171
|
+
|
|
172
|
+
Save the following as `case.json`:
|
|
173
|
+
|
|
174
|
+
```json
|
|
175
|
+
{
|
|
176
|
+
"chunks": [
|
|
177
|
+
"Project Aurora uses the Zurich lab.",
|
|
178
|
+
"The office opens at nine.",
|
|
179
|
+
"The Zurich lab's access code is R17."
|
|
180
|
+
]
|
|
181
|
+
}
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
```sh
|
|
185
|
+
kv-bisect run case.json --contains "Aurora && R17" --json-out result.json
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
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.
|
|
189
|
+
|
|
190
|
+
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.
|
|
191
|
+
|
|
192
|
+
## Run a passage list against a model
|
|
193
|
+
|
|
194
|
+
For a running OpenAI-compatible Chat Completions server, replace `YOUR_SERVED_MODEL` with the model ID configured on that server:
|
|
195
|
+
|
|
196
|
+
```sh
|
|
197
|
+
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
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
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`.
|
|
201
|
+
|
|
202
|
+
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.
|
|
203
|
+
|
|
204
|
+
## Read the cache numbers
|
|
205
|
+
|
|
206
|
+
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.
|
|
207
|
+
|
|
208
|
+
## Examples and license
|
|
209
|
+
|
|
210
|
+
- [Python quickstart](examples/01_quickstart.py)
|
|
211
|
+
- [OpenAI-compatible endpoint example](examples/02_openai_vllm_prefix_cache.py)
|
|
212
|
+
- [Interactive walkthrough](docs/index.html) — open the file locally and step through either example in English or Chinese.
|
|
213
|
+
|
|
214
|
+
See the [release history](CHANGELOG.md) and [maintenance guide](CONTRIBUTING.md). Released under the [MIT License](LICENSE).
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
# kv-bisect
|
|
2
|
+
|
|
3
|
+
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.
|
|
4
|
+
|
|
5
|
+
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/).
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
Python 3.10 or later:
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
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
|
|
13
|
+
kv-bisect demo
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
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.
|
|
17
|
+
|
|
18
|
+
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.
|
|
19
|
+
|
|
20
|
+
## Reproduce a wrong answer from a chat request
|
|
21
|
+
|
|
22
|
+
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.
|
|
23
|
+
|
|
24
|
+
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.
|
|
25
|
+
|
|
26
|
+
```sh
|
|
27
|
+
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
|
|
28
|
+
kv-bisect rag-replay bug.json --base-url http://localhost:8000/v1
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
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)
|
|
32
|
+
|
|
33
|
+
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.
|
|
34
|
+
|
|
35
|
+
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.
|
|
36
|
+
|
|
37
|
+
### Verify a prompt fix
|
|
38
|
+
|
|
39
|
+
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.
|
|
40
|
+
|
|
41
|
+
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:
|
|
42
|
+
|
|
43
|
+
```sh
|
|
44
|
+
kv-bisect rag-replay case.json --base-url http://localhost:8000/v1 --system-prompt-file fix.txt --expect-answer "1874" --reduced-answer "UNKNOWN"
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
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.
|
|
48
|
+
|
|
49
|
+
### Inspect a captured case
|
|
50
|
+
|
|
51
|
+
**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.
|
|
52
|
+
|
|
53
|
+
**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:
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
import json
|
|
57
|
+
from pathlib import Path
|
|
58
|
+
from kv_bisect.rag import capture_chat, replay_chat
|
|
59
|
+
|
|
60
|
+
request = json.loads(Path("request.json").read_text(encoding="utf-8"))
|
|
61
|
+
passages = json.loads(Path("passages.json").read_text(encoding="utf-8"))
|
|
62
|
+
|
|
63
|
+
def complete(body):
|
|
64
|
+
return client.chat.completions.create(**body).choices[0].message.content
|
|
65
|
+
|
|
66
|
+
case = capture_chat(request, passages, "Seattle Seahawks", complete)
|
|
67
|
+
print(case["diagnosis"]["witnesses"])
|
|
68
|
+
if case["indices"] is not None and case["diagnosis"]["status"] != "unstable_reproduction":
|
|
69
|
+
print(replay_chat(case, complete)["observed"])
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
## Reduce other ordered JSON records
|
|
73
|
+
|
|
74
|
+
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.
|
|
75
|
+
|
|
76
|
+
The [JSON equality example](examples/05_json_equality/) runs locally. From its directory:
|
|
77
|
+
|
|
78
|
+
```sh
|
|
79
|
+
kv-bisect capture request.json --at /data --out case.json -- python check.py
|
|
80
|
+
kv-bisect replay case.json --expect reproduced -- python check.py
|
|
81
|
+
kv-bisect replay case.json --expect healthy -- python check.py --fixed
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
Replay runs both the original batch and the reduced input through the updated validator. This catches changes that fix only the small example.
|
|
85
|
+
|
|
86
|
+
**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.
|
|
87
|
+
|
|
88
|
+
| Verdict | Meaning |
|
|
89
|
+
| --- | --- |
|
|
90
|
+
| `reproduced` | This specific failure occurred. |
|
|
91
|
+
| `healthy` | The application satisfied the expected behavior for this input. |
|
|
92
|
+
| `other` | A different or unexpected result occurred. |
|
|
93
|
+
| `invalid` | Deleting records made this input inapplicable to the check. |
|
|
94
|
+
|
|
95
|
+
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.
|
|
96
|
+
|
|
97
|
+
**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.
|
|
98
|
+
|
|
99
|
+
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.
|
|
100
|
+
|
|
101
|
+
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.
|
|
102
|
+
|
|
103
|
+
## Use your own check
|
|
104
|
+
|
|
105
|
+
```python
|
|
106
|
+
from kv_bisect import bisect
|
|
107
|
+
|
|
108
|
+
passages = [
|
|
109
|
+
"Charter: Headquarters is in Linz.",
|
|
110
|
+
"Interim notice: Headquarters is in Graz.",
|
|
111
|
+
"Menu: Lunch starts at noon.",
|
|
112
|
+
"Retraction: The interim notice is cancelled.",
|
|
113
|
+
]
|
|
114
|
+
|
|
115
|
+
def reproduces_linz(context):
|
|
116
|
+
charter = "Headquarters is in Linz." in context
|
|
117
|
+
notice = "Headquarters is in Graz." in context
|
|
118
|
+
retracted = "interim notice is cancelled" in context
|
|
119
|
+
return charter and (not notice or retracted)
|
|
120
|
+
|
|
121
|
+
result = bisect(passages, check_fn=reproduces_linz)
|
|
122
|
+
print(result.format_minimal_context())
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
```text
|
|
126
|
+
[Document 1]
|
|
127
|
+
Charter: Headquarters is in Linz.
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
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.
|
|
131
|
+
|
|
132
|
+
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.
|
|
133
|
+
|
|
134
|
+
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.
|
|
135
|
+
|
|
136
|
+
## Run a saved case from the command line
|
|
137
|
+
|
|
138
|
+
Save the following as `case.json`:
|
|
139
|
+
|
|
140
|
+
```json
|
|
141
|
+
{
|
|
142
|
+
"chunks": [
|
|
143
|
+
"Project Aurora uses the Zurich lab.",
|
|
144
|
+
"The office opens at nine.",
|
|
145
|
+
"The Zurich lab's access code is R17."
|
|
146
|
+
]
|
|
147
|
+
}
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
```sh
|
|
151
|
+
kv-bisect run case.json --contains "Aurora && R17" --json-out result.json
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
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.
|
|
155
|
+
|
|
156
|
+
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.
|
|
157
|
+
|
|
158
|
+
## Run a passage list against a model
|
|
159
|
+
|
|
160
|
+
For a running OpenAI-compatible Chat Completions server, replace `YOUR_SERVED_MODEL` with the model ID configured on that server:
|
|
161
|
+
|
|
162
|
+
```sh
|
|
163
|
+
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
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
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`.
|
|
167
|
+
|
|
168
|
+
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.
|
|
169
|
+
|
|
170
|
+
## Read the cache numbers
|
|
171
|
+
|
|
172
|
+
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.
|
|
173
|
+
|
|
174
|
+
## Examples and license
|
|
175
|
+
|
|
176
|
+
- [Python quickstart](examples/01_quickstart.py)
|
|
177
|
+
- [OpenAI-compatible endpoint example](examples/02_openai_vllm_prefix_cache.py)
|
|
178
|
+
- [Interactive walkthrough](docs/index.html) — open the file locally and step through either example in English or Chinese.
|
|
179
|
+
|
|
180
|
+
See the [release history](CHANGELOG.md) and [maintenance guide](CONTRIBUTING.md). Released under the [MIT License](LICENSE).
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
# Run RAG regressions in CI
|
|
2
|
+
|
|
3
|
+
A suite replays saved Chat Completions requests against a model endpoint. Each case checks the full input and a verified reduced input. Commit the manifest, its bundles and any revised prompts together. A bundle includes the original request and passages, so choose fixtures you can keep in that repository.
|
|
4
|
+
|
|
5
|
+
## Try the worked example
|
|
6
|
+
|
|
7
|
+
The wheel includes the [Tesla example](../examples/rag-chat/tesla/) with a case, a replacement system prompt and a two-case manifest. Create it in a new directory and check it offline.
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
kv-bisect suite example tesla-demo
|
|
11
|
+
cd tesla-demo
|
|
12
|
+
kv-bisect suite check suite.json --max-calls 8
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
With a server hosting the model specified by the fixture, run both cases and write reports. Set `OPENAI_API_KEY` if the endpoint requires authentication.
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
kv-bisect suite run suite.json --base-url http://localhost:8000/v1 --max-calls 8 --junit results.xml --html results.html --json-out results.json
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
The original prompt case expects `1879` on both requests. The revised prompt case expects `1874` on the full request and `UNKNOWN` on the reduced input. The default of two fresh calls per input makes eight requests in total.
|
|
22
|
+
|
|
23
|
+
## Add your own cases
|
|
24
|
+
|
|
25
|
+
Capture a failure using `rag-capture`. Choose `--search first` when you need one checked reproduction quickly, or `--search coverage` when you need to inspect other reproductions and the answers after individual deletions. Then initialize a suite from one or more saved bundles.
|
|
26
|
+
|
|
27
|
+
```sh
|
|
28
|
+
kv-bisect suite init regressions/suite.json regressions/billing.json regressions/search.json
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
The generated expectations reproduce the recorded wrong answers. Edit them to verify a change. This example tests a correct answer on the full request and abstention when evidence is missing.
|
|
32
|
+
|
|
33
|
+
```json
|
|
34
|
+
{
|
|
35
|
+
"format": "kv-bisect/suite-v1",
|
|
36
|
+
"cases": [
|
|
37
|
+
{
|
|
38
|
+
"name": "Returns / revised prompt",
|
|
39
|
+
"bundle": "billing.json",
|
|
40
|
+
"system_prompt_file": "revised.txt",
|
|
41
|
+
"expect_answer": "30 days",
|
|
42
|
+
"reduced_answer": "UNKNOWN"
|
|
43
|
+
}
|
|
44
|
+
]
|
|
45
|
+
}
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Use unique case names. Paths resolve under the manifest's directory. Omit `system_prompt_file` to keep the original prompt. Omit `reduced_answer` to use `expect_answer` for both inputs. To test another deployment, set `--base-url` or override every model ID with `--model`. Matching ignores case and outer whitespace. Each expected value must be a string, including years and numeric IDs.
|
|
49
|
+
|
|
50
|
+
## Pull-request checks
|
|
51
|
+
|
|
52
|
+
On a runner that can reach the endpoint, add the following steps after checkout and Python setup. Set the repository variable `RAG_BASE_URL` and, for an authenticated server, the secret `RAG_API_KEY`. Run private-endpoint checks only on trusted changes.
|
|
53
|
+
|
|
54
|
+
```yaml
|
|
55
|
+
- run: 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
|
|
56
|
+
- run: kv-bisect suite run regressions/suite.json --base-url "$RAG_BASE_URL" --max-calls 32 --junit results.xml --html results.html
|
|
57
|
+
shell: bash
|
|
58
|
+
env:
|
|
59
|
+
RAG_BASE_URL: ${{ vars.RAG_BASE_URL }}
|
|
60
|
+
OPENAI_API_KEY: ${{ secrets.RAG_API_KEY }}
|
|
61
|
+
- uses: actions/upload-artifact@v4
|
|
62
|
+
if: always()
|
|
63
|
+
with:
|
|
64
|
+
name: rag-results
|
|
65
|
+
path: |
|
|
66
|
+
results.xml
|
|
67
|
+
results.html
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
An exit code of 0 means every case passed, 1 means at least one answer differed, and 2 means a configuration or execution error occurred. All cases are validated before the first model call. During execution, an endpoint error marks its case as an error and later cases still run. The HTML and JSON reports include observed answers; the JUnit report includes details for failures and errors.
|
|
71
|
+
|
|
72
|
+
## Use Promptfoo
|
|
73
|
+
|
|
74
|
+
Export a suite into a new directory. The export writes the requests, a Python provider and a Promptfoo config. Each case becomes two tests. Saved model parameters, system-prompt overrides, passage order and answer matching are preserved.
|
|
75
|
+
|
|
76
|
+
```sh
|
|
77
|
+
kv-bisect suite export-promptfoo regressions/suite.json --out promptfoo-regressions
|
|
78
|
+
cd promptfoo-regressions
|
|
79
|
+
export OPENAI_BASE_URL=http://localhost:8000/v1
|
|
80
|
+
promptfoo eval -c promptfooconfig.json --no-cache --repeat 2
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
Use the Python environment where `kv-bisect` is installed. Set `PROMPTFOO_PYTHON` to its executable if Promptfoo uses another interpreter. On PowerShell, set the endpoint with `$env:OPENAI_BASE_URL='http://localhost:8000/v1'`. The export contains the full requests. Endpoint addresses and authorization headers are supplied at runtime. [Promptfoo Python providers](https://www.promptfoo.dev/docs/providers/python/)
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""3-line quickstart: isolate the minimal culpable chunks inside a RAG prompt."""
|
|
2
|
+
|
|
3
|
+
from kv_bisect import bisect
|
|
4
|
+
|
|
5
|
+
chunks = [
|
|
6
|
+
"Charter: Headquarters is permanently located in Linz.",
|
|
7
|
+
"Interim Memo: Temporarily route mail to Graz.", # spoils Doc 1 unless Doc 4 is present
|
|
8
|
+
"Lunch Notice: Cafeteria closes at 2pm on Friday.",
|
|
9
|
+
"Retraction: The Graz interim memo is cancelled; follow the Charter.",
|
|
10
|
+
]
|
|
11
|
+
|
|
12
|
+
result = bisect(
|
|
13
|
+
chunks,
|
|
14
|
+
check_fn=lambda ctx: ("Linz" in ctx) and ("Graz." not in ctx or "cancelled" in ctx),
|
|
15
|
+
)
|
|
16
|
+
print(result.summary())
|
|
17
|
+
print("\nMinimal reproducible context:\n" + result.format_minimal_context(chunks))
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""Run kv-bisect against vLLM (`--enable-prefix-caching`), SGLang, OpenAI, or DeepSeek.
|
|
2
|
+
|
|
3
|
+
Keeping fixed `[Document i]` headers on the left preserves byte-identical prompt prefixes across
|
|
4
|
+
probes for prefix-caching servers when prompts exceed the server's block threshold on a warm worker.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import os
|
|
8
|
+
from kv_bisect import OpenAICompatibleOracle, bisect
|
|
9
|
+
|
|
10
|
+
chunks = [f"Routine compliance note #{i + 1}." for i in range(32)]
|
|
11
|
+
chunks[1] = "Clause 4.2: Project Nimbus is governed by Swiss law."
|
|
12
|
+
chunks[19] = "Addendum B: Disputes under Swiss law are arbitrated in Geneva."
|
|
13
|
+
|
|
14
|
+
if not os.environ.get("OPENAI_API_KEY"):
|
|
15
|
+
print("Set OPENAI_API_KEY (and optional OPENAI_BASE_URL for vLLM/SGLang/DeepSeek) to run live.")
|
|
16
|
+
else:
|
|
17
|
+
oracle = OpenAICompatibleOracle(
|
|
18
|
+
chunks,
|
|
19
|
+
query="In which city are Project Nimbus disputes arbitrated?",
|
|
20
|
+
model=os.environ.get("KV_BISECT_MODEL", "gpt-4o-mini"),
|
|
21
|
+
expected_substring="Geneva",
|
|
22
|
+
)
|
|
23
|
+
result = bisect(oracle=oracle, mode="bisection")
|
|
24
|
+
print(result.summary())
|