Spaces:
Sleeping
Sleeping
File size: 11,747 Bytes
536d6c7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 | """RAG Pipeline for Context-Aware Agent Operations
Retrieval-Augmented Generation pipeline that enriches agent responses
with relevant context from docs/assets/test data corpus.
"""
import os
import json
from pathlib import Path
from typing import List, Dict, Any, Optional, Tuple
import numpy as np
from dataclasses import dataclass
try:
from sentence_transformers import SentenceTransformer
EMBEDDINGS_AVAILABLE = True
except ImportError:
EMBEDDINGS_AVAILABLE = False
print("Warning: sentence-transformers not available. Install with: pip install sentence-transformers")
@dataclass
class Document:
"""Document container with metadata"""
content: str
source: str
metadata: Dict[str, Any]
embedding: Optional[np.ndarray] = None
@dataclass
class RetrievalResult:
"""Result from RAG retrieval with context and citations"""
documents: List[Document]
context: str
citations: List[str]
scores: List[float]
class RAGPipeline:
"""Retrieval-Augmented Generation Pipeline
Provides context-aware enrichment for agent operations by:
- Indexing documents from docs/assets/test data
- Retrieving relevant context for queries
- Generating citations and evidence for responses
"""
def __init__(
self,
corpus_dir: str = "./docs",
model_name: str = "all-MiniLM-L6-v2",
top_k: int = 5,
cache_dir: str = "./rag_cache"
):
"""Initialize RAG pipeline
Args:
corpus_dir: Directory containing documents to index
model_name: Sentence transformer model for embeddings
top_k: Number of top documents to retrieve
cache_dir: Directory for caching embeddings
"""
self.corpus_dir = Path(corpus_dir)
self.top_k = top_k
self.cache_dir = Path(cache_dir)
self.cache_dir.mkdir(exist_ok=True)
# Initialize embedding model
if EMBEDDINGS_AVAILABLE:
try:
self.model = SentenceTransformer(model_name)
self.embedding_dim = self.model.get_sentence_embedding_dimension()
except Exception as e:
print(f"Error loading embedding model: {e}")
self.model = None
else:
self.model = None
# Document store
self.documents: List[Document] = []
self.embeddings: Optional[np.ndarray] = None
# Load and index documents
self._load_corpus()
def _load_corpus(self):
"""Load documents from corpus directory"""
if not self.corpus_dir.exists():
print(f"Warning: Corpus directory {self.corpus_dir} does not exist")
return
# Load all text-based files
extensions = [".txt", ".md", ".json", ".csv", ".py"]
for ext in extensions:
for file_path in self.corpus_dir.rglob(f"*{ext}"):
try:
self._load_document(file_path)
except Exception as e:
print(f"Error loading {file_path}: {e}")
print(f"Loaded {len(self.documents)} documents from corpus")
# Generate embeddings
if self.model and self.documents:
self._generate_embeddings()
def _load_document(self, file_path: Path):
"""Load a single document"""
with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
content = f.read()
# Skip empty files
if not content.strip():
return
# Create document
doc = Document(
content=content,
source=str(file_path.relative_to(self.corpus_dir)),
metadata={
"file_type": file_path.suffix,
"file_name": file_path.name,
"path": str(file_path)
}
)
self.documents.append(doc)
def _generate_embeddings(self):
"""Generate embeddings for all documents"""
if not self.model:
return
# Check cache
cache_file = self.cache_dir / "embeddings.npy"
cache_meta = self.cache_dir / "embeddings_meta.json"
if cache_file.exists() and cache_meta.exists():
try:
self.embeddings = np.load(cache_file)
with open(cache_meta, 'r') as f:
meta = json.load(f)
if meta.get("num_docs") == len(self.documents):
print("Loaded embeddings from cache")
return
except Exception as e:
print(f"Error loading cache: {e}")
# Generate new embeddings
print("Generating document embeddings...")
texts = [doc.content for doc in self.documents]
try:
self.embeddings = self.model.encode(
texts,
show_progress_bar=True,
convert_to_numpy=True
)
# Cache embeddings
np.save(cache_file, self.embeddings)
with open(cache_meta, 'w') as f:
json.dump({"num_docs": len(self.documents)}, f)
print("Embeddings generated and cached")
except Exception as e:
print(f"Error generating embeddings: {e}")
self.embeddings = None
def retrieve(
self,
query: str,
top_k: Optional[int] = None,
filter_metadata: Optional[Dict[str, Any]] = None
) -> RetrievalResult:
"""Retrieve relevant documents for a query
Args:
query: Search query
top_k: Number of documents to retrieve (default: self.top_k)
filter_metadata: Optional metadata filters
Returns:
RetrievalResult with documents, context, and citations
"""
if top_k is None:
top_k = self.top_k
if not self.documents:
return RetrievalResult(
documents=[],
context="No documents available in corpus.",
citations=[],
scores=[]
)
# Use semantic search if embeddings available
if self.model and self.embeddings is not None:
return self._semantic_retrieve(query, top_k, filter_metadata)
else:
# Fallback to keyword search
return self._keyword_retrieve(query, top_k, filter_metadata)
def _semantic_retrieve(
self,
query: str,
top_k: int,
filter_metadata: Optional[Dict[str, Any]]
) -> RetrievalResult:
"""Semantic retrieval using embeddings"""
# Encode query
query_embedding = self.model.encode([query], convert_to_numpy=True)[0]
# Compute similarities
similarities = np.dot(self.embeddings, query_embedding)
# Apply metadata filters
valid_indices = range(len(self.documents))
if filter_metadata:
valid_indices = [
i for i in valid_indices
if all(
self.documents[i].metadata.get(k) == v
for k, v in filter_metadata.items()
)
]
# Get top-k indices
if valid_indices:
filtered_sims = [(i, similarities[i]) for i in valid_indices]
top_indices = sorted(filtered_sims, key=lambda x: x[1], reverse=True)[:top_k]
indices, scores = zip(*top_indices) if top_indices else ([], [])
else:
indices, scores = [], []
# Build result
retrieved_docs = [self.documents[i] for i in indices]
return self._build_result(retrieved_docs, list(scores))
def _keyword_retrieve(
self,
query: str,
top_k: int,
filter_metadata: Optional[Dict[str, Any]]
) -> RetrievalResult:
"""Simple keyword-based retrieval fallback"""
query_terms = set(query.lower().split())
# Score documents by keyword overlap
scores = []
for doc in self.documents:
doc_terms = set(doc.content.lower().split())
overlap = len(query_terms & doc_terms)
scores.append(overlap)
# Apply metadata filters
valid_indices = range(len(self.documents))
if filter_metadata:
valid_indices = [
i for i in valid_indices
if all(
self.documents[i].metadata.get(k) == v
for k, v in filter_metadata.items()
)
]
# Get top-k
if valid_indices:
filtered_scores = [(i, scores[i]) for i in valid_indices]
top_indices = sorted(filtered_scores, key=lambda x: x[1], reverse=True)[:top_k]
indices, top_scores = zip(*top_indices) if top_indices else ([], [])
else:
indices, top_scores = [], []
retrieved_docs = [self.documents[i] for i in indices]
return self._build_result(retrieved_docs, list(top_scores))
def _build_result(self, documents: List[Document], scores: List[float]) -> RetrievalResult:
"""Build retrieval result with context and citations"""
# Build context string
context_parts = []
citations = []
for i, (doc, score) in enumerate(zip(documents, scores), 1):
# Truncate long documents
content_preview = doc.content[:500]
if len(doc.content) > 500:
content_preview += "..."
context_parts.append(
f"[{i}] {doc.source}\n{content_preview}\n"
)
citations.append(f"[{i}] {doc.source} (relevance: {score:.2f})")
context = "\n".join(context_parts) if context_parts else "No relevant context found."
return RetrievalResult(
documents=documents,
context=context,
citations=citations,
scores=scores
)
def enrich_query(self, query: str, max_context_length: int = 2000) -> Dict[str, Any]:
"""Enrich a query with retrieved context
Args:
query: User query
max_context_length: Maximum context length to include
Returns:
Dict with enriched_query, context, and citations
"""
result = self.retrieve(query)
# Truncate context if needed
context = result.context
if len(context) > max_context_length:
context = context[:max_context_length] + "..."
enriched_query = f"""{query}
Relevant Context:
{context}
Please use the above context to provide an informed response and cite sources where applicable."""
return {
"enriched_query": enriched_query,
"context": context,
"citations": result.citations,
"num_sources": len(result.documents)
}
# Singleton instance
_rag_pipeline = None
def get_rag_pipeline(
corpus_dir: str = "./docs",
force_reload: bool = False
) -> RAGPipeline:
"""Get or create RAG pipeline singleton
Args:
corpus_dir: Directory containing documents
force_reload: Force reload of the pipeline
Returns:
RAGPipeline instance
"""
global _rag_pipeline
if _rag_pipeline is None or force_reload:
_rag_pipeline = RAGPipeline(corpus_dir=corpus_dir)
return _rag_pipeline
|