Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Question]: Building multiple indexes #16584

Open
1 task done
NguyenDinhTiem opened this issue Oct 17, 2024 · 9 comments
Open
1 task done

[Question]: Building multiple indexes #16584

NguyenDinhTiem opened this issue Oct 17, 2024 · 9 comments
Labels
question Further information is requested

Comments

@NguyenDinhTiem
Copy link

Question Validation

  • I have searched both the documentation and discord for an answer.

Question

Tôi tạo và lưu trữ nhiều loại indexes từ nodes, điều này có vấn đề gì không?
def build_indexes(nodes, persist_dir):
try:
storage_context = StorageContext.from_defaults(
persist_dir=persist_dir
)

    vector_index = load_index_from_storage(
        storage_context, index_id="vector"
    )
    
    summary_index = load_index_from_storage(
        storage_context, index_id="summary"
    )
    
    document_summary_index = load_index_from_storage(
        storage_context, index_id="documentsummary"
    )
    
    tree_index = load_index_from_storage(
        storage_context, index_id="tree"
    )
    
    key_index = load_index_from_storage(
        storage_context, index_id="key"
    )
    
    proper_graph_index = load_index_from_storage(
        storage_context, index_id="propergraph"
    )
    
    knowledge_graph_index = load_index_from_storage(
        storage_context, index_id="knowledgegraph"
    )
    
    print("All indices loaded from storage.")
except Exception as e:
    print(f"Error occurred while loading indices: {e}")
    storage_context = StorageContext.from_defaults()
    
    vector_index = VectorStoreIndex(
        nodes, storage_context=storage_context, show_progress=True
    )
    vector_index.set_index_id("vector")
    
    summary_index = SummaryIndex(
        nodes, storage_context=storage_context, show_progress=True

    )
    summary_index.set_index_id("summary")
    
    document_summary_index = DocumentSummaryIndex(
        nodes, storage_context=storage_context, show_progress=True

    )
    document_summary_index.set_index_id("documentsummary")
    
    tree_index = TreeIndex(
        nodes, storage_context=storage_context, show_progress=True
    )
    tree_index.set_index_id("tree")
    
    key_index = KeywordTableIndex(
        nodes, storage_context=storage_context, show_progress=True
    )
    key_index.set_index_id("key")
    
    proper_graph_index = PropertyGraphIndex(
        nodes, storage_context=storage_context, show_progress=True
    )
    proper_graph_index.set_index_id("propergraph")
    
    knowledge_graph_index = KnowledgeGraphIndex(
        nodes, storage_context=storage_context, show_progress=True
    )
    knowledge_graph_index.set_index_id("knowledgegraph")
    
    storage_context.persist(
        persist_dir=persist_dir
    )
return vector_index, summary_index, document_summary_index, tree_index, key_index, proper_graph_index, knowledge_graph_index
@NguyenDinhTiem NguyenDinhTiem added the question Further information is requested label Oct 17, 2024
Copy link

dosubot bot commented Oct 17, 2024

