Sieve
____ ___ ______ _______
/ ___|_ _| ____\ \ / / ____|
\___ \| || _| \ \ / /| _|
___) | || |___ \ V / | |___
|____/___|_____| \_/ |_____|
Less noise. Better retrieval.
Sift the signal from your retrieval pipeline.
👉 New to Sieve? Take the 5-Minute Sieve Test Drive or run sieve demo in your terminal!
Sieve is a lightweight, post-retrieval context optimizer for Retrieval-Augmented Generation (RAG). It runs locally between your retriever and your LLM, evaluating retrieved sentences with a local cross-encoder to prune irrelevant noise before generation.
Retriever ──► [ Retrieved Chunks ] ──► Sieve (Local Cross-Encoder) ──► [ Pruned Context ] ──► LLM
Your vector database over-retrieves by design: embedding top-k similarity search returns large blocks of text where often only a few sentences answer the query. Sieve removes the noise, preserves document metadata, and passes a physically smaller, denser prompt to your downstream model.
Why Sieve?
Every irrelevant token retrieved into your prompt creates measurable friction:
- Cost: You pay per input token on hosted APIs (OpenAI, Anthropic, Gemini, Groq).
- Latency: Prompt processing time grows with input token volume.
- Attention Degradation: Irrelevant sentences compete with crucial facts for the model's attention budget ("lost in the middle" effect).
- Zero API Key Requirement: Filtering runs locally on your machine using a compact cross-encoder (
ms-marco-MiniLM-L-6-v2). Your LLM API keys are never needed for context compression.
Installation
Install via pip:
pip install sieve-context
Optional Extras
- LangChain Integration:
pip install "sieve-context[langchain]"
- Model Context Protocol (MCP) Server:
pip install "sieve-context[mcp]"
- Document Ingestion (PDF & HTML):
pip install "sieve-context[docs]"
- All Capabilities:
pip install "sieve-context[all]"
Quickstart
0. Zero-Code Terminal Demo (30 Seconds)
Test Sieve immediately without writing code:
sieve demo
Or prune any custom text directly from your terminal:
sieve filter "What was Apple's 2024 revenue?" --text "Apple reported revenue of $391,035M in FY24. The cafeteria serves lunch daily."
1. Document-Level Optimization (Preserving Metadata)
Pass retrieved documents directly into Sieve.optimize(). Sieve filters sentences while maintaining each document's identity and metadata:
from sieve import Document, Sieve
sieve = Sieve(threshold=0.50)
retrieved_docs = [
Document(
text=(
"Apple Inc. reported total net sales of $391,035 million in fiscal year 2024. "
"Apple Park's main circular building features solar panels generating 17 megawatts."
),
metadata={"source": "apple-10k.pdf", "page": 28}
),
Document(
text="Steve Jobs co-founded Apple in Los Altos in 1976. iPhone net sales reached $201,183 million.",
metadata={"source": "apple-10k.pdf", "page": 31}
)
]
result = sieve.optimize(
query="What was Apple's total net sales and iPhone sales in 2024?",
documents=retrieved_docs,
)
# Ready-to-inject string for your LLM prompt
print(result.context)
# Filtered documents preserving metadata
for doc in result.documents:
print(doc.metadata, "->", doc.text)
# Inspect exact token and reduction metrics
print(f"Original tokens: {result.metrics.original_tokens}")
print(f"Retained tokens: {result.metrics.filtered_tokens}")
print(f"Reduction: {result.metrics.reduction_percent}%")
print(f"Latency: {result.metrics.filtering_latency_ms} ms")
2. Direct String Filtering
If you have a raw context string:
from sieve import filter_context
result = filter_context(
query="What was Apple's 2024 revenue?",
context="Apple's fiscal 2024 revenue reached $391,035 million. The cafeteria serves lunch daily.",
threshold=0.50,
max_tokens=500,
)
print(result.filtered_context)
# Output: "Apple's fiscal 2024 revenue reached $391,035 million."
3. LangChain Integration
Drop Sieve into your existing LangChain retrieval chains as a document compressor:
from sieve.integrations.langchain import SieveCompressor
compressor = SieveCompressor(threshold=0.50)
optimized_docs = compressor.compress_documents(retrieved_docs, query="Apple 2024 revenue")
4. Model Context Protocol (MCP)
Sieve includes a native MCP server for Claude Desktop, Cursor, and any MCP-compliant agent.
Start the server:
sieve-mcp
Or configure it in your claude_desktop_config.json:
{
"mcpServers": {
"sieve": {
"command": "sieve-mcp"
}
}
}
Available MCP Tools
sieve_filter:- Inputs:
query(str),context(str),threshold(float, default 0.5),max_tokens(optional int). - Returns: Filtered context string, token counts, reduction percentage, and filtering latency.
- Inputs:
sieve_score:- Inputs:
query(str),context(str). - Returns: Unfiltered sentence-by-sentence relevance scores (0 to 1) for explainability.
- Inputs:
sieve_stats:- Returns cumulative session statistics: total calls, tokens processed, tokens pruned, and average reduction.
Sieve Calibrate
How aggressively can you filter context before answer accuracy degrades?
Sieve Calibrate sweeps a spectrum of thresholds across a benchmark dataset of {question, context, expected_answer} cases, evaluating answer preservation at each threshold to compute the minimum sufficient context.
Run calibration from the CLI:
sieve calibrate --offline
Example output:
SIEVE CALIBRATION RESULTS
+---------------------------------------------------------------------+
| Threshold | Context Kept | Accuracy | Correct | Avg Latency |
|-------------------+--------------+----------+---------+-------------|
| — (WITHOUT SIEVE) | 100.0% | 100.0% | 10/10 | 0.0ms |
| 0.20 | 38.1% | 100.0% | 10/10 | 0.3ms |
| 0.35 | 38.1% | 100.0% | 10/10 | 0.3ms |
| 0.50 | 38.1% | 100.0% | 10/10 | 0.3ms |
| 0.65 | 38.1% | 100.0% | 10/10 | 0.3ms |
| 0.80 | 38.1% | 100.0% | 10/10 | 0.3ms |
+---------------------------------------------------------------------+
Minimum sufficient context: Threshold 0.20, 38.1% of context retained, 100.0% accuracy.
Configuration & Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
threshold |
float |
0.50 |
Sigmoid-squashed cross-encoder logit cutoff (0.0 to 1.0). Sentences below this score are pruned. |
max_tokens |
int or None |
None |
Optional token budget limit for the retained context. |
context_window |
int |
0 |
Number of neighboring sentences within the same document to retain around high-scoring hits. |
model_name |
str |
cross-encoder/ms-marco-MiniLM-L-6-v2 |
Hugging Face cross-encoder model ID. |
Architecture & How It Works
- Sentence Segmentation: Text is parsed into discrete sentences without external NLP runtime dependencies.
- Local Batch Cross-Encoding: Query and sentence pairs are evaluated in parallel batches with
cross-encoder/ms-marco-MiniLM-L-6-v2. The model is loaded once per process and reused. - Thresholding & Context Preservation: Sentences scoring above the threshold are selected. Optional
context_windowpreserves adjacent sentences to maintain numerical and pronoun coherence. - Original Order Reconstruction: Retained sentences are reconstructed in their original document order to preserve narrative flow for the LLM.
- Deterministic Metrics: Token reductions are measured locally via
tiktoken(cl100k_base).
Limitations
- Sentence-level granularity: Sieve operates at sentence boundaries. It does not rewrite or partially redact sentences.
- Cross-Encoder Inference Time: Running a local neural model adds 50ms–300ms of local compute depending on CPU/GPU hardware.
- Non-probability scoring: Scores are sigmoid-squashed cross-encoder logits for ranking; a score of 0.8 represents ranking confidence, not an absolute statistical probability.
- Tabular Data: Regex sentence segmentation is designed for narrative prose and reports; complex ASCII/markdown tables should be handled prior to sentence chunking.
Contributing
Contributions are welcome! Please open an issue or pull request on GitHub:
- Repository: https://github.com/kuhinthewuh/Sieve
- Issues: https://github.com/kuhinthewuh/Sieve/issues
To set up development:
git clone https://github.com/kuhinthewuh/Sieve.git
cd Sieve
pip install -e ".[dev,all]"
pytest
License
This project is licensed under the MIT License.
Metadata
Release files for sieve-context 0.1.1
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 |
|---|---|---|---|---|
| sieve_context-0.1.1.tar.gz | 1.5 MB | Without provenance | Details for sieve_context-0.1.1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| sieve_context-0.1.1-py3-none-any.whl | Python 3 | none | any | Details for sieve_context-0.1.1-py3-none-any.whl |
Total release size: 1.6 MB
Release files / sieve_context-0.1.1.tar.gz
| Download URL | sieve_context-0.1.1.tar.gz |
|---|---|
| Size | 1.5 MB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
150ecb270a18c6265407ac560bfb906cf794b9d010e641d5a93f263c338d3afa
|
|
BLAKE2b-256 checksum How to use checksums |
0c4b9603c631cae1c7302e1e947f44c429cc4f515006b8a875a736b9b4d06685
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.4
|
Release files / sieve_context-0.1.1-py3-none-any.whl
| Download URL | sieve_context-0.1.1-py3-none-any.whl |
|---|---|
| Size | 32.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
1dc15a864b746d25993b7ad3b0bcefe47f06fbed3c851426c152be0bf7fa78b9
|
|
BLAKE2b-256 checksum How to use checksums |
404f88e212004d510a685a048b9901e2fb62ffe0be44af001b94390288a54cd2
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.4
|
Security for sieve-context 0.1.1
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.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A 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.