Spaces:
Sleeping
Sleeping
File size: 12,976 Bytes
108d8af 216bd52 108d8af | 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 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 | """
Knowledge Base Indexing and Retrieval using LlamaIndex
Modern LlamaIndex framework integration with:
- Foundation for knowledge base indexing (VectorStoreIndex, PropertyGraphIndex)
- Vector similarity search with retrieval
- Document retrieval with storage context
- Ingestion pipeline for data processing
"""
import os
from typing import List, Dict, Any, Optional, Union
from pathlib import Path
import logging
from llama_index.core import (
VectorStoreIndex,
SimpleDirectoryReader,
Document,
Settings,
StorageContext,
load_index_from_storage,
)
from llama_index.core.ingestion import IngestionPipeline
from llama_index.core.node_parser import SimpleNodeParser
from llama_index.core.extractors import TitleExtractor, KeywordExtractor
from llama_index.embeddings.openai import OpenAIEmbedding
from llama_index.vector_stores.pinecone import PineconeVectorStore
from llama_index.llms.openai import OpenAI
from pydantic import BaseModel, Field
logger = logging.getLogger(__name__)
class IndexConfig(BaseModel):
"""Configuration for knowledge base index following LlamaIndex best practices"""
# Embedding settings
embedding_model: str = Field(
default="text-embedding-3-small",
description="OpenAI embedding model"
)
# LLM settings
llm_model: str = Field(
default="gpt-4-turbo",
description="OpenAI LLM for query/synthesis"
)
# Chunking settings
chunk_size: int = Field(
default=1024,
description="Size of text chunks"
)
chunk_overlap: int = Field(
default=20,
description="Overlap between chunks"
)
# Vector store backend
use_pinecone: bool = Field(
default=False,
description="Use Pinecone for vector store"
)
pinecone_index_name: str = Field(
default="ecomcp-knowledge",
description="Pinecone index name"
)
pinecone_dimension: int = Field(
default=1536,
description="Dimension for embeddings"
)
# Retrieval settings
similarity_top_k: int = Field(
default=5,
description="Number of similar items to retrieve"
)
# Storage settings
persist_dir: str = Field(
default="./kb_storage",
description="Directory for persisting index"
)
class KnowledgeBase:
"""
Knowledge base for indexing and retrieving product/documentation information
"""
def __init__(self, config: Optional[IndexConfig] = None):
"""
Initialize knowledge base with modern LlamaIndex patterns
Args:
config: IndexConfig object for customization
"""
self.config = config or IndexConfig()
self.index = None
self.retriever = None
self.storage_context = None
self.ingestion_pipeline = None
self._setup_models()
self._setup_ingestion_pipeline()
def _setup_models(self):
"""Configure LLM and embedding models following LlamaIndex patterns"""
api_key = os.getenv("OPENAI_API_KEY")
if not api_key:
logger.warning("OPENAI_API_KEY not set. Models may not work.")
# Setup embedding model
self.embed_model = OpenAIEmbedding(
model=self.config.embedding_model,
api_key=api_key,
)
# Setup LLM
self.llm = OpenAI(
model=self.config.llm_model,
api_key=api_key,
)
# Configure global settings for LlamaIndex
Settings.embed_model = self.embed_model
Settings.llm = self.llm
Settings.chunk_size = self.config.chunk_size
Settings.chunk_overlap = self.config.chunk_overlap
def _setup_ingestion_pipeline(self):
"""Setup ingestion pipeline with metadata extraction"""
# Create node parser with metadata extraction
node_parser = SimpleNodeParser.from_defaults(
chunk_size=self.config.chunk_size,
chunk_overlap=self.config.chunk_overlap,
)
# Create metadata extractors
extractors = [
TitleExtractor(nodes=5),
KeywordExtractor(keywords=10),
]
# Create pipeline
self.ingestion_pipeline = IngestionPipeline(
transformations=[node_parser] + extractors,
)
def index_documents(self, documents_path: str) -> VectorStoreIndex:
"""
Index documents from a directory using ingestion pipeline
Args:
documents_path: Path to directory containing documents
Returns:
VectorStoreIndex: Indexed documents
"""
logger.info(f"Indexing documents from {documents_path}")
if not os.path.exists(documents_path):
logger.error(f"Document path not found: {documents_path}")
raise FileNotFoundError(f"Document path not found: {documents_path}")
# Load documents
reader = SimpleDirectoryReader(documents_path)
documents = reader.load_data()
logger.info(f"Loaded {len(documents)} documents")
# Process through ingestion pipeline
nodes = self.ingestion_pipeline.run(documents=documents)
logger.info(f"Processed into {len(nodes)} nodes with metadata")
# Create storage context
if self.config.use_pinecone:
self.storage_context = self._create_pinecone_storage()
else:
self.storage_context = StorageContext.from_defaults()
# Create index from nodes
self.index = VectorStoreIndex(
nodes=nodes,
storage_context=self.storage_context,
show_progress=True,
)
# Create retriever with configured top_k
self.retriever = self.index.as_retriever(
similarity_top_k=self.config.similarity_top_k
)
logger.info(f"Index created successfully with {len(nodes)} nodes")
return self.index
def _create_pinecone_storage(self) -> StorageContext:
"""
Create Pinecone-backed storage context
Returns:
StorageContext backed by Pinecone
"""
try:
from pinecone import Pinecone
api_key = os.getenv("PINECONE_API_KEY")
if not api_key:
logger.warning("PINECONE_API_KEY not set. Falling back to in-memory storage.")
return StorageContext.from_defaults()
pc = Pinecone(api_key=api_key)
# Get or create index
index_name = self.config.pinecone_index_name
if index_name not in pc.list_indexes().names():
logger.info(f"Creating Pinecone index: {index_name}")
pc.create_index(
name=index_name,
dimension=self.config.pinecone_dimension,
metric="cosine"
)
pinecone_index = pc.Index(index_name)
vector_store = PineconeVectorStore(pinecone_index=pinecone_index)
return StorageContext.from_defaults(vector_store=vector_store)
except ImportError:
logger.warning("Pinecone not available. Falling back to in-memory storage.")
return StorageContext.from_defaults()
def add_documents(self, documents: List[Document]) -> None:
"""
Add documents to existing index
Args:
documents: List of documents to add
"""
if self.index is None:
raise ValueError("Index not initialized. Call index_documents() first.")
logger.info(f"Adding {len(documents)} documents to index")
for doc in documents:
self.index.insert(doc)
def search(self, query: str, top_k: int = 5) -> List[Dict[str, Any]]:
"""
Search knowledge base by query
Args:
query: Search query string
top_k: Number of top results to return
Returns:
List of results with score and content
"""
if self.index is None:
logger.error("Index not initialized")
return []
try:
results = self.index.as_retriever(similarity_top_k=top_k).retrieve(query)
output = []
for node in results:
output.append({
"content": node.get_content(),
"score": node.score if hasattr(node, 'score') else None,
"metadata": node.metadata if hasattr(node, 'metadata') else {},
})
return output
except Exception as e:
logger.error(f"Search error: {e}")
return []
def query(self, query_str: str, top_k: Optional[int] = None) -> str:
"""
Query knowledge base with natural language using query engine
Args:
query_str: Natural language query
top_k: Number of top results to use (uses config if not specified)
Returns:
Query response string
"""
if self.index is None:
return "Index not initialized"
try:
if top_k is None:
top_k = self.config.similarity_top_k
# Create query engine with response synthesis
query_engine = self.index.as_query_engine(
similarity_top_k=top_k,
response_mode="compact", # or "tree_summarize", "refine"
)
response = query_engine.query(query_str)
return str(response)
except Exception as e:
logger.error(f"Query error: {e}")
return f"Error processing query: {e}"
def chat(self, messages: List[Dict[str, str]]) -> str:
"""
Multi-turn chat with knowledge base
Args:
messages: List of messages in format [{"role": "user", "content": "..."}, ...]
Returns:
Chat response string
"""
if self.index is None:
return "Index not initialized"
try:
# Create chat engine for conversational interface
chat_engine = self.index.as_chat_engine()
# Process last user message
last_message = None
for msg in reversed(messages):
if msg.get("role") == "user":
last_message = msg.get("content")
break
if not last_message:
return "No user message found"
response = chat_engine.chat(last_message)
return str(response)
except Exception as e:
logger.error(f"Chat error: {e}")
return f"Error processing chat: {e}"
def save_index(self, output_path: str) -> None:
"""
Save index to disk
Args:
output_path: Path to save index
"""
if self.index is None:
logger.warning("No index to save")
return
Path(output_path).mkdir(parents=True, exist_ok=True)
self.index.storage_context.persist(persist_dir=output_path)
logger.info(f"Index saved to {output_path}")
def load_index(self, input_path: str) -> VectorStoreIndex:
"""
Load index from disk
Args:
input_path: Path to saved index
Returns:
Loaded VectorStoreIndex
"""
if not os.path.exists(input_path):
logger.error(f"Index path not found: {input_path}")
raise FileNotFoundError(f"Index path not found: {input_path}")
# Load storage context from disk
self.storage_context = StorageContext.from_defaults(persist_dir=input_path)
self.index = load_index_from_storage(
self.storage_context,
settings=Settings, # Use current settings
)
self.retriever = self.index.as_retriever(
similarity_top_k=self.config.similarity_top_k
)
logger.info(f"Index loaded from {input_path}")
return self.index
def get_index_info(self) -> Dict[str, Any]:
"""Get information about current index"""
if self.index is None:
return {"status": "No index loaded"}
return {
"status": "Index loaded",
"embedding_model": self.config.embedding_model,
"chunk_size": self.config.chunk_size,
"vector_store": "Pinecone" if self.config.use_pinecone else "In-memory",
}
|