Khi tạo và lưu trữ nhiều loại indexes từ nodes trong LlamaIndex framework, có một số vấn đề và hạn chế tiềm ẩn mà bạn cần lưu ý:

  1. Quản lý ID của Index: Khi lưu trữ nhiều indexes vào cùng một thư mục, cần theo dõi ID của từng index để tải đúng dữ liệu. Nếu không chỉ định đúng ID khi tải, có thể dẫn đến việc truy xuất dữ liệu không chính xác [1].

  2. Cấu hình Storage Context: Nếu sử dụng backend từ xa hoặc các backend lưu trữ thay thế, cấu hình phải nhất quán trong suốt quá trình hoạt động. Sai cấu hình có thể dẫn đến việc dữ liệu không được lưu trữ hoặc tải đúng cách [1].

  3. Đồng thời và Ghi đè: Nếu nhiều tiến trình cố gắng lưu trữ indexes vào cùng một thư mục mà không có sự đồng bộ hóa thích hợp, có nguy cơ dữ liệu bị ghi đè hoặc hỏng [1].

  4. Giới hạn của Backend: Các backend lưu trữ khác nhau có thể có giới hạn hoặc yêu cầu riêng, như giới hạn kích thước, quyền truy cập, hoặc hạn chế về hiệu suất, có thể ảnh hưởng đến việc lưu trữ đồng thời nhiều indexes [1].

  5. Vấn đề chồng chất dữ liệu: Có một vấn đề là các mục trong docstore.json có thể chồng chất ngay cả khi cùng một tài liệu được index lại, dẫn đến trùng lặp dữ liệu và có thể gây ra sự không nhất quán [1].

  6. Sử dụng nhiều thư mục lưu trữ: Để tránh vấn đề chồng chất, nên sử dụng nhiều thư mục lưu trữ cho các indexes khác nhau. Cách này giúp ngăn chặn dữ liệu bị chồng chất và đảm bảo mỗi index được lưu trữ riêng biệt [1].

  7. Sử dụng Docstore: LlamaIndex cho phép sử dụng DocumentStore để định nghĩa nhiều index trên cùng một docstore, giúp tránh trùng lặp dữ liệu giữa các index. Tuy nhiên, điều này đòi hỏi quản lý cẩn thận để đảm bảo tất cả các index tham chiếu đúng dữ liệu mà không trùng lặp không cần thiết [1].

Những vấn đề này nhấn mạnh tầm quan trọng của việc quản lý và cấu hình cẩn thận khi làm việc với nhiều indexes trong LlamaIndex framework.

To continue talking to Dosu, mention @dosu.

@NguyenDinhTiem
Copy link
Author

@dosu
Tôi sử dụng summaryextractor cho nodes, nhưng không thực sự chắc chắn về hiệu quả của nó trên dữ liệu của tôi. Tôi có nên dùng nó. Dữ liệu của tôi là pdf cuốn sách ICD11.
`from llama_index.core import SimpleDirectoryReader
from llama_index.core.ingestion import IngestionPipeline, IngestionCache
from llama_index.core.node_parser import TokenTextSplitter
from llama_index.core.extractors import SummaryExtractor
from llama_index.embeddings.openai import OpenAIEmbedding
from llama_index.core import Settings
from llama_index.llms.openai import OpenAI
import openai
import streamlit as st
from src.global_settings import STORAGE_PATH, FILES_PATH, CACHE_FILE
from src.prompts import CUSTORM_SUMMARY_EXTRACT_TEMPLATE

openai.api_key = st.secrets.openai.OPENAI_API_KEY
Settings.llm = OpenAI(model="gpt-4o-mini", temperature=0.2)

def ingest_documents():
# Load documents, easy but we can't move data or share for another device.
# Because document id is root file name when our input is a folder.
# documents = SimpleDirectoryReader(
# STORAGE_PATH,
# filename_as_id = True
# ).load_data()

documents = SimpleDirectoryReader(
    input_files=FILES_PATH, 
    filename_as_id = True
).load_data()
for doc in documents:
    print(doc.id_)

try: 
    cached_hashes = IngestionCache.from_persist_path(
        CACHE_FILE
        )
    print("Cache file found. Running using cache...")
except:
    cached_hashes = ""
    print("No cache file found. Running without cache...")
pipeline = IngestionPipeline(
    transformations=[
        TokenTextSplitter(
            chunk_size=1024, 
            chunk_overlap=20
        ),
        SummaryExtractor(summaries=['self'], prompt_template=CUSTORM_SUMMARY_EXTRACT_TEMPLATE),
        OpenAIEmbedding()
    ],
    cache=cached_hashes
)

nodes = pipeline.run(documents=documents)
pipeline.cache.persist(CACHE_FILE)

return nodes`

Copy link

dosubot bot commented Oct 17, 2024

The SummaryExtractor in the LlamaIndex framework is designed to extract summaries from nodes using a language model (LLM) based on a specified prompt template. It is particularly useful for generating metadata fields like section_summary from text nodes. However, its effectiveness can vary depending on the structure and content of your data.

