raglib-py 2.2.0__tar.gz → 2.2.1__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.
- {raglib_py-2.2.0 → raglib_py-2.2.1}/PKG-INFO +1 -1
- {raglib_py-2.2.0 → raglib_py-2.2.1}/pyproject.toml +1 -1
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/__init__.py +3 -1
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/__main__.py +5 -5
- raglib_py-2.2.1/raglib/access.py +10 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/components/hybrid_retriever.py +2 -2
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/components/multi_hop_retriever.py +50 -50
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/components/multi_query_retriever.py +87 -87
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/components/retriever.py +11 -5
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/components/router_retriever.py +16 -5
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/components/tools.py +59 -59
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/components/web_retriever.py +86 -6
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/core/__init__.py +19 -19
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/core/base.py +408 -408
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/core/fusion.py +103 -103
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/core/intents.py +71 -71
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/core/parsing.py +121 -121
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/core/runtime.py +123 -123
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/core/text.py +199 -199
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/core/tracing.py +55 -55
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/embedding/__init__.py +27 -27
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/facade.py +5 -3
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/graph_context/engine.py +1109 -1109
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/graphrag/__init__.py +35 -35
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/graphrag/background.py +182 -182
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/graphrag/schemas.py +161 -161
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/graphrag/search.py +14 -2
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/graphrag/store/__init__.py +39 -39
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/graphrag/store/base.py +111 -111
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/graphrag/store/neo4j_store.py +295 -295
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/graphrag/store/networkx_store.py +264 -264
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/llm/mock_client.py +218 -218
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/loaders/html_text.py +147 -147
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/loaders/structured_loaders.py +253 -253
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/providers/base_provider.py +73 -73
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/providers/factory.py +142 -142
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/quick.py +34 -34
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/rag_types/__init__.py +31 -31
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/rag_types/advanced_rag.py +29 -29
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/rag_types/agentic_rag.py +3 -2
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/rag_types/corrective_rag.py +2 -1
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/rag_types/graph_rag.py +6 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/rag_types/hybrid_rag.py +44 -43
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/rag_types/memory_rag.py +33 -33
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/rag_types/multi_hop_rag.py +39 -39
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/rag_types/naive_rag.py +28 -28
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/rag_types/routing_rag.py +28 -28
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/rag_types/web_rag.py +26 -25
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/schemas.py +74 -74
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/vectorstores/base_store.py +128 -128
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/vectorstores/chroma_store.py +215 -215
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/vectorstores/in_memory_store.py +290 -290
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/vectorstores/pgvector_store.py +2 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/vectorstores/qdrant_store.py +3 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/vision/chat_vision.py +27 -27
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/visualize.py +299 -299
- {raglib_py-2.2.0 → raglib_py-2.2.1}/.gitignore +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/LICENSE +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/README.md +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/cli.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/components/__init__.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/components/bm25.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/components/context_reducer.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/components/decision.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/components/deduplicator.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/components/evaluator.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/components/generator.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/components/grader.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/components/memory.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/components/planner.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/components/query_expander.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/components/query_rewriter.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/components/refiner.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/components/reflection.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/components/reranker.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/components/sql_tool.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/constants.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/core/concurrency.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/embedding/base_embedding.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/embedding/cached_embedding.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/embedding/embedding_factory.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/embedding/google_embedding.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/embedding/huggingface_embedding.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/embedding/mock_embedding.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/embedding/ollama_embedding.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/embedding/openai_embedding.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/eval/__init__.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/graph_context/__init__.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/graph_context/schemas.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/graphrag/communities.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/graphrag/extractor.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/graphrag/indexer.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/llm/__init__.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/llm/base_client.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/llm/clients.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/llm/constants.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/llm/http.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/llm/langchain_adapter.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/llm/provider_detector.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/llm/providers.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/llm/resilience.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/loaders/__init__.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/loaders/chunk_splitter.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/loaders/document_loader.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/loaders/exceptions.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/loaders/pdf_loader.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/loaders/pptx_loader.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/loaders/text_loader.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/loaders/web_loader.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/loaders/word_loader.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/preprocessing/__init__.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/preprocessing/chunk_splitter.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/providers/__init__.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/providers/bing_provider.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/providers/brave_provider.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/providers/duckduckgo_provider.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/providers/exa_provider.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/providers/google_cse_provider.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/providers/searxng_provider.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/providers/serpapi_provider.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/providers/tavily_provider.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/rag_types/multi_query_rag.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/rag_types/self_rag.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/rag_types/tool_augmented_rag.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/session/__init__.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/session/interactive.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/vectorstores/__init__.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/vectorstores/factory.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/vision/__init__.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/vision/anthropic_vision.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/vision/base_vision.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/vision/google_vision.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/vision/mock_vision.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/vision/openai_vision.py +0 -0
- {raglib_py-2.2.0 → raglib_py-2.2.1}/raglib/vision/vision_factory.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: raglib-py
|
|
3
|
-
Version: 2.2.
|
|
3
|
+
Version: 2.2.1
|
|
4
4
|
Summary: Modular Retrieval-Augmented Generation: hybrid search, reranking, CRAG, Self-RAG, agentic and GraphRAG pipelines
|
|
5
5
|
Project-URL: Homepage, https://github.com/himanshuhs9011/raglib
|
|
6
6
|
Project-URL: Documentation, https://github.com/himanshuhs9011/raglib/blob/main/docs/USAGE.md
|
|
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "raglib-py"
|
|
7
|
-
version = "2.2.
|
|
7
|
+
version = "2.2.1"
|
|
8
8
|
description = "Modular Retrieval-Augmented Generation: hybrid search, reranking, CRAG, Self-RAG, agentic and GraphRAG pipelines"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
license = { file = "LICENSE" }
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
+
from raglib.access import FilterNotSupportedError
|
|
5
6
|
from raglib.components import (
|
|
6
7
|
BM25Index,
|
|
7
8
|
ContextReducer,
|
|
@@ -90,6 +91,7 @@ __all__ = [
|
|
|
90
91
|
"BM25Index",
|
|
91
92
|
"Retriever",
|
|
92
93
|
"WebRetriever",
|
|
94
|
+
"FilterNotSupportedError",
|
|
93
95
|
"HybridRetriever",
|
|
94
96
|
"RouterRetriever",
|
|
95
97
|
"MultiQueryRetriever",
|
|
@@ -131,4 +133,4 @@ __all__ = [
|
|
|
131
133
|
"GraphContextWindow",
|
|
132
134
|
]
|
|
133
135
|
|
|
134
|
-
__version__ = "2.2.
|
|
136
|
+
__version__ = "2.2.1"
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"""Allow ``python -m raglib ask docs/ "question"``."""
|
|
2
|
-
|
|
3
|
-
from raglib.cli import main
|
|
4
|
-
|
|
5
|
-
raise SystemExit(main())
|
|
1
|
+
"""Allow ``python -m raglib ask docs/ "question"``."""
|
|
2
|
+
|
|
3
|
+
from raglib.cli import main
|
|
4
|
+
|
|
5
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"""Errors for metadata filters that cannot be enforced."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class FilterNotSupportedError(RuntimeError):
|
|
7
|
+
"""A retriever or backend was asked to apply a metadata filter it cannot enforce.
|
|
8
|
+
|
|
9
|
+
Raised instead of silently returning unfiltered results, which could leak documents.
|
|
10
|
+
"""
|
|
@@ -6,7 +6,7 @@ import logging
|
|
|
6
6
|
from typing import Any, List, Optional
|
|
7
7
|
|
|
8
8
|
from raglib.components.retriever import Retriever
|
|
9
|
-
from raglib.components.web_retriever import WebRetriever
|
|
9
|
+
from raglib.components.web_retriever import WebRetriever, web_retrieve
|
|
10
10
|
from raglib.core.concurrency import parallel_map
|
|
11
11
|
from raglib.core.fusion import interleave
|
|
12
12
|
from raglib.schemas import Document
|
|
@@ -56,7 +56,7 @@ class HybridRetriever:
|
|
|
56
56
|
|
|
57
57
|
tasks = [
|
|
58
58
|
(lambda: self.vector_retriever.retrieve(query, **kwargs)) if self.vector_weight > 0 else (lambda: []),
|
|
59
|
-
(lambda: self.web_retriever.
|
|
59
|
+
(lambda: web_retrieve(self.web_retriever, query, kwargs.get("filters"))) if self.web_weight > 0 else (lambda: []),
|
|
60
60
|
]
|
|
61
61
|
vector_docs, web_docs = parallel_map(lambda task: task(), tasks, max_workers=2)
|
|
62
62
|
fused = self.allocate(vector_docs, web_docs)
|
|
@@ -1,50 +1,50 @@
|
|
|
1
|
-
"""Iterative multi-hop retrieval: each hop is planned from the evidence gathered so far."""
|
|
2
|
-
|
|
3
|
-
from __future__ import annotations
|
|
4
|
-
|
|
5
|
-
import logging
|
|
6
|
-
from dataclasses import replace
|
|
7
|
-
from typing import Any, List
|
|
8
|
-
|
|
9
|
-
from raglib.components.planner import Planner
|
|
10
|
-
from raglib.components.retriever import Retriever
|
|
11
|
-
from raglib.core.fusion import interleave
|
|
12
|
-
from raglib.schemas import Document, QueryResult
|
|
13
|
-
|
|
14
|
-
logger = logging.getLogger(__name__)
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
class MultiHopRetriever:
|
|
18
|
-
"""Retrieve -> inspect evidence -> plan the next query (bridge entity) -> repeat."""
|
|
19
|
-
|
|
20
|
-
def __init__(self, retriever: Retriever, planner: Planner, max_hops: int = 3, docs_per_hop: int = 4):
|
|
21
|
-
"""Initialize multi-hop retrieval dependencies."""
|
|
22
|
-
|
|
23
|
-
self.retriever = retriever
|
|
24
|
-
self.planner = planner
|
|
25
|
-
self.max_hops = max(1, max_hops)
|
|
26
|
-
self.docs_per_hop = docs_per_hop
|
|
27
|
-
|
|
28
|
-
def retrieve(self, query: str, **kwargs: Any) -> QueryResult:
|
|
29
|
-
"""Run up to ``max_hops`` dependent retrieval hops and fuse their results."""
|
|
30
|
-
|
|
31
|
-
queries: List[str] = [query]
|
|
32
|
-
hop_results: List[List[Document]] = []
|
|
33
|
-
evidence: List[Document] = []
|
|
34
|
-
current = query
|
|
35
|
-
for hop in range(1, self.max_hops + 1):
|
|
36
|
-
docs = self.retriever.retrieve(current, top_k=self.docs_per_hop, **kwargs)
|
|
37
|
-
hop_results.append(
|
|
38
|
-
[replace(doc, metadata={**doc.metadata, "hop": hop, "hop_query": current}) for doc in docs]
|
|
39
|
-
)
|
|
40
|
-
evidence.extend(hop_results[-1])
|
|
41
|
-
logger.debug("MultiHopRetriever hop=%d docs=%d", hop, len(docs))
|
|
42
|
-
if hop == self.max_hops:
|
|
43
|
-
break
|
|
44
|
-
next_query = self.planner.next_step(query, evidence, queries)
|
|
45
|
-
if next_query is None:
|
|
46
|
-
break
|
|
47
|
-
queries.append(next_query)
|
|
48
|
-
current = next_query
|
|
49
|
-
fused = interleave(hop_results) # each hop answers a different sub-question
|
|
50
|
-
return QueryResult(query=query, documents=fused, hop_count=len(hop_results), rewritten_query=" | ".join(queries))
|
|
1
|
+
"""Iterative multi-hop retrieval: each hop is planned from the evidence gathered so far."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
from dataclasses import replace
|
|
7
|
+
from typing import Any, List
|
|
8
|
+
|
|
9
|
+
from raglib.components.planner import Planner
|
|
10
|
+
from raglib.components.retriever import Retriever
|
|
11
|
+
from raglib.core.fusion import interleave
|
|
12
|
+
from raglib.schemas import Document, QueryResult
|
|
13
|
+
|
|
14
|
+
logger = logging.getLogger(__name__)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class MultiHopRetriever:
|
|
18
|
+
"""Retrieve -> inspect evidence -> plan the next query (bridge entity) -> repeat."""
|
|
19
|
+
|
|
20
|
+
def __init__(self, retriever: Retriever, planner: Planner, max_hops: int = 3, docs_per_hop: int = 4):
|
|
21
|
+
"""Initialize multi-hop retrieval dependencies."""
|
|
22
|
+
|
|
23
|
+
self.retriever = retriever
|
|
24
|
+
self.planner = planner
|
|
25
|
+
self.max_hops = max(1, max_hops)
|
|
26
|
+
self.docs_per_hop = docs_per_hop
|
|
27
|
+
|
|
28
|
+
def retrieve(self, query: str, **kwargs: Any) -> QueryResult:
|
|
29
|
+
"""Run up to ``max_hops`` dependent retrieval hops and fuse their results."""
|
|
30
|
+
|
|
31
|
+
queries: List[str] = [query]
|
|
32
|
+
hop_results: List[List[Document]] = []
|
|
33
|
+
evidence: List[Document] = []
|
|
34
|
+
current = query
|
|
35
|
+
for hop in range(1, self.max_hops + 1):
|
|
36
|
+
docs = self.retriever.retrieve(current, top_k=self.docs_per_hop, **kwargs)
|
|
37
|
+
hop_results.append(
|
|
38
|
+
[replace(doc, metadata={**doc.metadata, "hop": hop, "hop_query": current}) for doc in docs]
|
|
39
|
+
)
|
|
40
|
+
evidence.extend(hop_results[-1])
|
|
41
|
+
logger.debug("MultiHopRetriever hop=%d docs=%d", hop, len(docs))
|
|
42
|
+
if hop == self.max_hops:
|
|
43
|
+
break
|
|
44
|
+
next_query = self.planner.next_step(query, evidence, queries)
|
|
45
|
+
if next_query is None:
|
|
46
|
+
break
|
|
47
|
+
queries.append(next_query)
|
|
48
|
+
current = next_query
|
|
49
|
+
fused = interleave(hop_results) # each hop answers a different sub-question
|
|
50
|
+
return QueryResult(query=query, documents=fused, hop_count=len(hop_results), rewritten_query=" | ".join(queries))
|
|
@@ -1,87 +1,87 @@
|
|
|
1
|
-
"""Multi-query retrieval: parallel retrieval per query variant, fused with RRF."""
|
|
2
|
-
|
|
3
|
-
from __future__ import annotations
|
|
4
|
-
|
|
5
|
-
import logging
|
|
6
|
-
from typing import Any, List, Optional
|
|
7
|
-
|
|
8
|
-
from raglib.components.deduplicator import Deduplicator
|
|
9
|
-
from raglib.components.query_expander import QueryExpander
|
|
10
|
-
from raglib.components.retriever import Retriever
|
|
11
|
-
from raglib.core.concurrency import parallel_map
|
|
12
|
-
from raglib.core.fusion import reciprocal_rank_fusion
|
|
13
|
-
from raglib.schemas import Document
|
|
14
|
-
|
|
15
|
-
logger = logging.getLogger(__name__)
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
class MultiQueryRetriever:
|
|
19
|
-
"""Expands a query into variants, retrieves for each in parallel, and fuses with RRF."""
|
|
20
|
-
|
|
21
|
-
def __init__(
|
|
22
|
-
self,
|
|
23
|
-
retriever: Retriever,
|
|
24
|
-
query_expander: QueryExpander,
|
|
25
|
-
deduplicator: Optional[Deduplicator] = None,
|
|
26
|
-
top_k: int = 5,
|
|
27
|
-
max_workers: int = 4,
|
|
28
|
-
):
|
|
29
|
-
"""Initialize variant retrieval dependencies."""
|
|
30
|
-
|
|
31
|
-
self.retriever = retriever
|
|
32
|
-
self.query_expander = query_expander
|
|
33
|
-
self.deduplicator = deduplicator
|
|
34
|
-
self.top_k = top_k
|
|
35
|
-
self.max_workers = max_workers
|
|
36
|
-
|
|
37
|
-
def retrieve(self, query: str, top_k: Optional[int] = None, **kwargs: Any) -> List[Document]:
|
|
38
|
-
"""Retrieve documents across query variants and fuse rankings."""
|
|
39
|
-
|
|
40
|
-
return self.retrieve_with_variants(query, top_k=top_k, **kwargs)[0]
|
|
41
|
-
|
|
42
|
-
def retrieve_with_variants(self, query: str, top_k: Optional[int] = None, **kwargs: Any):
|
|
43
|
-
"""Return (fused documents, query variants) - thread-safe, no shared state."""
|
|
44
|
-
|
|
45
|
-
k = top_k or self.top_k
|
|
46
|
-
variants = self.query_expander.expand(query)
|
|
47
|
-
if len(variants) == 1:
|
|
48
|
-
ranked_lists = [self.retriever.retrieve(variants[0], top_k=k, **kwargs)]
|
|
49
|
-
else:
|
|
50
|
-
ranked_lists = parallel_map(lambda v: self.retriever.retrieve(v, top_k=k, **kwargs), variants, self.max_workers)
|
|
51
|
-
weights = [1.5] + [1.0] * (len(ranked_lists) - 1)
|
|
52
|
-
fused = reciprocal_rank_fusion(ranked_lists, weights=weights)
|
|
53
|
-
fused = cover_each_list(ranked_lists, fused, k)
|
|
54
|
-
if self.deduplicator is not None:
|
|
55
|
-
fused = self.deduplicator.deduplicate(fused)
|
|
56
|
-
return fused[:k], variants
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
def cover_each_list(ranked_lists: List[List[Document]], fused: List[Document], k: int) -> List[Document]:
|
|
60
|
-
"""Reserve the first slots for each list's best result, then fill by fused (RRF) order.
|
|
61
|
-
|
|
62
|
-
RRF rewards documents found by many queries, so when the queries cover different parts of a
|
|
63
|
-
question (one per source or entity), the part matched by most queries takes every slot and the
|
|
64
|
-
others are lost. Giving each query its top hit first keeps every part covered; for plain
|
|
65
|
-
paraphrases the top hits mostly coincide, so the order stays close to RRF.
|
|
66
|
-
"""
|
|
67
|
-
|
|
68
|
-
from raglib.core.fusion import doc_key
|
|
69
|
-
|
|
70
|
-
scored = {doc_key(doc): doc for doc in fused} # carry the fused score and metadata
|
|
71
|
-
chosen: List[Document] = []
|
|
72
|
-
seen = set()
|
|
73
|
-
for ranked in ranked_lists:
|
|
74
|
-
if len(chosen) >= k:
|
|
75
|
-
break
|
|
76
|
-
if not ranked:
|
|
77
|
-
continue
|
|
78
|
-
key = doc_key(ranked[0]) # this query's best hit; if already chosen, the query is covered
|
|
79
|
-
if key not in seen:
|
|
80
|
-
seen.add(key)
|
|
81
|
-
chosen.append(scored.get(key, ranked[0]))
|
|
82
|
-
for doc in fused:
|
|
83
|
-
key = doc_key(doc)
|
|
84
|
-
if key not in seen:
|
|
85
|
-
seen.add(key)
|
|
86
|
-
chosen.append(doc)
|
|
87
|
-
return chosen
|
|
1
|
+
"""Multi-query retrieval: parallel retrieval per query variant, fused with RRF."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
from typing import Any, List, Optional
|
|
7
|
+
|
|
8
|
+
from raglib.components.deduplicator import Deduplicator
|
|
9
|
+
from raglib.components.query_expander import QueryExpander
|
|
10
|
+
from raglib.components.retriever import Retriever
|
|
11
|
+
from raglib.core.concurrency import parallel_map
|
|
12
|
+
from raglib.core.fusion import reciprocal_rank_fusion
|
|
13
|
+
from raglib.schemas import Document
|
|
14
|
+
|
|
15
|
+
logger = logging.getLogger(__name__)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class MultiQueryRetriever:
|
|
19
|
+
"""Expands a query into variants, retrieves for each in parallel, and fuses with RRF."""
|
|
20
|
+
|
|
21
|
+
def __init__(
|
|
22
|
+
self,
|
|
23
|
+
retriever: Retriever,
|
|
24
|
+
query_expander: QueryExpander,
|
|
25
|
+
deduplicator: Optional[Deduplicator] = None,
|
|
26
|
+
top_k: int = 5,
|
|
27
|
+
max_workers: int = 4,
|
|
28
|
+
):
|
|
29
|
+
"""Initialize variant retrieval dependencies."""
|
|
30
|
+
|
|
31
|
+
self.retriever = retriever
|
|
32
|
+
self.query_expander = query_expander
|
|
33
|
+
self.deduplicator = deduplicator
|
|
34
|
+
self.top_k = top_k
|
|
35
|
+
self.max_workers = max_workers
|
|
36
|
+
|
|
37
|
+
def retrieve(self, query: str, top_k: Optional[int] = None, **kwargs: Any) -> List[Document]:
|
|
38
|
+
"""Retrieve documents across query variants and fuse rankings."""
|
|
39
|
+
|
|
40
|
+
return self.retrieve_with_variants(query, top_k=top_k, **kwargs)[0]
|
|
41
|
+
|
|
42
|
+
def retrieve_with_variants(self, query: str, top_k: Optional[int] = None, **kwargs: Any):
|
|
43
|
+
"""Return (fused documents, query variants) - thread-safe, no shared state."""
|
|
44
|
+
|
|
45
|
+
k = top_k or self.top_k
|
|
46
|
+
variants = self.query_expander.expand(query)
|
|
47
|
+
if len(variants) == 1:
|
|
48
|
+
ranked_lists = [self.retriever.retrieve(variants[0], top_k=k, **kwargs)]
|
|
49
|
+
else:
|
|
50
|
+
ranked_lists = parallel_map(lambda v: self.retriever.retrieve(v, top_k=k, **kwargs), variants, self.max_workers)
|
|
51
|
+
weights = [1.5] + [1.0] * (len(ranked_lists) - 1)
|
|
52
|
+
fused = reciprocal_rank_fusion(ranked_lists, weights=weights)
|
|
53
|
+
fused = cover_each_list(ranked_lists, fused, k)
|
|
54
|
+
if self.deduplicator is not None:
|
|
55
|
+
fused = self.deduplicator.deduplicate(fused)
|
|
56
|
+
return fused[:k], variants
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def cover_each_list(ranked_lists: List[List[Document]], fused: List[Document], k: int) -> List[Document]:
|
|
60
|
+
"""Reserve the first slots for each list's best result, then fill by fused (RRF) order.
|
|
61
|
+
|
|
62
|
+
RRF rewards documents found by many queries, so when the queries cover different parts of a
|
|
63
|
+
question (one per source or entity), the part matched by most queries takes every slot and the
|
|
64
|
+
others are lost. Giving each query its top hit first keeps every part covered; for plain
|
|
65
|
+
paraphrases the top hits mostly coincide, so the order stays close to RRF.
|
|
66
|
+
"""
|
|
67
|
+
|
|
68
|
+
from raglib.core.fusion import doc_key
|
|
69
|
+
|
|
70
|
+
scored = {doc_key(doc): doc for doc in fused} # carry the fused score and metadata
|
|
71
|
+
chosen: List[Document] = []
|
|
72
|
+
seen = set()
|
|
73
|
+
for ranked in ranked_lists:
|
|
74
|
+
if len(chosen) >= k:
|
|
75
|
+
break
|
|
76
|
+
if not ranked:
|
|
77
|
+
continue
|
|
78
|
+
key = doc_key(ranked[0]) # this query's best hit; if already chosen, the query is covered
|
|
79
|
+
if key not in seen:
|
|
80
|
+
seen.add(key)
|
|
81
|
+
chosen.append(scored.get(key, ranked[0]))
|
|
82
|
+
for doc in fused:
|
|
83
|
+
key = doc_key(doc)
|
|
84
|
+
if key not in seen:
|
|
85
|
+
seen.add(key)
|
|
86
|
+
chosen.append(doc)
|
|
87
|
+
return chosen
|
|
@@ -236,7 +236,7 @@ class Retriever:
|
|
|
236
236
|
|
|
237
237
|
results = candidates[:k]
|
|
238
238
|
if self.neighbor_window > 0:
|
|
239
|
-
results = [self._expand_neighbors(doc) for doc in results]
|
|
239
|
+
results = [self._expand_neighbors(doc, filters) for doc in results]
|
|
240
240
|
logger.debug("Retriever mode=%s returned %d docs", active_mode, len(results))
|
|
241
241
|
return [
|
|
242
242
|
replace(doc, metadata={**doc.metadata, "retriever": active_mode}, source=doc.source or "vector")
|
|
@@ -367,15 +367,21 @@ class Retriever:
|
|
|
367
367
|
remaining.remove(best_doc)
|
|
368
368
|
return selected
|
|
369
369
|
|
|
370
|
-
def _expand_neighbors(self, doc: Document) -> Document:
|
|
371
|
-
"""Small-to-big: widen a hit with its neighbouring chunks from the same parent.
|
|
370
|
+
def _expand_neighbors(self, doc: Document, filters: Optional[MetadataFilter] = None) -> Document:
|
|
371
|
+
"""Small-to-big: widen a hit with its neighbouring chunks from the same parent.
|
|
372
|
+
|
|
373
|
+
Expansion stops at a neighbour that fails ``filters``.
|
|
374
|
+
"""
|
|
375
|
+
|
|
376
|
+
def allowed(neighbor: Document) -> bool:
|
|
377
|
+
return not filters or matches_filter({**neighbor.metadata, "source": neighbor.source}, filters)
|
|
372
378
|
|
|
373
379
|
parts = [doc.content]
|
|
374
380
|
current = doc
|
|
375
381
|
for _ in range(self.neighbor_window):
|
|
376
382
|
prev_id = current.metadata.get("prev_id")
|
|
377
383
|
prev_doc = self._doc_index.get(prev_id) if prev_id else None
|
|
378
|
-
if prev_doc is None:
|
|
384
|
+
if prev_doc is None or not allowed(prev_doc):
|
|
379
385
|
break
|
|
380
386
|
parts.insert(0, prev_doc.content)
|
|
381
387
|
current = prev_doc
|
|
@@ -383,7 +389,7 @@ class Retriever:
|
|
|
383
389
|
for _ in range(self.neighbor_window):
|
|
384
390
|
next_id = current.metadata.get("next_id")
|
|
385
391
|
next_doc = self._doc_index.get(next_id) if next_id else None
|
|
386
|
-
if next_doc is None:
|
|
392
|
+
if next_doc is None or not allowed(next_doc):
|
|
387
393
|
break
|
|
388
394
|
parts.append(next_doc.content)
|
|
389
395
|
current = next_doc
|
|
@@ -7,7 +7,7 @@ from typing import Any, List, Optional
|
|
|
7
7
|
|
|
8
8
|
from raglib.components.hybrid_retriever import HybridRetriever
|
|
9
9
|
from raglib.components.retriever import Retriever
|
|
10
|
-
from raglib.components.web_retriever import WebRetriever
|
|
10
|
+
from raglib.components.web_retriever import WebRetriever, web_retrieve
|
|
11
11
|
from raglib.core.intents import (
|
|
12
12
|
is_comparison,
|
|
13
13
|
is_global_question,
|
|
@@ -96,17 +96,28 @@ class RouterRetriever:
|
|
|
96
96
|
return route
|
|
97
97
|
|
|
98
98
|
def retrieve_route(self, route: str, query: str, **kwargs: Any) -> List[Document]:
|
|
99
|
-
"""Retrieve from a specific route.
|
|
99
|
+
"""Retrieve from a specific route.
|
|
100
100
|
|
|
101
|
+
``filters`` restrict the corpus on every route: the hybrid route passes them to its corpus
|
|
102
|
+
search, and a corpus-backed search provider (``web_search_provider="local"``) applies them.
|
|
103
|
+
Public web results are not corpus documents, so filters do not apply to them. The knowledge
|
|
104
|
+
graph cannot apply filters in 2.2, so a filtered query routed to ``graph`` uses the vector
|
|
105
|
+
route instead.
|
|
106
|
+
"""
|
|
107
|
+
|
|
108
|
+
filters = kwargs.get("filters")
|
|
101
109
|
if route == ROUTE_WEB and self.web_retriever is not None:
|
|
102
|
-
return self.web_retriever
|
|
110
|
+
return web_retrieve(self.web_retriever, query, filters)
|
|
103
111
|
if route == ROUTE_HYBRID and self.hybrid_retriever is not None:
|
|
104
|
-
return self.hybrid_retriever.retrieve(query)
|
|
112
|
+
return self.hybrid_retriever.retrieve(query, **kwargs)
|
|
105
113
|
if route == ROUTE_GRAPH and self.graph_retriever is not None:
|
|
106
|
-
|
|
114
|
+
if not filters:
|
|
115
|
+
return self.graph_retriever.retrieve(query, **kwargs)
|
|
116
|
+
logger.warning("RouterRetriever: the graph route cannot apply filters; using the vector route")
|
|
107
117
|
return self.vector_retriever.retrieve(query, **kwargs)
|
|
108
118
|
|
|
109
119
|
def retrieve(self, query: str, **kwargs: Any) -> List[Document]:
|
|
110
120
|
"""Route then retrieve."""
|
|
111
121
|
|
|
112
122
|
return self.retrieve_route(self.route(query), query, **kwargs)
|
|
123
|
+
|
|
@@ -1,59 +1,59 @@
|
|
|
1
|
-
"""Tool abstraction for agentic RAG."""
|
|
2
|
-
|
|
3
|
-
from __future__ import annotations
|
|
4
|
-
|
|
5
|
-
import hashlib
|
|
6
|
-
import logging
|
|
7
|
-
from dataclasses import dataclass
|
|
8
|
-
from typing import Any, Callable, List, Union
|
|
9
|
-
|
|
10
|
-
from raglib.schemas import Document
|
|
11
|
-
|
|
12
|
-
logger = logging.getLogger(__name__)
|
|
13
|
-
|
|
14
|
-
ToolOutput = Union[str, Document, List[Document], List[str], None]
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
@dataclass
|
|
18
|
-
class Tool:
|
|
19
|
-
"""A callable the agent can invoke with a single string input.
|
|
20
|
-
|
|
21
|
-
``func`` may return text, a Document, or a list of either; outputs are normalized
|
|
22
|
-
to Documents so they can be cited like retrieved chunks.
|
|
23
|
-
"""
|
|
24
|
-
|
|
25
|
-
name: str
|
|
26
|
-
description: str
|
|
27
|
-
func: Callable[[str], ToolOutput]
|
|
28
|
-
|
|
29
|
-
def run(self, tool_input: str) -> List[Document]:
|
|
30
|
-
"""Invoke the tool and normalize its output to Documents."""
|
|
31
|
-
|
|
32
|
-
output: Any = self.func(tool_input)
|
|
33
|
-
return normalize_tool_output(self.name, tool_input, output)
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
def normalize_tool_output(tool_name: str, tool_input: str, output: Any) -> List[Document]:
|
|
37
|
-
"""Convert arbitrary tool output into a list of Documents."""
|
|
38
|
-
|
|
39
|
-
if output is None:
|
|
40
|
-
return []
|
|
41
|
-
items = output if isinstance(output, list) else [output]
|
|
42
|
-
documents: List[Document] = []
|
|
43
|
-
for index, item in enumerate(items, start=1):
|
|
44
|
-
if isinstance(item, Document):
|
|
45
|
-
documents.append(item)
|
|
46
|
-
continue
|
|
47
|
-
text = str(item).strip()
|
|
48
|
-
if not text:
|
|
49
|
-
continue
|
|
50
|
-
digest = hashlib.sha256(f"{tool_name}:{tool_input}:{text}".encode("utf-8")).hexdigest()[:12]
|
|
51
|
-
documents.append(
|
|
52
|
-
Document(
|
|
53
|
-
id=f"tool-{tool_name}-{digest}",
|
|
54
|
-
content=text,
|
|
55
|
-
metadata={"tool": tool_name, "tool_input": tool_input, "title": f"{tool_name} result {index}"},
|
|
56
|
-
source=f"tool:{tool_name}",
|
|
57
|
-
)
|
|
58
|
-
)
|
|
59
|
-
return documents
|
|
1
|
+
"""Tool abstraction for agentic RAG."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import logging
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from typing import Any, Callable, List, Union
|
|
9
|
+
|
|
10
|
+
from raglib.schemas import Document
|
|
11
|
+
|
|
12
|
+
logger = logging.getLogger(__name__)
|
|
13
|
+
|
|
14
|
+
ToolOutput = Union[str, Document, List[Document], List[str], None]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass
|
|
18
|
+
class Tool:
|
|
19
|
+
"""A callable the agent can invoke with a single string input.
|
|
20
|
+
|
|
21
|
+
``func`` may return text, a Document, or a list of either; outputs are normalized
|
|
22
|
+
to Documents so they can be cited like retrieved chunks.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
name: str
|
|
26
|
+
description: str
|
|
27
|
+
func: Callable[[str], ToolOutput]
|
|
28
|
+
|
|
29
|
+
def run(self, tool_input: str) -> List[Document]:
|
|
30
|
+
"""Invoke the tool and normalize its output to Documents."""
|
|
31
|
+
|
|
32
|
+
output: Any = self.func(tool_input)
|
|
33
|
+
return normalize_tool_output(self.name, tool_input, output)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def normalize_tool_output(tool_name: str, tool_input: str, output: Any) -> List[Document]:
|
|
37
|
+
"""Convert arbitrary tool output into a list of Documents."""
|
|
38
|
+
|
|
39
|
+
if output is None:
|
|
40
|
+
return []
|
|
41
|
+
items = output if isinstance(output, list) else [output]
|
|
42
|
+
documents: List[Document] = []
|
|
43
|
+
for index, item in enumerate(items, start=1):
|
|
44
|
+
if isinstance(item, Document):
|
|
45
|
+
documents.append(item)
|
|
46
|
+
continue
|
|
47
|
+
text = str(item).strip()
|
|
48
|
+
if not text:
|
|
49
|
+
continue
|
|
50
|
+
digest = hashlib.sha256(f"{tool_name}:{tool_input}:{text}".encode("utf-8")).hexdigest()[:12]
|
|
51
|
+
documents.append(
|
|
52
|
+
Document(
|
|
53
|
+
id=f"tool-{tool_name}-{digest}",
|
|
54
|
+
content=text,
|
|
55
|
+
metadata={"tool": tool_name, "tool_input": tool_input, "title": f"{tool_name} result {index}"},
|
|
56
|
+
source=f"tool:{tool_name}",
|
|
57
|
+
)
|
|
58
|
+
)
|
|
59
|
+
return documents
|