### Installing KG-RAG Dependencies with uv (Recommended) - Bash Source: https://github.com/vectorinstitute/kg-rag/blob/main/README.md Clones the repository, installs the uv package manager, and uses uv to synchronize project dependencies into a virtual environment, activating it. ```bash # Clone the repository git clone https://github.com/yourusername/kg-rag.git cd kg-rag # Install uv if you don't have it curl -sSf https://astral.sh/uv/install.sh | bash uv sync source .venv/bin/activate ``` -------------------------------- ### System Usage Example - Python Source: https://github.com/vectorinstitute/kg-rag/blob/main/kg_rag/methods/graphrag_based/README.md Demonstrates how to initialize the GraphRAG-based KG-RAG system using the `create_graphrag_system` function with various configuration parameters and how to perform a query against the system. ```python from kg_rag.methods.graphrag_based.kg_rag import create_graphrag_system # Create the GraphRAG system graphrag = create_graphrag_system( artifacts_path="data/graphrag_artifacts.pkl", vector_store_dir="vector_stores", llm_model="gpt-4o", search_strategy="local", community_level=2, use_cot=True, numerical_answer=False, verbose=True ) # Query the system result = graphrag.query("What was Apple's revenue in Q3 2023?") print(result["answer"]) ``` -------------------------------- ### Installing KG-RAG Development Dependencies with uv - Bash Source: https://github.com/vectorinstitute/kg-rag/blob/main/README.md Uses uv to synchronize development dependencies into the virtual environment and activates it. This is for contributors working on the project. ```bash uv sync --dev source .venv/bin/activate ``` -------------------------------- ### Using EntityBasedKGRAG in Python Source: https://github.com/vectorinstitute/kg-rag/blob/main/kg_rag/methods/entity_based/README.md This example demonstrates how to initialize and use the EntityBasedKGRAG system. It involves loading documents and graph data, initializing the language model, configuring the KG-RAG instance with various parameters, and executing a query. ```python from langchain_openai import ChatOpenAI from kg_rag.methods.entity_based.kg_rag import EntityBasedKGRAG from kg_rag.utils.document_loader import load_documents, load_graph_documents from kg_rag.utils.graph_utils import create_graph_from_graph_documents # Load documents and graph documents = load_documents( directory_path="data/docs", pickle_path="data/graphs/documents.pkl", ) graph_documents = load_graph_documents("data/graphs/graph_documents.pkl") graph = create_graph_from_graph_documents(graph_documents) # Initialize LLM llm = ChatOpenAI(temperature=0, model_name="gpt-4o") # Create KG-RAG system kg_rag = EntityBasedKGRAG( graph=graph, graph_documents=graph_documents, document_chunks=documents, llm=llm, top_k_nodes=10, top_k_chunks=5, similarity_threshold=0.7, node_freq_weight=0.4, node_sim_weight=0.6, use_cot=True, numerical_answer=False, verbose=True, ) # Query the system result = kg_rag.query("What was Apple's revenue in Q3 2023?") print(f"Answer: {result['answer']}") print(f"Reasoning: {result['reasoning']}") ``` -------------------------------- ### Example Cypher Queries for Neo4j KG-RAG Source: https://github.com/vectorinstitute/kg-rag/blob/main/kg_rag/methods/cypher_based/README.md Provides example Cypher queries used to retrieve specific information from the Neo4j knowledge graph within the KG-RAG system. Demonstrates querying for related entities, assets, and specific financial data based on node properties. ```Cypher // Finding entities related to a specific company MATCH p=()-[]->(n:Company)-[]->() WHERE n.id = "Nvidia Corporation" RETURN p LIMIT 50 // Finding assets of a company MATCH p=(n:Company)-[r:HAS]->(a) WHERE n.id = "Nvidia Corporation" RETURN p LIMIT 25 // Finding specific financial data MATCH (d:Date)-[r:BEGINNING_CASH_BALANCE]->(a:Amount) WHERE d.id = "April 1, 2023" RETURN a.id LIMIT 1 ``` -------------------------------- ### Initializing BaselineRAG Pipeline in Python Source: https://github.com/vectorinstitute/kg-rag/blob/main/kg_rag/methods/baseline_rag/README.md Initializes the main BaselineRAG class, orchestrating the entire RAG pipeline. Sets up configuration options for the vector store, generation model, embedding model, retrieval parameters (top_k), and prompting strategies (COT, numerical answer). ```python class BaselineRAG: def __init__(self, collection_name: str = "document_collection", chroma_persist_dir: str = "chroma_db", model_name: str = "gpt-4o", embedding_model: str = "text-embedding-3-small", top_k: int = 5, use_cot: bool = False, numerical_answer: bool = False, verbose: bool = False): # Initialize components and settings ``` -------------------------------- ### Running Interactive Query Mode for Baseline RAG - Bash Source: https://github.com/vectorinstitute/kg-rag/blob/main/README.md Launches an interactive command-line interface to query the baseline RAG system using the previously built vector store and a specified language model. ```bash python -m scripts.run_baseline_rag \ --collection-name sec_10q \ --persist-dir chroma_db \ --model gpt-4o \ --verbose ``` -------------------------------- ### Running Pre-commit Hooks (Bash) Source: https://github.com/vectorinstitute/kg-rag/blob/main/CONTRIBUTING.md This command executes all configured pre-commit hooks on all files in the repository. It is used after setting up the Python virtual environment to automatically check code for style, formatting, and potential issues before committing changes. ```bash pre-commit run --all-files ``` -------------------------------- ### Initializing DocumentProcessor in Python Source: https://github.com/vectorinstitute/kg-rag/blob/main/kg_rag/methods/baseline_rag/README.md Initializes the DocumentProcessor class, setting up a text splitter with configurable chunk size and overlap for processing documents. Includes a verbose option for detailed output. ```python class DocumentProcessor: def __init__(self, chunk_size: int = 512, chunk_overlap: int = 24, verbose: bool = False): self.text_splitter = TokenTextSplitter(chunk_size=chunk_size, chunk_overlap=chunk_overlap) self.verbose = verbose ``` -------------------------------- ### Running Interactive Query Mode for Entity KG-RAG - Bash Source: https://github.com/vectorinstitute/kg-rag/blob/main/README.md Launches an interactive command-line interface to query the entity-based KG-RAG system using a specified knowledge graph file and configuration parameters like beam width and max depth. ```bash python -m scripts.run_entity_rag \ --graph-path data/graphs/sec10q_entity_graph.pkl \ --beam-width 10 \ --max-depth 8 \ --top-k 100 \ --verbose ``` -------------------------------- ### Building Vector Store with Python Script Source: https://github.com/vectorinstitute/kg-rag/blob/main/kg_rag/methods/baseline_rag/README.md Executes the Python script `scripts.build_baseline_vectordb` to create a vector database. Specifies the directory containing documents, the collection name, the persistence directory for the database, and enables verbose output. Requires a Python environment with necessary libraries and the specified script. ```bash python -m scripts.build_baseline_vectordb \ --docs-dir data/sec-10-q/docs \ --collection-name sec_10q \ --persist-dir chroma_db \ --verbose ``` -------------------------------- ### Running RAG Evaluation with Python Script Source: https://github.com/vectorinstitute/kg-rag/blob/main/kg_rag/methods/baseline_rag/README.md Executes the Python script `kg_rag.evaluation.run_evaluation` to evaluate the RAG system. Specifies the path to the test questions CSV, the evaluation method (baseline), the path to the configuration file, the output directory for results, and flags for handling numerical answers and using chain-of-thought. Requires a Python environment, the script, test data, and configuration. ```bash python -m kg_rag.evaluation.run_evaluation \ --data-path data/test_questions.csv \ --method baseline \ --config-path kg_rag/configs/baseline-kgrag.json \ --output-dir evaluation_results \ --numerical-answer \ --use-cot ``` -------------------------------- ### Running RAG Queries with Python Script Source: https://github.com/vectorinstitute/kg-rag/blob/main/kg_rag/methods/baseline_rag/README.md Executes the Python script `scripts.run_baseline_rag` to perform RAG queries. Specifies the collection name, the persistence directory of the database, the language model to use (gpt-4o), the number of top results to retrieve (top-k), and enables verbose output. Requires a Python environment, the script, an existing database, and access to the specified model. ```bash python -m scripts.run_baseline_rag \ --collection-name sec_10q \ --persist-dir chroma_db \ --model gpt-4o \ --top-k 5 \ --verbose ``` -------------------------------- ### Initializing Default Context Builder in Python Source: https://github.com/vectorinstitute/kg-rag/blob/main/kg_rag/methods/graphrag_based/README.md This snippet initializes the default `ContextBuilder`. This component is responsible for assembling the retrieved information into a structured context for the LLM, optimizing for relevance, coherence, and length constraints. ```Python # Context building self.context_builder = ContextBuilder.build_default( token_counter=TiktokenCounter(), ) ``` -------------------------------- ### Setting Neo4j Environment Variables for Cypher Approach - Bash Source: https://github.com/vectorinstitute/kg-rag/blob/main/README.md Exports environment variables for connecting to a Neo4j database, including URI, username, and password, necessary for the Cypher-based KG-RAG method. ```bash NEO4J_URI=bolt://localhost:7687 NEO4J_USER=neo4j NEO4J_PASSWORD=your_password ``` -------------------------------- ### Initializing Global Search Strategy in Python Source: https://github.com/vectorinstitute/kg-rag/blob/main/kg_rag/methods/graphrag_based/README.md This code initializes the `GlobalSearchStrategy`. This strategy takes a broader approach, identifying relevant communities across the entire graph and aggregating key points for context building. ```Python # Global search implementation self.global_search = GlobalSearchStrategy( llm=self.llm, artifacts=artifacts, community_level=community_level, token_counter=self.token_counter, show_references=show_references, verbose=verbose, strict_output_format=(use_cot or numerical_answer), ) ``` -------------------------------- ### Initializing ChromaDBManager Vector Store in Python Source: https://github.com/vectorinstitute/kg-rag/blob/main/kg_rag/methods/baseline_rag/README.md Initializes the ChromaDBManager class to manage persistent storage and retrieval of document chunks and embeddings using ChromaDB. Configures collection name, persistence directory, batch size, and verbosity. ```python class ChromaDBManager: def __init__(self, collection_name: str, persist_directory: str = "chroma_db", batch_size: int = 100, verbose: bool = False): self.client = chromadb.PersistentClient(path=persist_directory) self.collection_name = collection_name # Additional initialization... ``` -------------------------------- ### Running Pre-commit Hooks - Bash Source: https://github.com/vectorinstitute/kg-rag/blob/main/README.md Executes all configured pre-commit hooks on all files in the repository to ensure code quality and consistency before commits. ```bash pre-commit run --all-files ``` -------------------------------- ### Building Vector Store for Baseline RAG Methods - Bash Source: https://github.com/vectorinstitute/kg-rag/blob/main/README.md Runs a Python script to process documents from a specified directory and build a vector database collection for use with baseline RAG methods. ```bash python -m scripts.build_baseline_vectordb \ --docs-dir data/sec-10-q/docs \ --collection-name sec_10q \ --persist-dir chroma_db \ --verbose ``` -------------------------------- ### Running Project Tests - Bash Source: https://github.com/vectorinstitute/kg-rag/blob/main/README.md Executes the project's test suite using pytest to verify functionality. ```bash pytest ``` -------------------------------- ### Running Evaluation of RAG Methods - Bash Source: https://github.com/vectorinstitute/kg-rag/blob/main/README.md Executes a Python script to evaluate the performance of various RAG methods (baseline and KG-RAG) on a test dataset, saving results to an output directory. ```bash python -m kg_rag.evaluation.run_evaluation \ --data-path data/test_questions.csv \ --graph-path data/graphs/sec10q_entity_graph.pkl \ --method all \ --output-dir evaluation_results \ --collection-name sec_10q \ --persist-dir chroma_db \ --max-samples 50 \ --verbose ``` -------------------------------- ### Building Neo4j Knowledge Graph (Bash) Source: https://github.com/vectorinstitute/kg-rag/blob/main/kg_rag/methods/cypher_based/README.md Executes the Python script to construct the Neo4j knowledge graph from source documents. Specifies input document directory, output graph directory, Neo4j connection details (URI and user), and enables verbose output. ```Bash python -m scripts.build_cypher_graph \ --docs-dir data/sec-10-q/docs \ --output-dir data/graphs \ --neo4j-uri bolt://localhost:7687 \ --neo4j-user neo4j \ --verbose ``` -------------------------------- ### Running KG-RAG Queries (Bash) Source: https://github.com/vectorinstitute/kg-rag/blob/main/kg_rag/methods/cypher_based/README.md Executes the Python script to run the end-to-end KG-RAG query process. Connects to the Neo4j database, sets parameters for graph traversal depth and hops, and enables verbose output for debugging. ```Bash python -m scripts.run_cypher_rag \ --neo4j-uri bolt://localhost:7687 \ --neo4j-user neo4j \ --max-depth 2 \ --max-hops 3 \ --verbose ``` -------------------------------- ### Setting OpenAI API Key Environment Variable - Bash Source: https://github.com/vectorinstitute/kg-rag/blob/main/README.md Exports the `OPENAI_API_KEY` environment variable, required for methods utilizing OpenAI models. ```bash OPENAI_API_KEY=your_openai_api_key ``` -------------------------------- ### Building Knowledge Graph for KG-RAG Methods - Bash Source: https://github.com/vectorinstitute/kg-rag/blob/main/README.md Runs a Python script to process documents and build an entity-based knowledge graph, saving it to a specified output directory for use with KG-RAG methods. ```bash python -m scripts.build_entity_graph \ --docs-dir data/sec-10-q/docs \ --output-dir data/graphs \ --graph-name sec10q_entity_graph \ --verbose ``` -------------------------------- ### Indexer Artifacts Structure - Python Source: https://github.com/vectorinstitute/kg-rag/blob/main/kg_rag/methods/graphrag_based/README.md Illustrates the expected dictionary structure for artifacts generated during the indexing process, including placeholders for entity data, relationship data, community data at multiple levels, and document text units. ```python # Artifacts structure generated during indexing artifacts = { "entities": {...}, # Entity data "relationships": {...}, # Relationship data "communities": {...}, # Community data at multiple levels "text_units": {...} # Document text units } ``` -------------------------------- ### Running Hyperparameter Search for KG-RAG Methods - Bash Source: https://github.com/vectorinstitute/kg-rag/blob/main/README.md Executes a Python script to perform a hyperparameter search for a specific KG-RAG method (e.g., entity-based) using a configuration file and a test dataset. ```bash python -m kg_rag.evaluation.hyperparameter_search \ --data-path data/test_questions.csv \ --graph-path data/graphs/sec10q_entity_graph.pkl \ --method entity \ --configs-path kg_rag/evaluation/hyperparameter_configs.json \ --output-dir hyperparameter_search \ --max-samples 10 \ --verbose ``` -------------------------------- ### Initializing OpenAIEmbedding Handler in Python Source: https://github.com/vectorinstitute/kg-rag/blob/main/kg_rag/methods/baseline_rag/README.md Initializes the OpenAIEmbedding class for generating vector embeddings using specified OpenAI models. Configures API key, model name, batching parameters, rate limit handling, and verbosity. ```python class OpenAIEmbedding: def __init__(self, api_key: str, model: str = "text-embedding-3-small", batch_size: int = 100, max_tokens_per_batch: int = 8000, rate_limit_pause: float = 60.0, verbose: bool = False): # Initialize with OpenAI client and configuration ``` -------------------------------- ### Initializing Local Search Strategy in Python Source: https://github.com/vectorinstitute/kg-rag/blob/main/kg_rag/methods/graphrag_based/README.md This snippet shows the initialization of the `LocalSearchStrategy`. This strategy focuses on retrieving relevant information from the immediate neighborhood of matched entities within specific communities. ```Python # Local search implementation self.local_search = LocalSearchStrategy( llm=self.llm, entities_vector_store=entities_vector_store, artifacts=artifacts, community_level=community_level, show_references=show_references, verbose=verbose, system_prompt=system_prompt, strict_output_format=(use_cot or numerical_answer), ) ``` -------------------------------- ### Format Context from Paths and Chunks in Python Source: https://github.com/vectorinstitute/kg-rag/blob/main/kg_rag/methods/entity_based/README.md Assembles a formatted string context by combining knowledge graph path descriptions and document chunk content. Includes source information for chunks. ```python def _format_context(self, paths: list[str], chunks: list[Document]) -> str: context_lines = [] # Add knowledge paths if paths: context_lines.append("=== KNOWLEDGE GRAPH INFORMATION ===") for i, path in enumerate(paths): context_lines.append(f"Path {i + 1}: {path}") context_lines.append("") # Add document chunks if chunks: context_lines.append("=== DOCUMENT CHUNKS ===") for i, chunk in enumerate(chunks): content = chunk.page_content source = chunk.metadata.get("source", chunk.metadata.get("file_path", "unknown")) page = chunk.metadata.get("page", "") source_info = f"[Source: {source}" if page: source_info += f", Page: {page}" source_info += "]" context_lines.append(f"Chunk {i + 1}: {source_info}") context_lines.append(content) context_lines.append("---") return "\n".join(context_lines) ``` -------------------------------- ### Running Project Tests with Coverage - Bash Source: https://github.com/vectorinstitute/kg-rag/blob/main/README.md Executes the project's test suite using pytest and generates a coverage report to show which parts of the code are covered by tests. ```bash pytest --cov=kg_rag tests/ ``` -------------------------------- ### Searching for Similar Entities in Python Source: https://github.com/vectorinstitute/kg-rag/blob/main/kg_rag/methods/graphrag_based/README.md This snippet demonstrates how to use a vector store to find entities similar to a given query. It utilizes the `similarity_search` method, limiting the results to the top `k` matches. ```Python # The query is processed to find similar entities in the vector store similar_entities = entities_vector_store.similarity_search(query, k=top_k) ``` -------------------------------- ### Query RAG System with LLM Generation in Python Source: https://github.com/vectorinstitute/kg-rag/blob/main/kg_rag/methods/entity_based/README.md The main query method orchestrating the RAG process. It formats the context from knowledge graph paths and selected chunks and invokes the LLM to generate a response. ```python def query(self, question: str) -> Any: # ... (steps 1-5 as described above) # Format context context = self._format_context(paths, top_chunks) # Create prompt messages = create_query_prompt( question=question, context=context, system_type="entity", use_cot=self.use_cot, numerical_answer=self.numerical_answer, ) # Generate answer using LLM response = self.llm.invoke(messages) return self._process_results(response, nodes, paths, top_chunks) ``` -------------------------------- ### Invoking LLM for Response Generation in Python Source: https://github.com/vectorinstitute/kg-rag/blob/main/kg_rag/methods/graphrag_based/README.md This code demonstrates how to invoke the large language model (LLM) to generate the final answer. It passes the prepared `messages` (containing the context and query) to the LLM's `invoke` method. ```Python # Generate the final answer response = self.llm.invoke(messages) ``` -------------------------------- ### Local Search Strategy Class Definition - Python Source: https://github.com/vectorinstitute/kg-rag/blob/main/kg_rag/methods/graphrag_based/README.md Defines the `LocalSearchStrategy` class, outlining its constructor parameters for initializing the local search mechanism within the GraphRAG-based system. It includes dependencies like a language model, entity vector store, and the indexed artifacts. ```python class LocalSearchStrategy: """Local search strategy for GraphRAG.""" def __init__( self, llm: ChatOpenAI, entities_vector_store: Chroma, artifacts: IndexerArtifacts, community_level: int = 2, show_references: bool = True, verbose: bool = False, system_prompt: str | None = None, strict_output_format: bool = False, ): ... def search(self, query: str) -> Any: """Perform local search.""" ... ``` -------------------------------- ### Global Search Strategy Class Definition - Python Source: https://github.com/vectorinstitute/kg-rag/blob/main/kg_rag/methods/graphrag_based/README.md Defines the `GlobalSearchStrategy` class, detailing its constructor parameters for initializing the global search mechanism used in the GraphRAG-based system. It requires a language model and the indexed artifacts. ```python class GlobalSearchStrategy: """Global search strategy for GraphRAG.""" def __init__( self, llm: ChatOpenAI, artifacts: IndexerArtifacts, community_level: int = 2, token_counter: TiktokenCounter | None = None, show_references: bool = True, verbose: bool = False, strict_output_format: bool = False, ): ... def search(self, query: str) -> str: """Perform global search.""" ... ``` -------------------------------- ### Initializing Hierarchical Community Detector in Python Source: https://github.com/vectorinstitute/kg-rag/blob/main/kg_rag/methods/graphrag_based/README.md This code initializes a `HierarchicalLeidenCommunityDetector` instance. This component is responsible for identifying densely connected subgraphs within the knowledge graph during the indexing phase. ```Python # Community detection is performed during indexing self.community_detector = HierarchicalLeidenCommunityDetector() ``` -------------------------------- ### Embedding Query with OpenAI Python Source: https://github.com/vectorinstitute/kg-rag/blob/main/kg_rag/methods/entity_based/README.md This line of code demonstrates how the input question is converted into a numerical vector representation. It utilizes an embedding handler object, likely wrapping a model like OpenAI's text-embedding-3-small, to perform the embedding and stores the result as a NumPy array. ```python query_embedding = np.array(self.embedding_handler.embedder.embed_query(question)) ``` -------------------------------- ### Exploring Knowledge Graph Subgraph Python Source: https://github.com/vectorinstitute/kg-rag/blob/main/kg_rag/methods/entity_based/README.md This private method constructs a relevant subgraph around a set of initial nodes within the knowledge graph. It iteratively expands the set of nodes by including predecessors and successors up to a specified maximum number of hops, effectively capturing the local neighborhood and relationships relevant to the query. It requires a NetworkX graph object (self.graph). ```python def _get_subgraph(self, nodes: list[str], max_hops: int = 1) -> nx.DiGraph: if not nodes: return nx.DiGraph() nodes_to_include = set(nodes) for _ in range(max_hops): new_nodes = set() for node in nodes_to_include: if node in self.graph: new_nodes.update(self.graph.predecessors(node)) new_nodes.update(self.graph.successors(node)) nodes_to_include.update(new_nodes) return self.graph.subgraph(nodes_to_include) ``` -------------------------------- ### Finding Similar Knowledge Graph Nodes Python Source: https://github.com/vectorinstitute/kg-rag/blob/main/kg_rag/methods/entity_based/README.md This private method identifies knowledge graph entities semantically similar to the query embedding. It iterates through pre-computed entity embeddings, calculates cosine similarity, filters nodes above a threshold, sorts them by similarity, and returns the top-k nodes along with their scores. It depends on the embedding_handler and pre-computed entity_embeddings. ```python def _get_similar_nodes(self, query_embedding: np.ndarray) -> list[tuple[str, float]]: similarities = [] for node, embedding in self.embedding_handler.entity_embeddings.items(): similarity = self.embedding_handler.compute_similarity(query_embedding, embedding) if similarity >= self.similarity_threshold: similarities.append((node, similarity)) similarities.sort(key=lambda x: x[1], reverse=True) return similarities[:self.top_k_nodes] ``` -------------------------------- ### Score Chunks by Node Frequency and Similarity in Python Source: https://github.com/vectorinstitute/kg-rag/blob/main/kg_rag/methods/entity_based/README.md Scores a list of document chunks based on the frequency and average similarity of the entities they contain relative to the query. Uses weighted combination of frequency and similarity scores. ```python def _score_chunks_by_nodes(self, chunks: list[Document], node_info: list[tuple[str, float]]) -> list[tuple[Document, float]]: node_scores = dict(node_info) nodes = list(node_scores.keys()) chunk_to_nodes: dict[int, set[str]] = {id(chunk): set() for chunk in chunks} # Map chunks to nodes for _, chunk in enumerate(chunks): chunk_id = id(chunk) orig_idx = None for i, orig_chunk in enumerate(self.document_chunks): if chunk is orig_chunk: orig_idx = i break if orig_idx is not None: for node in nodes: if (node in self.entity_chunk_map and orig_idx in self.entity_chunk_map[node]): chunk_to_nodes[chunk_id].add(node) # Score each chunk chunk_scores = [] for chunk in chunks: chunk_id = id(chunk) referencing_nodes = chunk_to_nodes[chunk_id] if not referencing_nodes: chunk_scores.append((chunk, 0.0)) continue # Calculate frequency score freq_score = len(referencing_nodes) / len(nodes) if nodes else 0 # Calculate similarity score sim_score = sum(node_scores.get(node, 0) for node in referencing_nodes) / len(referencing_nodes) # Combined weighted score combined_score = (self.node_freq_weight * freq_score) + (self.node_sim_weight * sim_score) chunk_scores.append((chunk, combined_score)) return chunk_scores ``` -------------------------------- ### Retrieve Chunks for Nodes in Python Source: https://github.com/vectorinstitute/kg-rag/blob/main/kg_rag/methods/entity_based/README.md Retrieves the unique indices of document chunks that contain any of the specified graph nodes (entities) using an entity-to-chunk mapping. ```python def _get_chunks_for_nodes(self, nodes: list[str]) -> list[int]: chunk_indices = set() for node in nodes: if node in self.entity_chunk_map: chunk_indices.update(self.entity_chunk_map[node]) return list(chunk_indices) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.