For your use case with PDF documents of the ICD11 book, consider the following:

  1. Structured Data: If your PDF contains highly structured data, such as tables or lists, the SummaryExtractor might not perform optimally, as it is primarily designed for text-based content.

  2. Customization: You are using a custom prompt template (CUSTORM_SUMMARY_EXTRACT_TEMPLATE). Ensure that this template is well-suited to the type of content in your PDFs to improve the quality of the summaries generated.

  3. Document Complexity: Given the complexity of medical texts like ICD11, you might need to experiment with different configurations or even custom models to achieve the desired summary quality.

  4. Performance: The SummaryExtractor can be resource-intensive, especially on large datasets. Monitor the performance and adjust the chunk size or overlap in the TokenTextSplitter to balance between context retention and processing efficiency.

If the summaries generated are not meeting your expectations, you might need to refine your prompt template or consider additional preprocessing steps to better structure the input data for the extractor.

To continue talking to Dosu, mention @dosu.

@NguyenDinhTiem
Copy link
Author

@dosu
Trong trường hợp dữ liệu ICD11 tôi nên dùng SemanticSplitterNodeParser hay TokenTextSplitter sex tốt hơn. So sánh và giai thích dễ hiểu giúp tôi.

Copy link

dosubot bot commented Oct 17, 2024

Đối với dữ liệu ICD11, việc chọn giữa SemanticSplitterNodeParserTokenTextSplitter phụ thuộc vào cách bạn muốn xử lý và phân tích dữ liệu:

  1. SemanticSplitterNodeParser:

    • Phân đoạn ngữ nghĩa: Sử dụng mô hình nhúng để xác định sự tương đồng ngữ nghĩa giữa các câu, từ đó chọn điểm ngắt một cách thích hợp. Điều này giúp các đoạn văn bản được phân chia có ý nghĩa ngữ nghĩa liên quan với nhau.
    • Linh hoạt: Kích thước đoạn không cố định, mà thay đổi dựa trên mối quan hệ ngữ nghĩa, phù hợp hơn với dữ liệu có cấu trúc phức tạp như ICD11.
    • Cấu hình: Có thể điều chỉnh các tham số như buffer_size, breakpoint_percentile_threshold, và embed_model để tối ưu hóa cho dữ liệu y tế [1].
  2. TokenTextSplitter:

    • Phân đoạn theo token: Chia văn bản thành các đoạn có kích thước cố định dựa trên số lượng token, không quan tâm đến mối quan hệ ngữ nghĩa giữa các câu.
    • Đơn giản và nhanh chóng: Thích hợp cho các trường hợp cần phân đoạn nhanh chóng mà không cần phân tích ngữ nghĩa sâu.
    • Cấu hình: Có thể điều chỉnh chunk_size, chunk_overlap, và separator để phù hợp với nhu cầu cụ thể [1].

Lựa chọn:

  • Nếu bạn cần phân tích ngữ nghĩa sâu và muốn các đoạn văn bản có ý nghĩa liên quan, SemanticSplitterNodeParser sẽ là lựa chọn tốt hơn.
  • Nếu bạn cần phân đoạn nhanh chóng và không cần phân tích ngữ nghĩa chi tiết, TokenTextSplitter có thể phù hợp hơn.

Với dữ liệu ICD11, thường có cấu trúc phức tạp và yêu cầu hiểu biết ngữ nghĩa, SemanticSplitterNodeParser có thể mang lại kết quả tốt hơn trong việc duy trì ngữ cảnh và ý nghĩa của dữ liệu.

To continue talking to Dosu, mention @dosu.

@NguyenDinhTiem
Copy link
Author

@dosu
Xin chào, vấn đề tôi gặp phải khi load file pdf là khi trang pdf rỗng chỉ có tiêu đề thì trình trích xuất vẫn tạo ra document chỉ chứa tiêu đề. Sau đó tôi thực hiện tạo nodes từ các document này thì gặp vấn đề là nodes được tạo ra từ trang rỗng chỉ chứa tiêu đề thì node đó chỉ chứa text là tiêu đề đó thôi, điều này tôi nghĩ không hợp lý, bạn có biết tại sao không?

