Spaces:
Sleeping
Sleeping
File size: 8,063 Bytes
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 | """
LlamaIndex Integration Examples
Demonstrates usage patterns for the knowledge base
"""
import os
from typing import List, Dict, Any
from .llama_integration import EcoMCPKnowledgeBase, IndexConfig
from .knowledge_base import KnowledgeBase
from .document_loader import DocumentLoader
from .vector_search import VectorSearchEngine
def example_basic_indexing():
"""Example: Basic document indexing"""
print("=== Basic Indexing Example ===")
# Initialize knowledge base
kb = EcoMCPKnowledgeBase()
# Index documents from a directory
docs_path = "./docs"
if os.path.exists(docs_path):
kb.initialize(docs_path)
print(f"Indexed documents from {docs_path}")
else:
print(f"Directory {docs_path} not found")
def example_product_search():
"""Example: Search for products"""
print("\n=== Product Search Example ===")
kb = EcoMCPKnowledgeBase()
# Add sample products
products = [
{
"id": "prod_001",
"name": "Wireless Headphones",
"description": "High-quality noise-canceling wireless headphones",
"price": "$299",
"category": "Electronics",
"features": ["Noise Canceling", "30h Battery", "Bluetooth 5.0"],
"tags": ["audio", "wireless", "premium"]
},
{
"id": "prod_002",
"name": "Laptop Stand",
"description": "Adjustable aluminum laptop stand",
"price": "$49",
"category": "Accessories",
"features": ["Adjustable", "Aluminum", "Portable"],
"tags": ["ergonomic", "desk"]
},
]
kb.add_products(products)
# Search
query = "noise canceling audio equipment"
results = kb.search_products(query, top_k=3)
print(f"\nSearch query: '{query}'")
print(f"Found {len(results)} results:")
for i, result in enumerate(results, 1):
print(f"\n{i}. Score: {result.score:.2f}")
print(f" Content: {result.content[:200]}...")
def example_documentation_search():
"""Example: Search documentation"""
print("\n=== Documentation Search Example ===")
kb = EcoMCPKnowledgeBase()
# Index docs directory
docs_path = "./docs"
if os.path.exists(docs_path):
kb.initialize(docs_path)
# Search
query = "how to deploy"
results = kb.search_documentation(query, top_k=3)
print(f"\nSearch query: '{query}'")
print(f"Found {len(results)} results:")
for i, result in enumerate(results, 1):
print(f"\n{i}. Source: {result.source}")
print(f" Score: {result.score:.2f}")
print(f" Preview: {result.content[:200]}...")
def example_semantic_search():
"""Example: Semantic similarity search"""
print("\n=== Semantic Search Example ===")
kb = EcoMCPKnowledgeBase()
docs_path = "./docs"
if os.path.exists(docs_path):
kb.initialize(docs_path)
# Semantic search with threshold
query = "installation and setup"
results = kb.search_engine.semantic_search(query, top_k=5, similarity_threshold=0.5)
print(f"\nSemantic search for: '{query}'")
print(f"Results with similarity >= 0.5:")
for i, result in enumerate(results, 1):
print(f"{i}. Score: {result.score:.2f} - {result.content[:100]}...")
def example_recommendations():
"""Example: Get recommendations"""
print("\n=== Recommendations Example ===")
kb = EcoMCPKnowledgeBase()
# Add products
products = [
{
"id": "prod_001",
"name": "Wireless Mouse",
"description": "Ergonomic wireless mouse with precision tracking",
"price": "$29",
"category": "Accessories",
"tags": ["mouse", "wireless", "ergonomic"]
},
{
"id": "prod_002",
"name": "Keyboard",
"description": "Mechanical keyboard with RGB lighting",
"price": "$129",
"category": "Accessories",
"tags": ["keyboard", "mechanical", "gaming"]
},
]
kb.add_products(products)
# Get recommendations
query = "I need a wireless input device for programming"
recommendations = kb.get_recommendations(query, recommendation_type="products", limit=3)
print(f"\nUser query: '{query}'")
print("Recommendations:")
for rec in recommendations:
print(f"\n#{rec['rank']}")
print(f"Confidence: {rec['confidence']:.2f}")
print(f"Product: {rec['content'][:150]}...")
def example_hierarchical_search():
"""Example: Multi-level search across types"""
print("\n=== Hierarchical Search Example ===")
kb = EcoMCPKnowledgeBase()
docs_path = "./docs"
# Setup with both docs and products
if os.path.exists(docs_path):
products = [
{
"id": "prod_001",
"name": "E-commerce Platform",
"description": "Complete e-commerce solution",
"category": "Software",
"tags": ["ecommerce", "platform"]
}
]
kb.initialize(docs_path, products=products)
# Hierarchical search
query = "e-commerce"
results = kb.search_engine.hierarchical_search(query, levels=["product", "documentation"])
print(f"\nHierarchical search for: '{query}'")
for level, items in results.items():
print(f"\n{level.upper()}: {len(items)} results")
for item in items[:2]:
print(f" - {item.content[:80]}...")
def example_custom_config():
"""Example: Custom configuration"""
print("\n=== Custom Configuration Example ===")
config = IndexConfig(
embedding_model="text-embedding-3-large",
chunk_size=2048,
chunk_overlap=128,
use_pinecone=False, # Set to True if using Pinecone
)
kb = EcoMCPKnowledgeBase(config=config)
print(f"Knowledge base created with custom config:")
print(f" - Embedding model: {config.embedding_model}")
print(f" - Chunk size: {config.chunk_size}")
print(f" - Vector store: {'Pinecone' if config.use_pinecone else 'In-memory'}")
def example_persistence():
"""Example: Save and load knowledge base"""
print("\n=== Persistence Example ===")
kb = EcoMCPKnowledgeBase()
# Initialize with documents
docs_path = "./docs"
if os.path.exists(docs_path):
kb.initialize(docs_path)
# Save
save_path = "./kb_index"
kb.save(save_path)
print(f"Knowledge base saved to {save_path}")
# Create new instance and load
kb2 = EcoMCPKnowledgeBase()
if kb2.load(save_path):
print("Knowledge base loaded successfully")
# Verify with search
results = kb2.search("test query", top_k=1)
print(f"Loaded index contains {len(results)} search results for test query")
def example_query_engine():
"""Example: Natural language query"""
print("\n=== Query Engine Example ===")
kb = EcoMCPKnowledgeBase()
docs_path = "./docs"
if os.path.exists(docs_path):
kb.initialize(docs_path)
# Natural language query
question = "What are the main features of the platform?"
response = kb.query(question)
print(f"\nQuestion: {question}")
print(f"Response: {response}")
if __name__ == "__main__":
print("LlamaIndex Integration Examples\n")
# Run examples
example_basic_indexing()
example_custom_config()
example_product_search()
example_documentation_search()
example_semantic_search()
example_recommendations()
example_hierarchical_search()
example_persistence()
example_query_engine()
print("\n✓ All examples completed")
|