run-llama / llama_index

LlamaIndex is a data framework for your LLM applications
https://docs.llamaindex.ai
MIT License
36.22k stars 5.16k forks source link

[Question]: Building multiple indexes #16584

Open NguyenDinhTiem opened 4 days ago

NguyenDinhTiem commented 4 days ago

Question Validation

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
dosubot[bot] commented 4 days ago

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 commented 4 days ago

@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`
dosubot[bot] commented 4 days ago

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 commented 4 days ago

@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.

dosubot[bot] commented 4 days ago

Đố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:

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 commented 2 days ago

@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')]

dosubot[bot] commented 2 days ago

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 commented 2 days ago

@dosu

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

dosubot[bot] commented 2 days ago

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.

NguyenDinhTiem commented 4 hours ago

@dosu Tại sao khi tôi load 1 file pdf, tôi nhận được danh sách documents, mỗi documents là nội dung 1 trang, điều này có đúng không, có phải lỗi không? documents = SimpleDirectoryReader( input_files=["data/ingestion_storage/ICD11.pdf"], filename_as_id = True ).load_data() output: ` [Document(id_='data/ingestion_storage/ICD11.pdf_part_0', embedding=None, metadata={'page_label': 'A', 'file_name': 'ICD11.pdf', 'file_path': 'data/ingestion_storage/ICD11.pdf', 'file_type': 'application/pdf', 'file_size': 8046373, 'creation_date': '2024-10-05', 'last_modified_date': '2024-10-05'}, 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='Clinical descriptions and \ndiagnostic requirements for \nICD-11 mental, behavioural and \nneurodevelopmental disorders', mimetype='text/plain', start_char_idx=None, end_char_idx=None, text_template='{metadata_str}\n\n{content}', metadata_template='{key}: {value}', metadataseperator='\n'), Document(id='data/ingestion_storage/ICD11.pdf_part_1', embedding=None, metadata={'page_label': 'B', 'file_name': 'ICD11.pdf', 'file_path': 'data/ingestion_storage/ICD11.pdf', 'file_type': 'application/pdf', 'file_size': 8046373, 'creation_date': '2024-10-05', 'last_modified_date': '2024-10-05'}, 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='', 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'),

`

dosubot[bot] commented 4 hours ago

Khi bạn load một file PDF và nhận được danh sách documents, mỗi document là nội dung của một trang, điều này không phải là lỗi. Theo tài liệu về PDFReader trong LlamaIndex, phương thức load_data có thể được cấu hình để trả về mỗi trang của PDF như một document riêng biệt. Điều này xảy ra khi tùy chọn return_full_document được đặt là False, đây là hành vi mặc định. Nếu bạn muốn nhận toàn bộ PDF dưới dạng một document duy nhất, bạn có thể đặt return_full_documentTrue. Do đó, việc nhận mỗi trang dưới dạng một document riêng biệt là hành vi mong đợi khi sử dụng công cụ này [1][2][3].

To continue talking to Dosu, mention @dosu.

NguyenDinhTiem commented 4 hours ago

@dosu Tại sao lại mặc định tạo document từng trang. Nó có ưu và nhược điểm gì so với toàn bộ cuốn sách được lưu trong 1 documents?

dosubot[bot] commented 3 hours ago

Mặc định tạo document cho từng trang khi load file PDF có một số ưu và nhược điểm so với việc lưu toàn bộ cuốn sách trong một document duy nhất:

Ưu điểm:

  1. Quản lý Dữ liệu Dễ Dàng: Mỗi trang là một document riêng biệt giúp dễ dàng quản lý và truy xuất dữ liệu, đặc biệt khi bạn chỉ cần xử lý hoặc tìm kiếm thông tin trên một số trang cụ thể.
  2. Hiệu Suất Tốt Hơn: Xử lý từng trang một cách độc lập có thể cải thiện hiệu suất, đặc biệt khi làm việc với các tài liệu lớn, vì bạn không cần tải toàn bộ tài liệu vào bộ nhớ cùng một lúc.
  3. Tính Linh Hoạt: Cho phép áp dụng các kỹ thuật xử lý khác nhau cho từng trang, chẳng hạn như trích xuất thông tin hoặc phân tích nội dung cụ thể cho từng phần của tài liệu.

Nhược điểm:

  1. Mất Ngữ Cảnh: Khi mỗi trang là một document riêng biệt, có thể mất đi ngữ cảnh giữa các trang, điều này có thể quan trọng đối với các tài liệu mà thông tin trải dài qua nhiều trang.
  2. Tăng Số Lượng Document: Số lượng document tăng lên có thể làm phức tạp việc quản lý và lưu trữ, đặc biệt khi làm việc với nhiều tài liệu lớn.
  3. Khó Khăn Trong Tích Hợp: Một số ứng dụng hoặc quy trình có thể yêu cầu dữ liệu được xử lý dưới dạng một khối lớn, và việc chia nhỏ thành từng trang có thể gây khó khăn trong việc tích hợp.

Việc chọn cách tiếp cận nào phụ thuộc vào nhu cầu cụ thể của bạn, như yêu cầu về hiệu suất, cách sử dụng dữ liệu, và khả năng xử lý của hệ thống.

To continue talking to Dosu, mention @dosu.

NguyenDinhTiem commented 3 hours ago

@dosu Vấn đề xuất hiện khi tạo nodes. Nếu một document chứa thông tin trên 1 trang thì trong trường hợp trang đó rỗng hoặc nội dung nằm trên 2 trang khác nhau. Khi tạo nodes sẽ tạo ra nodes rỗng hoặc nodes thiếu thông tin phải không?

dosubot[bot] commented 3 hours ago

Khi tạo nodes từ documents, nếu một document chỉ chứa thông tin từ một trang và trang đó rỗng, thì node được tạo ra sẽ rỗng hoặc chỉ chứa thông tin tối thiểu như tiêu đề. Tương tự, nếu nội dung của một phần thông tin nằm trên hai trang khác nhau, việc tạo nodes từ từng trang riêng biệt có thể dẫn đến nodes thiếu thông tin đầy đủ.

Để giải quyết vấn đề này, bạn có thể:

  1. Gộp Nội Dung Từ Nhiều Trang: Trước khi tạo nodes, bạn có thể gộp nội dung từ nhiều trang lại với nhau nếu chúng thuộc cùng một phần thông tin logic. Điều này giúp đảm bảo rằng nodes được tạo ra có đầy đủ thông tin.

  2. Kiểm Tra Nội Dung Trước Khi Tạo Nodes: Thực hiện kiểm tra nội dung của mỗi document trước khi tạo nodes. Nếu document không chứa đủ thông tin (ví dụ: chỉ có tiêu đề), bạn có thể chọn không tạo node từ document đó.

  3. Sử Dụng Các Công Cụ Phân Tích Ngữ Nghĩa: Sử dụng các công cụ phân tích ngữ nghĩa để xác định và gộp các phần thông tin liên quan từ nhiều trang, đảm bảo rằng nodes được tạo ra có ý nghĩa và đầy đủ thông tin.

Bằng cách áp dụng các phương pháp này, bạn có thể cải thiện chất lượng và tính đầy đủ của các nodes được tạo ra từ documents.

To continue talking to Dosu, mention @dosu.

NguyenDinhTiem commented 3 hours ago

@Dosu Nếu tôi chỉ tạo 1 document duy nhất thì điều gì sẽ xảy ra? Nó có tốt hơn so với việc tạo document cho từng trang không?

dosubot[bot] commented 3 hours ago

Nếu bạn chỉ tạo một document duy nhất từ một file PDF thay vì tạo document cho từng trang, điều này có thể có những ảnh hưởng sau:

  1. Tích hợp thông tin: Bạn sẽ có một cái nhìn tổng quan và tích hợp hơn về toàn bộ nội dung của file PDF. Điều này có thể hữu ích nếu bạn cần xử lý hoặc phân tích tài liệu như một khối thông tin duy nhất.

  2. Hiệu suất: Tạo một document duy nhất có thể cải thiện hiệu suất trong một số trường hợp, vì bạn chỉ cần thực hiện một lần xử lý cho toàn bộ tài liệu thay vì xử lý từng trang riêng lẻ.

  3. Mất thông tin chi tiết: Bạn có thể mất đi thông tin chi tiết về từng trang, chẳng hạn như nhãn trang hoặc các thông tin metadata cụ thể cho từng trang. Điều này có thể không lý tưởng nếu bạn cần theo dõi hoặc xử lý từng trang riêng biệt.

  4. Khả năng quản lý: Quản lý một document duy nhất có thể đơn giản hơn so với quản lý nhiều document, đặc biệt là khi làm việc với các hệ thống lưu trữ hoặc cơ sở dữ liệu.

Dựa trên đoạn mã trong tài liệu, nếu bạn thiết lập return_full_document=True trong PDFReader, bạn sẽ nhận được một document duy nhất cho toàn bộ file PDF. Ngược lại, nếu return_full_document=False, mỗi trang sẽ được trả về như một document riêng biệt [1].

To continue talking to Dosu, mention @dosu.