Đây là nội dung documents của tôi:
[Document(id_='712cff97-86fa-40c6-ba59-70d2eadb2841', embedding=None, metadata={'file_path': 'data/ingestion_storage/ICD11-test.pdf', 'file_name': 'ICD11-test.pdf', 'file_type': 'application/pdf', 'file_size': 69934341, 'creation_date': '2024-10-19', 'last_modified_date': '2024-10-19'}, excluded_embed_metadata_keys=['file_name', 'file_type', 'file_size', 'creation_date', 'last_modified_date', 'last_accessed_date'], excluded_llm_metadata_keys=['file_name', 'file_type', 'file_size', 'creation_date', 'last_modified_date', 'last_accessed_date'], relationships={}, text=' Mental, behavioural and neurodevelopmental disorders 89\n\nMental, behavioural and\nneurodevelopmental disorders\n\nMental, behavioural and neurodevelopmental disorders are syndromes characterized by clinically\nsignificant disturbance in an individual’s cognition, emotional regulation or behaviour that\nreflects a dysfunction in the psychological, biological or developmental processes that underlie\nmental and behavioural functioning. These disturbances are usually associated with distress\nor impairment in personal, family, social, educational, occupational or other important areas\nof functioning.', mimetype='text/plain', start_char_idx=None, end_char_idx=None, text_template='{metadata_str}\n\n{content}', metadata_template='{key}: {value}', metadata_seperator='\n'), Document(id_='e42e0e71-581a-4281-a220-f5d6b7c923d7', embedding=None, metadata={'file_path': 'data/ingestion_storage/ICD11-test.pdf', 'file_name': 'ICD11-test.pdf', 'file_type': 'application/pdf', 'file_size': 69934341, 'creation_date': '2024-10-19', 'last_modified_date': '2024-10-19'}, excluded_embed_metadata_keys=['file_name', 'file_type', 'file_size', 'creation_date', 'last_modified_date', 'last_accessed_date'], excluded_llm_metadata_keys=['file_name', 'file_type', 'file_size', 'creation_date', 'last_modified_date', 'last_accessed_date'], relationships={}, text='90 Clinical Descriptions and Diagnostic Requirements for ICD-11 Mental, Behavioural or Neurodevelopmental Disorders', mimetype='text/plain', start_char_idx=None, end_char_idx=None, text_template='{metadata_str}\n\n{content}', metadata_template='{key}: {value}', metadata_seperator='\n'), Document(id_='e90a9acf-ca93-4a4b-a290-4daf62dbfa0f', embedding=None, metadata={'file_path': 'data/ingestion_storage/ICD11-test.pdf', 'file_name': 'ICD11-test.pdf', 'file_type': 'application/pdf', 'file_size': 69934341, 'creation_date': '2024-10-19', 'last_modified_date': '2024-10-19'}, excluded_embed_metadata_keys=['file_name', 'file_type', 'file_size', 'creation_date', 'last_modified_date', 'last_accessed_date'], excluded_llm_metadata_keys=['file_name', 'file_type', 'file_size', 'creation_date', 'last_modified_date', 'last_accessed_date'], relationships={}, text=' ivx1InvtvrIodvuc2r3n45I1nv15 91\n\n Neurodevelopmental disorders\n\nNeurodevelopmental disorders are behavioural and cognitive disorders arising during the\ndevelopmental period that involve significant difficulties in the acquisition and execution\nof specific intellectual, motor, language or social functions. In this context, arising during the\ndevelopmental period is typically considered to mean that these disorders have their onset prior\nto 18 years of age, regardless of the age at which the individual first comes to clinical attention.\nAlthough behavioural and cognitive deficits are present in many mental and behavioural\ndisorders that can arise during the developmental period (e.g. schizophrenia, bipolar disorder),\nonly disorders whose core features are neurodevelopmental are included in this grouping.\nThe presumptive etiology for neurodevelopmental disorders is complex, and in many individual\ncases is unknown, but they are presumed to be primarily due to genetic or other factors that are\npresent from birth. However, lack of appropriate environmental stimulation and lack of adequate\nlearning opportunities and experiences may also be contributory factors in neurodevelopmental\ndisorders and should be considered routinely in their assessment. Certain neurodevelopmental\ndisorders may also arise from injury, disease or other insult to the central nervous system, when\nthis occurs during the developmental period.\n\n Neurodevelopmental disorders include the following:\n\n 6A00 Disorders of intellectual development\n\n 6A01 Developmental speech and language disorders\n 6A01.0 Developmental speech sound disorder\n 6A01.1 Developmental speech fluency disorder\n 6A01.2 Developmental language disorder\n 6A01.Y Other specified developmental speech or language disorder\n 6A01.Z Developmental speech or language disorder, unspecified\n\n 6A02 Autism spectrum disorder\n\n 6A03 Developmental learning disorder\n\n 6A04 Developmental motor coordination disorder\n\n 6A05 Attention deficit hyperactivity disorder\n\n 6A06 Stereotyped movement disorder\n\n 6A0Y Other specified neurodevelopmental disorder\n\n 6A0Z Neurodevelopmental disorder, unspecified.\n\n Neurodevelopmental disorders', mimetype='text/plain', start_char_idx=None, end_char_idx=None, text_template='{metadata_str}\n\n{content}', metadata_template='{key}: {value}', metadata_seperator='\n'), Document(id_='8958d87e-cdc0-4f0c-bf0f-47a2d89b47da', embedding=None, metadata={'file_path': 'data/ingestion_storage/ICD11-test.pdf', 'file_name': 'ICD11-test.pdf', 'file_type': 'application/pdf', 'file_size': 69934341, 'creation_date': '2024-10-19', 'last_modified_date': '2024-10-19'}, excluded_embed_metadata_keys=['file_name', 'file_type', 'file_size', 'creation_date', 'last_modified_date', 'last_accessed_date'], excluded_llm_metadata_keys=['file_name', 'file_type', 'file_size', 'creation_date', 'last_modified_date', 'last_accessed_date'], relationships={}, text=' 92 Clinical Descriptions and Diagnostic Requirements for ICD-11 Mental, Behavioural or Neurodevelopmental Disorders\n\n In addition, three categories from the grouping of primary tics and tic disorders in Chapter 8 on\n diseases of the nervous system are cross-listed here, with diagnostic guidance provided, because\n of their high co-occurrence and familial association with neurodevelopmental disorders.\n These include:\n\n 8A05.00 Tourette syndrome\n\n 8A05.01 Chronic motor tic disorder\n\n 8A05.02 Chronic phonic tic disorder\n\n General cultural considerations for neurodevelopmental disorders\n\n • The evaluation of the essential features of most of the disorders in this section either\n depends on or is informed by standardized assessments. The cultural appropriateness of\n tests and norms used to assess intellectual, motor, language or social abilities should be\n considered for each individual. Test performance may be affected by cultural biases (e.g.\n reference in test items to terminology or objects not common to a culture) and limitations\n of translation. Language proficiency must also be considered when interpreting test results.\n Where appropriately normed and standardized tests are not available, assessment of the\n essential features of these disorders requires greater reliance on clinical judgement based\n on appropriate evidence and assessment.\n\n 6A00 Disorders of intellectual development\n\n Essential (required) features\n\n • The presence of significant limitations in intellectual functioning across various domains\n such as perceptual reasoning, working memory, processing speed and verbal comprehension\n is required for diagnosis. There is often substantial variability in the extent to which any\n of these domains are affected in an individual. Whenever possible, performance should be\n measured using appropriately normed, standardized tests of intellectual functioning and\n found to be approximately 2 or more standard deviations below the mean (i.e. approximately\n less than the 2.3rd percentile). In situations where appropriately normed and standardized\n tests are not available, assessment of intellectual functioning requires greater reliance on\n clinical judgement based on appropriate evidence and assessment, which may include the\n use of behavioural indicators of intellectual functioning (see Table 6.1, p. 101).\n • The presence of significant limitations in adaptive behaviour, which refers to the set of\n conceptual, social and practical skills that have been learned and are performed by people in\n their everyday lives, is an essential component. Conceptual skills are those that involve the\n application of knowledge (e.g. reading, writing, calculating, solving problems and making\n decisions) and communication; social skills include managing interpersonal interactions\n\nNeurodevelopmental disorders | Disorders of intellectual development', mimetype='text/plain', start_char_idx=None, end_char_idx=None, text_template='{metadata_str}\n\n{content}', metadata_template='{key}: {value}', metadata_seperator='\n')]

