Spaces:
Sleeping
Sleeping
| """ | |
| 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") | |