Copy link

dosubot bot commented Oct 19, 2024

The issue you're encountering, where a PDF page with only a title results in a document and subsequently a node containing just that title, is likely due to how the document loading and node creation processes handle minimal content. In the LlamaIndex framework, when a document is created from a PDF page, it includes whatever text is present, even if it's just a title. This behavior can lead to nodes that contain only minimal content, such as a title, which might not be useful for your application.

To address this, you can implement a preprocessing step to filter out or handle documents with minimal content before they are converted into nodes. Here are a few strategies you might consider:

  1. Content Length Check: Before creating nodes, check the length of the document's text. If it falls below a certain threshold (e.g., only a few words), you can choose to exclude it from the node creation process.

  2. Custom Filtering Logic: Implement custom logic to identify and exclude documents that only contain titles or other minimal content. This could involve checking for specific patterns or keywords that indicate a document is not substantive.

  3. Modify Node Creation: Adjust the node creation process to ignore documents that do not meet your content criteria. This might involve modifying the logic in your pipeline to skip over documents with insufficient content.

By incorporating these strategies, you can ensure that only documents with meaningful content are processed into nodes, improving the quality and relevance of your data.

To continue talking to Dosu, mention @dosu.

@NguyenDinhTiem
Copy link
Author

@dosu

Vui lòng cung cấp code minh họa

Copy link

dosubot bot commented Oct 19, 2024

To address the issue of creating nodes from PDF pages that only contain titles, you can implement a preprocessing step to filter out documents with minimal content. Here's a code example illustrating how you might achieve this:

from llama_index.core import SimpleDirectoryReader
from llama_index.core.ingestion import IngestionPipeline, IngestionCache
from llama_index.core.node_parser import TokenTextSplitter
from llama_index.core.extractors import SummaryExtractor
from llama_index.embeddings.openai import OpenAIEmbedding
from llama_index.core import Settings
from llama_index.llms.openai import OpenAI
import openai
import streamlit as st
from src.global_settings import STORAGE_PATH, FILES_PATH, CACHE_FILE
from src.prompts import CUSTORM_SUMMARY_EXTRACT_TEMPLATE

openai.api_key = st.secrets.openai.OPENAI_API_KEY
Settings.llm = OpenAI(model="gpt-4o-mini", temperature=0.2)

def ingest_documents():
    # Load documents
    documents = SimpleDirectoryReader(
        input_files=FILES_PATH, 
        filename_as_id=True
    ).load_data()

    # Filter out documents with minimal content
    filtered_documents = [doc for doc in documents if len(doc.text.strip()) > 10]  # Adjust threshold as needed

    for doc in filtered_documents:
        print(doc.id_)

    try: 
        cached_hashes = IngestionCache.from_persist_path(CACHE_FILE)
        print("Cache file found. Running using cache...")
    except:
        cached_hashes = ""
        print("No cache file found. Running without cache...")

    pipeline = IngestionPipeline(
        transformations=[
            TokenTextSplitter(chunk_size=1024, chunk_overlap=20),
            SummaryExtractor(summaries=['self'], prompt_template=CUSTORM_SUMMARY_EXTRACT_TEMPLATE),
            OpenAIEmbedding()
        ],
        cache=cached_hashes
    )
   
    nodes = pipeline.run(documents=filtered_documents)
    pipeline.cache.persist(CACHE_FILE)
    
    return nodes

# Call the function to ingest documents
nodes = ingest_documents()

In this example, the filtered_documents list is created by filtering out documents with text length below a certain threshold (e.g., 10 characters). You can adjust this threshold based on your specific needs to ensure that only documents with meaningful content are processed into nodes.

To continue talking to Dosu, mention @dosu.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

1 participant