<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by khalid bouziane on Medium]]></title>
        <description><![CDATA[Stories by khalid bouziane on Medium]]></description>
        <link>https://medium.com/@kbouziane.ai?source=rss-8b767210b35c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*rlqk_Aov1q9NSwsJ.jpg</url>
            <title>Stories by khalid bouziane on Medium</title>
            <link>https://medium.com/@kbouziane.ai?source=rss-8b767210b35c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 05:54:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kbouziane.ai/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Introduction to GraphRAG using R2R and Neo4j]]></title>
            <link>https://medium.com/@kbouziane.ai/introduction-to-graphrag-using-r2r-and-neo4j-692bc8778360?source=rss-8b767210b35c------2</link>
            <guid isPermaLink="false">https://medium.com/p/692bc8778360</guid>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[graphrag]]></category>
            <dc:creator><![CDATA[khalid bouziane]]></dc:creator>
            <pubDate>Wed, 11 Sep 2024 14:23:26 GMT</pubDate>
            <atom:updated>2024-09-11T14:37:33.475Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*isANUGChSwqbMnwG" /></figure><p>One significant challenge for Large Language Models (LLMs) is their ability to respond to queries about private datasets or data that is more recent than their training cutoff. While Retrieval Augmented Generation (RAG) offers a potential solution, it also has notable limitations. In this blog post, we will explore these limitations and explain how GraphRAG overcomes them. Additionally, we will guide you through the process of deploying a GraphRAG system using R2R and Neo4J.</p><p>Traditional RAG systems operate by segmenting data into chunks, embedding these chunks, and storing them in a vector database. To answer a query, the query itself is embedded using the same model, and the most similar chunks are retrieved. This method allows the LLM to incorporate relevant information not included in its original training data. However, basic RAG systems encounter several challenges, two of which are particularly critical:</p><ol><li>Answering questions that require an understanding of complex relationships between different pieces of information.</li><li>Answering questions that demand a global context, where the answer requires knowledge of the entire dataset.</li></ol><p>GraphRAG effectively addresses both of these challenges!</p><p>In current RAG systems, retrieval is often the most challenging step. Relevant information can be missed, or irrelevant details can be pulled in, both of which lower the quality of the answers. This is where GraphRAG comes into play! GraphRAG solves these problems by adding a knowledge graph to the RAG process, which keeps track of complex relationships between chunks of information, making it easier to find and use them when answering questions.</p><p>Here’s a simple breakdown of how GraphRAG works:</p><p><strong>Building the Knowledge Graph:</strong> Instead of just breaking text into chunks and embedding them, GraphRAG identifies key entities and their relationships to create a knowledge graph. This graph captures how different pieces of information are connected.</p><p><strong>Graph-Based Retrieval:</strong> When a query is made, GraphRAG can explore the knowledge graph to find relevant information. This allows it to follow relationships between entities that a simple vector search might miss.</p><p><strong>Community Detection:</strong> The knowledge graph is examined to find groups of closely related entities, or “communities.” These groups represent broader themes or topics in the dataset.</p><p><strong>Community Summarization:</strong> Each community is summarized to provide an overview of the information it contains, capturing the bigger picture that might be missed if only individual chunks are considered.</p><p><strong>Hybrid Retrieval:</strong> GraphRAG combines the strengths of both vector search and graph-based retrieval. It uses vector search to identify relevant communities, then navigates the graph to find deeper connections within and between those communities.</p><p>By using this approach, GraphRAG ensures that answers are more accurate and comprehensive!.</p><p>By combining these techniques, GraphRAG can provide more comprehensive and contextually relevant information to the language model, enabling it to generate more accurate and insightful responses. Figure 1 shows a high-level architecture of a GraphRAG system.</p><figure><img alt="GraphRag pipeline" src="https://cdn-images-1.medium.com/max/700/0*U83i7HXhv_MW0-B9.jpeg" /><figcaption>Figure 1: high-level architecture of a GraphRAG pipeline system</figcaption></figure><p>Now let’ s take advantage of the R2R library features, and build a knowledge graph. this way we will avoid the hussle of writing cypher queries during the construction of the graph but also while quering information from it.</p><p>For the sake of simplicity we will use the default R2R configuration parameters and a small pdf document named “IF10244.pdf “ which you can download it <a href="https://sgp.fas.org/crs/misc/IF10244.pdf">here</a>, the doc is about “Wildfire Statistics” in US, It highlights regional differences, damages, and key issues for Congress on wildfire management.</p><p>First, install the R2R CLI and Python SDK</p><pre>pip install r2r</pre><p>Second, we will use Open api key and docker to run the server,</p><pre>export OPENAI_API_KEY=sk-...<br><br>r2r serve --docker --config-name=neo4j_kg</pre><p>neo4j_kg is the default configuration file provided by r2r, which include parameters related to the knowledge graph, type of the prompt and LLM used and more, in our case we will use “gpt-4o-mini”, neo4j_kg file can be customized according to the user requirements, and can also support local LLM,Please refer to <a href="https://github.com/SciPhi-AI/R2R/tree/755458895831e990d10847390b04c532617a1410/py/core/configs">R2R github repo</a> or <a href="https://r2r-docs.sciphi.ai/documentation/configuration/knowledge-graph/overview">docs</a> for more details. When using Neo4j as the knowledge graph provider, you need to set up the following environment variables or provide them in the r2r.toml file, In our case, we will use the default neo4j environement variables provided by r2r, and which you can find them <a href="https://github.com/SciPhi-AI/R2R/blob/755458895831e990d10847390b04c532617a1410/py/compose.yaml">here</a>, ( <em>look for line 129</em>).</p><pre>export NEO4J_USER=your_neo4j_username<br>export NEO4J_PASSWORD=your_neo4j_password<br>export NEO4J_URL=bolt://your_neo4j_host:7687<br>export NEO4J_DATABASE=neo4j</pre><p>Once all services are healty, the R2R Docker launches an applications at localhost:7273</p><p>Sign in using the default username and password provided, you can change them later from R2R/py/r2r.toml file. Forget about the app for now, we will discuss that in an other blog post and let’s continue using the r2r CLI.</p><p>Next, we need to ingest the file “IF10244.pdf “ using this command:</p><pre>r2r ingest-files IF10244.pdf</pre><p>This command initiates the ingestion process, producing output similar to:</p><pre>{<br>  &quot;results&quot;: [<br>    {<br>      &quot;message&quot;: &quot;Ingestion task queued successfully.&quot;,<br>      &quot;task_id&quot;: &quot;03f5eb10-2135-4d2c-891f-07f81e70f0d4&quot;,<br>      &quot;document_id&quot;: &quot;1947b668-4231-5ce4-b784-aee612fd40c9&quot;<br>    }<br>  ]<br>}</pre><p>let’s see now the entities that was created by the LLM and related relationship between them, run the command:</p><pre>r2r inspect-knowledge-graph</pre><p>The output will look something like this:</p><pre>== States ==<br>  Responsible for Response:<br>    - Wildfires<br>  Jurisdiction:<br>    - Nonfederal Lands<br><br>== Federal Government ==<br>  Responsible for Response:<br>    - Wildfires<br>  Oversight:<br>    - Federal Agencies<br><br>== Forest Service ==<br>  Manages:<br>    - National Forest System<br>  Collaborates:<br>    - National Interagency Coordination Center<br>  Part of:<br>    - Department of the Interior<br>  Management:<br>    - National Forest System<br><br>== National Interagency Coordination Center ==<br>  Manages:<br>    - Wildfires<br>  Reports on:<br>    - Acres<br>  Compiles Data:<br>    - Wildfire<br><br>== Wildfires ==<br>  Affects:<br>    - Acres<br>    - Civilians<br>    - Acres Burned<br>  Occurred In:<br>    - 2022<br>    - 2023<br>  Affected Area:<br>    - Alaska<br>  Causes Damage:<br>    - Structures<br>  Engages:<br>    - Firefighters<br>  Can lead to:<br>    - Conflagrations<br>  Burn:<br>    - Acres<br>  Affected by:<br>    - Geography<br>  Impacts:<br>    - Acres<br>  Location of Impact:<br>    - Alaska<br>  Impact:<br>    - Acres<br>  Occurrence Date:<br>    - June 1, 2023<br>  Responsible Response:<br>    - States<br>    - Federal Government<br>  Causes:<br>    - Acres Burned<br><br>== Federal ==<br>  Manages:<br>    - Wildfires<br>  Collaborates with:<br>    - FS<br>  Part of:<br>    - Government<br>  Governs:<br>    - National Governance<br><br>== FS ==<br>  Manages:<br>    - Wildfires<br><br>== DOI ==<br>  Manages:<br>    - Wildfires<br><br>== Nonfederal ==<br>  Responds to:<br>    - Wildfires<br><br>== Department of the Interior ==<br>  Oversees:<br>    - National Interagency Coordination Center<br>  Manages:<br>    - Alaska<br>  Provides data for:<br>    - NICC Wildland Fire Summary and Statistics<br><br>== 2022 ==<br>  Year of Impact:<br>    - Wildfires<br>  Year of significant events:<br>    - Wildfire<br><br>== Wildfire ==<br>  Causes:<br>    - Acreage<br>  Type:<br>    - Human-Caused Wildfires<br>  Assessed by:<br>    - Preparedness Level (PL)<br>  Affects:<br>    - Communities<br>  Impacts:<br>    - Ecological Resources<br>  Has Data:<br>    - Statistics<br>  Occurs In:<br>    - U.S.<br><br>== NICC ==<br>  Provides statistics for:<br>    - Wildfire<br>  Reports on:<br>    - Wildfires<br>  Coordinates:<br>    - Wildland Fire<br>  Reports On:<br>    - Federal Lands<br>    - Nonfederal Lands<br><br>== Fires ==<br>  Measured by:<br>    - Acreage<br>  Influenced by:<br>    - Weather<br>  Measurement:<br>    - Fires<br><br>== Human Development ==<br>  Impacted by:<br>    - Wildfire<br><br>== Communities ==<br>  Affected by:<br>    - Wildfire<br><br>== Federal Lands ==<br>  Burned by:<br>    - Wildfires<br>  Acreage Burned:<br>    - West<br><br>== State Lands ==<br>  Burned by:<br>    - Wildfires<br><br>== NICC Wildland Fire Summary and Statistics ==<br>  Reports on:<br>    - Alaska<br>  Data Source:<br>    - Federal Lands<br><br>== Nonfederal Lands ==<br>  Acreage Burned:<br>    - East<br><br>== WY ==<br>  Affected by:<br>    - Wildfire<br><br>== Puerto Rico ==<br>  Affected by:<br>    - Wildfire<br><br>== Firefighters ==<br>  Protects:<br>    - Civilians<br><br>== California ==<br>  Location of Occurrence:<br>    - Wildfires<br><br>== Conflagrations ==<br>  Consume:<br>    - Acres<br><br>== Congress ==<br>  Considers:<br>    - Wildfire Management<br>  Comprises:<br>    - Members of Congress<br>  Organizes into:<br>    - Congressional Committees<br><br>== Katie Hoover ==<br>  Expertise:<br>    - Suppression Operations<br><br>== Laura A. Hanson ==<br>  Research Relevance:<br>    - Suppression Operations<br><br>== CRS ==<br>  Provides support to:<br>    - Congress<br>  Supports:<br>    - Congressional Committees<br>  Serves:<br>    - Members of Congress<br>  Provides Research:<br>    - Members of Congress<br><br>== Wildfire Statistics ==<br>  Informs legislation on:<br>    - Congress<br>  Data Collection:<br>    - Wildfires<br><br>== CRS Reports ==<br>  Utilizes:<br>    - Members of Congress<br>  Produced By:<br>    - CRS<br>  Government Document:<br>    - United States Government<br>  May Require Permission:<br>    - Copyright Holder<br><br>== Acres ==<br>  Measurement of Impact:<br>    - Wildfire Statistics<br>  Measurement Date:<br>    - June 1, 2023<br><br>== June 1, 2023 ==<br>  Is in:<br>    - June<br>  Occurs in:<br>    - 2023<br><br>== June ==<br>  Occurs in:<br>    - 2023<br><br>== First Day of June ==<br>  Is part of:<br>    - June<br>  Is on:<br>    - June 1, 2023<br><br>== 30 years ==<br>  Time Frame for Data:<br>    - Wildfire<br><br>== 2000 ==<br>  Starting Point for Averages:<br>    - Wildfire<br><br>== Wildland Fire ==<br>  Occurs On:<br>    - Federal Lands<br>    - Nonfederal Lands<br><br>== Wildfire Acreage ==<br>  Analyzed In:<br>    - Years<br><br>== Years ==<br>  Reference Point:<br>    - 1960<br><br>== 1960 ==<br>  Contextualizes:<br>    - Wildfire Acreage<br><br>== Acres Burned ==<br>  Measured Over:<br>    - 1993-2022<br><br>== 1993-2022 ==<br>  Observed During:<br>    - Wildfires<br><br>== Graph Statistics ==<br>Number of nodes: 67<br>Number of edges: 100<br>Number of connected components: 20<br><br>== Most Central Nodes ==<br>  Wildfires: 0.2727<br>  Wildfire: 0.1061<br>  NICC: 0.0758<br>  Forest Service: 0.0606<br>  Federal: 0.0606</pre><p>As you see, we manage to extract entities and relationships, but I m lazy to go through all of them, what about if we need to ingest a whole book, or a large document….!!! Here where knowledge graph visualition tools like neo4j comes to play, and to make our life easy, to do that open: <a href="http://localhost:7474/browser/">http://localhost:7474/browser/</a> and enter the credentials I have provided above and which again you can find them <a href="https://github.com/SciPhi-AI/R2R/blob/755458895831e990d10847390b04c532617a1410/py/compose.yaml">here</a>, ( <em>look for line 129</em>). connect to neo4j browser , go to database and choose neo4j.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*5vnqr4OnzQgSceD3s9726w.png" /></figure><p>et VOILA…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*77mYnPjq5R-jaXHnVYFSdg.png" /></figure><p>Now, you can check nodes and edges, to understand how entities are connected, more than that, you can use the power of neo4j features, to extract certain aspect or add nodes etc….But since it’ s all about GraphRag we will continue with R2R to extract information using natural language.</p><p>we have a graph, but this graph is not searchable yet. We need to perform the graph enrichment step.</p><p>The graph enrichment step adds node and relationship descriptions, performs hierarchical leiden clustering to create communities, and embeds the descriptions. These embeddings will be used later in the local search stage of the pipeline.</p><pre>r2r enrich-graph</pre><p>Now you can see that the graph is enriched with the following information. We have added descriptions and embeddings to the nodes and relationships. Also, each node is mapped to a community.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*mtGH-GDKQnY06UqOckWhXA.png" /></figure><p>GraphRAG currently supports two types of searches: local and global.</p><p><strong>Local searches</strong> are faster and cheaper than global. A local knowledge graph search performs similarity search on the entity, relationship and community description embeddings.</p><pre>r2r search --query=&quot;what is wildfire?&quot; <br>--use-kg-search --kg-search-type=local</pre><p>The answer will be returned in JSON format and contains results from entities, relationships and communities. Following is a snippet of the output:</p><pre>{&#39;fragment_id&#39;: &#39;40168532-51c4-5e76-b9cb-995bd7f2096d&#39;, &#39;extraction_id&#39;: &#39;1ac90a9a-c82e-532a-95af-b22a044a643f&#39;, &#39;document_id&#39;: &#39;1917b668-4271-5ce4-b784-aee912fd40c9&#39;, &#39;user_id&#39;: &#39;2acb499e-8428-543b-bd85-0d9098718220&#39;, &#39;group_ids&#39;: [], &#39;score&#39;: 0.5886406898498577, &#39;text&#39;: &#39;Wildfire Statistics&#39;, &#39;metadata&#39;: {&#39;title&#39;: &#39;IF10244.pdf&#39;, &#39;version&#39;: &#39;v0&#39;, &#39;chunk_order&#39;: 0, &#39;document_type&#39;: &#39;pdf&#39;, &#39;unstructured_filetype&#39;: &#39;application/pdf&#39;, &#39;unstructured_languages&#39;: [&#39;eng&#39;], &#39;unstructured_coordinates&#39;: {&#39;points&#39;: [[485.98, 24.840000000000032], [485.98, 35.879999999999995], [556.99504, 35.879999999999995], [556.99504, 24.840000000000032]], &#39;system&#39;: &#39;PixelSpace&#39;, &#39;layout_width&#39;: 612, &#39;layout_height&#39;: 792}, &#39;unstructured_page_number&#39;: 3, &#39;partitioned_by_unstructured&#39;: True, &#39;associated_query&#39;: &#39;what is wildfire?&#39;}}<br>{&#39;fragment_id&#39;: &#39;fd76a8f9-b4bf-52c3-986b-441b59844892&#39;, &#39;extraction_id&#39;: &#39;1c29fb7f-f464-5bf1-886d-d9ca2e269941&#39;, &#39;document_id&#39;: &#39;1917b668-4271-5ce4-b784-aee912fd40c9&#39;, &#39;user_id&#39;: &#39;2acb499e-8428-543b-bd85-0d9098718220&#39;, &#39;group_ids&#39;: [], &#39;score&#39;: 0.5886043661000957, &#39;text&#39;: &#39;Wildfire Statistics&#39;, &#39;metadata&#39;: {&#39;title&#39;: &#39;IF10244.pdf&#39;, &#39;version&#39;: &#39;v0&#39;, &#39;chunk_order&#39;: 0, &#39;document_type&#39;: &#39;pdf&#39;, &#39;unstructured_filetype&#39;: &#39;application/pdf&#39;, &#39;unstructured_languages&#39;: [&#39;eng&#39;], &#39;unstructured_coordinates&#39;: {&#39;points&#39;: [[57.6, 106.98800000000006], [57.6, 124.98800000000006], [196.09199999999998, 124.98800000000006], [196.09199999999998, 106.98800000000006]], &#39;system&#39;: &#39;PixelSpace&#39;, &#39;layout_width&#39;: 612, &#39;layout_height&#39;: 792}, &#39;unstructured_page_number&#39;: 1, &#39;partitioned_by_unstructured&#39;: True, &#39;associated_query&#39;: &#39;what is wildfire?&#39;}}<br>{&#39;fragment_id&#39;: &#39;5fd08a9c-7eb5-5a7c-8d0c-1095963ac8e2&#39;, &#39;extraction_id&#39;: &#39;b3914c5c-169a-576d-9468-79b658d2a927&#39;, &#39;document_id&#39;: &#39;1917b668-4271-5ce4-b784-aee912fd40c9&#39;, &#39;user_id&#39;: &#39;2acb499e-8428-543b-bd85-0d9098718220&#39;, &#39;group_ids&#39;: [], &#39;score&#39;: 0.5886043661000957, &#39;text&#39;: &#39;Wildfire Statistics&#39;, &#39;metadata&#39;: {&#39;title&#39;: &#39;IF10244.pdf&#39;, &#39;version&#39;: &#39;v0&#39;, &#39;chunk_order&#39;: 0, &#39;document_type&#39;: &#39;pdf&#39;, &#39;unstructured_filetype&#39;: &#39;application/pdf&#39;, &#39;unstructured_languages&#39;: [&#39;eng&#39;], &#39;unstructured_coordinates&#39;: {&#39;points&#39;: [[485.98, 24.840000000000032], [485.98, 35.879999999999995], [556.99504, 35.879999999999995], [556.99504, 24.840000000000032]], &#39;system&#39;: &#39;PixelSpace&#39;, &#39;layout_width&#39;: 612, &#39;layout_height&#39;: 792}, &#39;unstructured_page_number&#39;: 2, &#39;partitioned_by_unstructured&#39;: True, &#39;associated_query&#39;: &#39;what is wildfire?&#39;}}<br>{&#39;fragment_id&#39;: &#39;0a56fb2d-7e65-5708-ad8f-af39a1389225&#39;, &#39;extraction_id&#39;: &#39;de935fb3-4077-5c9e-88e2-05a36da9bc67&#39;, &#39;document_id&#39;: &#39;1917b668-4271-5ce4-b784-aee912fd40c9&#39;, &#39;user_id&#39;: &#39;2acb499e-8428-543b-bd85-0d9098718220&#39;, &#39;group_ids&#39;: [], &#39;score&#39;: 0.5558385153864489, &#39;text&#39;: &#39;Wildfires are unplanned fires, including lightning-caused fires, unauthorized human-caused fires, and escaped fires from prescribed burn projects. States are responsible for responding to wildfires that begin on nonfederal (state, local, and private) lands, except for lands protected by federal agencies under cooperative agreements. The federal government is responsible for responding to wildfires that begin on federal lands. The Forest Service (FS)—within the U.S. Department of Agriculture—carries out wildfire management and response across the 193 million acres of the National Forest System (NFS). The Department of the Interior (DOI) manages wildfire response for more than 400 million acres of national parks, wildlife refuges and preserves, other public lands, and Indian reservations.&#39;, &#39;metadata&#39;: {&#39;title&#39;: &#39;IF10244.pdf&#39;, &#39;version&#39;: &#39;v0&#39;, &#39;chunk_order&#39;: 0, &#39;document_type&#39;: &#39;pdf&#39;, &#39;unstructured_filetype&#39;: &#39;application/pdf&#39;, &#39;unstructured_languages&#39;: [&#39;eng&#39;], &#39;unstructured_parent_id&#39;: &#39;255a3758f6916b1d06037f219de720e5&#39;, &#39;unstructured_coordinates&#39;: {&#39;points&#39;: [[57.6, 137.05136000000005], [57.6, 289.96136], [300.3451199999999, 289.96136], [300.3451199999999, 137.05136000000005]], &#39;system&#39;: &#39;PixelSpace&#39;, &#39;layout_width&#39;: 612, &#39;layout_height&#39;: 792}, &#39;unstructured_page_number&#39;: 1, &#39;partitioned_by_unstructured&#39;: True, &#39;associated_query&#39;: &#39;what is wildfire?&#39;}}<br>{&#39;fragment_id&#39;: &#39;ded015b5-7f7d-5d18-9dd1-49d195662d04&#39;, &#39;extraction_id&#39;: &#39;697a1581-6043-5053-868a-9595c5b31453&#39;, &#39;document_id&#39;: &#39;1917b668-4271-5ce4-b784-aee912fd40c9&#39;, &#39;user_id&#39;: &#39;2acb499e-8428-543b-bd85-0d9098718220&#39;, &#39;group_ids&#39;: [], &#39;score&#39;: 0.5059535804959294, &#39;text&#39;: &#39;Wildfire statistics help illustrate past U.S. wildfire activity. Nationwide data compiled by the National Interagency Coordination Center (NICC) indicate that the number of annual wildfires is variable but has decreased slightly over the last 30 years. The number of acres affected annually, while also variable, generally has increased (see Figure 1). Since 2000, an annual average of 70,025 wildfires have burned an annual average of 7.0 million acres. The acreage figure is more than double the average annual acreage burned in the 1990s (3.3 million acres), although a greater number of fires occurred annually in the 1990s on average (78,600).&#39;, &#39;metadata&#39;: {&#39;title&#39;: &#39;IF10244.pdf&#39;, &#39;version&#39;: &#39;v0&#39;, &#39;chunk_order&#39;: 0, &#39;document_type&#39;: &#39;pdf&#39;, &#39;unstructured_filetype&#39;: &#39;application/pdf&#39;, &#39;unstructured_languages&#39;: [&#39;eng&#39;], &#39;unstructured_parent_id&#39;: &#39;396d19ebc80f33d147d9ffae264a2757&#39;, &#39;unstructured_coordinates&#39;: {&#39;points&#39;: [[57.6, 302.08135999999996], [57.6, 432.90136], [296.76691999999997, 432.90136], [296.76691999999997, 302.08135999999996]], &#39;system&#39;: &#39;PixelSpace&#39;, &#39;layout_width&#39;: 612, &#39;layout_height&#39;: 792}, &#39;unstructured_page_number&#39;: 1, &#39;partitioned_by_unstructured&#39;: True, &#39;associated_query&#39;: &#39;what is wildfire?&#39;}}<br>{&#39;fragment_id&#39;: &#39;3a357a58-71e6-5292-8e58-27cc700abe49&#39;, &#39;extraction_id&#39;: &#39;686dca1b-1ec1-5526-98f2-d603371dbbda&#39;, &#39;document_id&#39;: &#39;1917b668-4271-5ce4-b784-aee912fd40c9&#39;, &#39;user_id&#39;: &#39;2acb499e-8428-543b-bd85-0d9098718220&#39;, &#39;group_ids&#39;: [], &#39;score&#39;: 0.5025474878443024, &#39;text&#39;: &#39;Wildfire Damages Wildfires may affect certain ecological resources beneficially, but wildfires also may have devastating impacts, especially for communities affected by wildfire activity. Statistics showing the level of destruction a wildfire caused can provide useful metrics to evaluate the fire’s effect. Such statistics may include acres burned or impacted, lives lost (firefighters and civilians), and structures (residential, commercial, and other) destroyed. For example, in 2022, over 2,700 structures were burned in wildfires; the majority of the damage occurred in California (see Table 2).&#39;, &#39;metadata&#39;: {&#39;title&#39;: &#39;IF10244.pdf&#39;, &#39;version&#39;: &#39;v0&#39;, &#39;chunk_order&#39;: 0, &#39;document_type&#39;: &#39;pdf&#39;, &#39;unstructured_filetype&#39;: &#39;application/pdf&#39;, &#39;unstructured_languages&#39;: [&#39;eng&#39;], &#39;unstructured_parent_id&#39;: &#39;f2a69199a012bb00be04e8a085259b82&#39;, &#39;unstructured_coordinates&#39;: {&#39;points&#39;: [[313.25, 178.23079999999993], [313.25, 309.16136], [555.3100000000001, 309.16136], [555.3100000000001, 178.23079999999993]], &#39;system&#39;: &#39;PixelSpace&#39;, &#39;layout_width&#39;: 612, &#39;layout_height&#39;: 792}, &#39;unstructured_page_number&#39;: 2, &#39;partitioned_by_unstructured&#39;: True, &#39;associated_query&#39;: &#39;what is wildfire?&#39;}}<br>{&#39;fragment_id&#39;: &#39;4faec220-f2e7-5ef3-bfe9-fd378850bdc3&#39;, &#39;extraction_id&#39;: &#39;ec0b6455-7e28-58c0-b931-7bc1da69992b&#39;, &#39;document_id&#39;: &#39;1917b668-4271-5ce4-b784-aee912fd40c9&#39;, &#39;user_id&#39;: &#39;2acb499e-8428-543b-bd85-0d9098718220&#39;, &#39;group_ids&#39;: [], &#39;score&#39;: 0.4845070829693734, &#39;text&#39;: &#39;Conflagrations Of the 1.6 million wildfires that have occurred since 2000, 254 exceeded 100,000 acres burned and 16 exceeded 500,000 acres burned. A small fraction of wildfires become catastrophic, and a small percentage of fires accounts for the vast majority of acres burned. For example, about 1% of wildfires become conflagrations—raging, destructive fires—but predicting which fires will “blow up” into conflagrations is challenging and depends on a multitude of factors, such as weather and geography. There have been 1,041 large or significant fires annually on average from 2018 through 2022. In 2022, 2% of wildfires were classified as large or significant (1,289); 45 exceeded 40,000 acres in size, and 17 exceeded 100,000 acres. For context, there were fewer large or significant wildfires in 2021 (943) but more in 2017 (1,409).&#39;, &#39;metadata&#39;: {&#39;title&#39;: &#39;IF10244.pdf&#39;, &#39;version&#39;: &#39;v0&#39;, &#39;chunk_order&#39;: 0, &#39;document_type&#39;: &#39;pdf&#39;, &#39;unstructured_filetype&#39;: &#39;application/pdf&#39;, &#39;unstructured_languages&#39;: [&#39;eng&#39;], &#39;unstructured_parent_id&#39;: &#39;02b65f46a42a77ad802305f45be1c490&#39;, &#39;unstructured_coordinates&#39;: {&#39;points&#39;: [[313.25, 406.5208], [313.25, 581.34136], [556.025, 581.34136], [556.025, 406.5208]], &#39;system&#39;: &#39;PixelSpace&#39;, &#39;layout_width&#39;: 612, &#39;layout_height&#39;: 792}, &#39;unstructured_page_number&#39;: 2, &#39;partitioned_by_unstructured&#39;: True, &#39;associated_query&#39;: &#39;what is wildfire?&#39;}}<br>{&#39;fragment_id&#39;: &#39;86853815-c750-5174-a538-1a831cd8451f&#39;, &#39;extraction_id&#39;: &#39;db89bbca-7a94-5ac6-907d-b983b8a69153&#39;, &#39;document_id&#39;: &#39;1917b668-4271-5ce4-b784-aee912fd40c9&#39;, &#39;user_id&#39;: &#39;2acb499e-8428-543b-bd85-0d9098718220&#39;, &#39;group_ids&#39;: [], &#39;score&#39;: 0.482953996482261, &#39;text&#39;: &#39;Most wildfires are human-caused (89% of the average number of wildfires from 2018 to 2022). Wildfires caused by lightning tend to be slightly larger and to burn more acreage (53% of the average acreage burned from 2018 to 2022) than human-caused fires.&#39;, &#39;metadata&#39;: {&#39;title&#39;: &#39;IF10244.pdf&#39;, &#39;version&#39;: &#39;v0&#39;, &#39;chunk_order&#39;: 0, &#39;document_type&#39;: &#39;pdf&#39;, &#39;unstructured_filetype&#39;: &#39;application/pdf&#39;, &#39;unstructured_languages&#39;: [&#39;eng&#39;], &#39;unstructured_parent_id&#39;: &#39;1cf31594d4c20ad9c1eec48eb0d58e36&#39;, &#39;unstructured_coordinates&#39;: {&#39;points&#39;: [[313.25, 671.61136], [313.25, 725.48736], [548.287, 725.48736], [548.287, 671.61136]], &#39;system&#39;: &#39;PixelSpace&#39;, &#39;layout_width&#39;: 612, &#39;layout_height&#39;: 792}, &#39;unstructured_page_number&#39;: 1, &#39;partitioned_by_unstructured&#39;: True, &#39;associated_query&#39;: &#39;what is wildfire?&#39;}}<br>{&#39;fragment_id&#39;: &#39;4adf5107-0dc6-5516-9753-75d838d148f1&#39;, &#39;extraction_id&#39;: &#39;e71a7a4b-c0b7-56e7-8cab-cd341fcefba5&#39;, &#39;document_id&#39;: &#39;1917b668-4271-5ce4-b784-aee912fd40c9&#39;, &#39;user_id&#39;: &#39;2acb499e-8428-543b-bd85-0d9098718220&#39;, &#39;group_ids&#39;: [], &#39;score&#39;: 0.4819944788214262, &#39;text&#39;: &#39;From 2013 to 2022, there were an average of 61,410 wildfires annually and an average of 7.2 million acres impacted annually. In 2022, 68,988 wildfires burned 7.6 million acres. Over 40% of those acres were in Alaska (3.1 million acres).&#39;, &#39;metadata&#39;: {&#39;title&#39;: &#39;IF10244.pdf&#39;, &#39;version&#39;: &#39;v0&#39;, &#39;chunk_order&#39;: 0, &#39;document_type&#39;: &#39;pdf&#39;, &#39;unstructured_filetype&#39;: &#39;application/pdf&#39;, &#39;unstructured_languages&#39;: [&#39;eng&#39;], &#39;unstructured_parent_id&#39;: &#39;396d19ebc80f33d147d9ffae264a2757&#39;, &#39;unstructured_coordinates&#39;: {&#39;points&#39;: [[313.25, 313.24136], [313.25, 367.12136000000004], [551.6812, 367.12136000000004], [551.6812, 313.24136]], &#39;system&#39;: &#39;PixelSpace&#39;, &#39;layout_width&#39;: 612, &#39;layout_height&#39;: 792}, &#39;unstructured_page_number&#39;: 1, &#39;partitioned_by_unstructured&#39;: True, &#39;associated_query&#39;: &#39;what is wildfire?&#39;}}<br>{&#39;fragment_id&#39;: &#39;4aa69047-72f0-5461-a484-cfc473bd5ca3&#39;, &#39;extraction_id&#39;: &#39;b551af9f-ced1-55ef-b5a6-605ec8b10ba5&#39;, &#39;document_id&#39;: &#39;1917b668-4271-5ce4-b784-aee912fd40c9&#39;, &#39;user_id&#39;: &#39;2acb499e-8428-543b-bd85-0d9098718220&#39;, &#39;group_ids&#39;: [], &#39;score&#39;: 0.47869345418771914, &#39;text&#39;: &#39;More wildfires occur in the East (including the central states), but the wildfires in the West (i.e., Alaska, Arizona, California, Colorado, Idaho, Montana, New Mexico, Nevada, Oregon, Utah, Washington, and Wyoming) are larger and burn more acreage. In 2022, just over 20,000 wildfires burned approximately 5.8 million acres in the West, compared with the over 48,000 fires that burned just over 1.8 million acres in the East. In the East (where there is less federal acreage), most of the fires occur on nonfederal lands; in the West, most of the fires occur on federal lands (see Figure 4). In 2022, 85% (1.5 million acres) of the acreage burned in the East was on nonfederal land, whereas 64% (3.7 million acres) of the acreage burned in the West was on federal land.&#39;, &#39;metadata&#39;: {&#39;title&#39;: &#39;IF10244.pdf&#39;, &#39;version&#39;: &#39;v0&#39;, &#39;chunk_order&#39;: 0, &#39;document_type&#39;: &#39;pdf&#39;, &#39;unstructured_filetype&#39;: &#39;application/pdf&#39;, &#39;unstructured_languages&#39;: [&#39;eng&#39;], &#39;unstructured_parent_id&#39;: &#39;6398d78142b135de705696ecde61d0c3&#39;, &#39;unstructured_coordinates&#39;: {&#39;points&#39;: [[57.6, 368.68136], [57.6, 521.58136], [300.896, 521.58136], [300.896, 368.68136]], &#39;system&#39;: &#39;PixelSpace&#39;, &#39;layout_width&#39;: 612, &#39;layout_height&#39;: 792}, &#39;unstructured_page_number&#39;: 2, &#39;partitioned_by_unstructured&#39;: True, &#39;associated_query&#39;: &#39;what is wildfire?&#39;}}<br>KG search results:<br>{&#39;local_result&#39;: {<br>&#39;query&#39;: &#39;what is wildfire?&#39;, <br>&#39;entities&#39;: {&#39;0&#39;: {&#39;name&#39;: &#39;Wildfire Recovery&#39;, &#39;description&#39;: &#39;Wildfire Recovery is the process aimed at restoring areas impacted by wildfires, focusing on rebuilding infrastructure, restoring ecosystems, and providing support to affected communities. This multifaceted approach emphasizes the importance of community assistance and environmental restoration as integral components of recovery efforts. Overall, Wildfire Recovery seeks to rehabilitate both the physical landscape and the social fabric of communities devastated by wildfires.&#39;}, &#39;1&#39;: {&#39;name&#39;: &#39;Wildfire&#39;, &#39;description&#39;: &#39;Wildfires are uncontrolled fires that occur in wildland areas, such as forests and grasslands, often exacerbated by dry conditions, high winds, and human activities. They can cause significant ecological and economic damage, impacting ecosystems, human property, and community safety. The Preparedness Level (PL) metric assesses the readiness for wildfire suppression, while statistics compiled by organizations like the National Interagency Coordination Center provide insights into wildfire frequency, intensity, and their effects over time, particularly in regions like California and Wyoming.&#39;}, &#39;2&#39;: {&#39;name&#39;: &#39;Wildfire Management&#39;, &#39;description&#39;: &#39;Wildfire Management refers to a comprehensive approach aimed at minimizing damage from wildfires through prevention, response, recovery, and restoration efforts, ultimately enhancing community resilience. Congress considers various strategies and resources related to wildfire management as part of its legislative responsibilities, emphasizing the importance of effective management in mitigating the impacts of wildfires. This holistic framework underscores the need for coordinated efforts in addressing the challenges posed by wildfires.&#39;}, &#39;3&#39;: {&#39;name&#39;: &#39;Wildfire Activity&#39;, &#39;description&#39;: &#39;Wildfire activity refers to the occurrence and intensity of wildfires, which can fluctuate annually due to various environmental factors. It is directly indicated by the number of fires and measured by the acreage burned, reflecting the extent of such activity. Additionally, wildfire activity has a significant impact on human development, particularly in urbanized areas.&#39;}, &#39;4&#39;: {&#39;name&#39;: &#39;Wildfire Mitigation&#39;, &#39;description&#39;: &#39;Wildfire mitigation refers to actions taken to reduce the severity and impact of wildfires, such as creating defensible space around properties and improving forest management practices. This concept is recognized and considered by Congress as part of its legislative agenda, emphasizing the importance of strategic approaches to address wildfire risks effectively.&#39;}, &#39;5&#39;: {&#39;name&#39;: &#39;Significant Fires&#39;, &#39;description&#39;: &#39;Significant fires are wildfires distinguished by their considerable size, impact, and the extensive resources required for their management. These fires are systematically tracked to gather statistical data, which aids in understanding trends in wildfire occurrences. Their monitoring is crucial for assessing the broader implications of wildfires on ecosystems and communities.&#39;}, &#39;6&#39;: {&#39;name&#39;: &#39;Post-Wildfire Recovery&#39;, &#39;description&#39;: &#39;Post-wildfire recovery refers to the process of addressing and mitigating the impacts of wildfires on affected communities and ecosystems. This recovery process is a significant concern for Congress, highlighting its importance in legislative discussions and policymaking. The entity encompasses various strategies and initiatives aimed at restoring areas devastated by wildfires, ensuring both environmental and community resilience.&#39;}, &#39;7&#39;: {&#39;name&#39;: &#39;Wildland Fire&#39;, &#39;description&#39;: &#39;Wildland fires are uncontrolled fires that occur in natural areas such as forests, grasslands, and prairies, posing significant threats to ecosystems and property. These fires can arise from both natural events and human activities and are reported in statistics that detail their occurrences and impacts over time. The National Interagency Coordination Center (NICC) plays a crucial role in managing wildland fire responses across the United States, documenting incidents in annual reports and noting that these fires can occur on both federal and nonfederal lands.&#39;}, &#39;8&#39;: {&#39;name&#39;: &#39;Wildfire Prevention&#39;, &#39;description&#39;: &#39;Wildfire prevention encompasses strategies and resources designed to mitigate the risk of wildfires, including controlled burns, firebreaks, and community education. These strategies are recognized by Congress as part of its legislative agenda, highlighting the importance of proactive measures in addressing wildfire risks. Overall, the entity aims to enhance public safety and environmental protection through effective wildfire management practices.&#39;}, &#39;9&#39;: {&#39;name&#39;: &#39;2000&#39;, &#39;description&#39;: &#39;The year 2000 serves as a critical reference point for analyzing wildfire activity and intensity, establishing a baseline for calculating the annual average of wildfires and acres burned. It is also utilized as a comparative benchmark for assessing the duration of the highest Preparedness Level in 2021. This timeline underscores the ecological significance of wildfire events and their historical context.&#39;}}, <br>&#39;relationships&#39;: {}, <br>&#39;communities&#39;: {}<br>}, <br>&#39;global_result&#39;: None}</pre><p><strong>Global searches</strong> can be used for queries that require reasoning over the whole dataset. They provide more accurate results, however they use a large amount of queries and are expensive.</p><p>Let ‘s ask a question where the answer can be extracted from different parts of the doc and require a global understanding of the content, a good question will be like : <strong>“How has the federal and nonfederal response to wildfires changed over the years in terms of fire occurrences and acreage burned?”.</strong></p><pre>r2r search --query=&quot;How has the federal and nonfederal response to wildfires changed over the years in terms of fire occurrences and acreage burned?&quot; <br>--use-kg-search --kg-search-type=global </pre><p>Extracting the global_result from the payload that is returned from above we find the following:</p><pre>### Overview of Wildfire Activity<br>In recent years, wildfire activity has remained significant, with both federal <br>and nonfederal lands experiencing substantial impacts. In 2022, there were <br>68,988 wildfires that burned approximately 7.6 million acres, underscoring the<br>high level of wildfire activity and the necessity for robust preparedness and <br>response strategies [Data: Reports (2022, Wildfire Impact Community 2022)]. <br>This trend continued into 2023, with approximately 18,300 wildfires affecting <br>over 511,000 acres, indicating ongoing challenges in wildfire management <br>[Data: Reports (2023, Wildfire Management Community)].<br><br>### Federal Lands and Management<br>Federal lands have been particularly affected, accounting for 52% of the <br>nationwide acreage burned by wildfires in 2022. <br>This highlights the critical role of federal agencies, such as the Forest <br>Service, in managing wildfire risks on these lands [Data: Reports (2022, <br>Wildfire Management Community: Forest Service and Federal Lands)]. <br>The Federal Government oversees various agencies that coordinate wildfire <br>responses, ensuring a unified approach and the efficient sharing of <br>resources and information among agencies [Data: Reports (Federal Government, <br>Wildfire Management Community)].\<br><br>### State and Nonfederal Lands<br>State lands also play a significant role in wildfire management, with nonfederal <br>lands accounting for 48% of the acreage burned in 2022. This emphasizes the <br>importance of state-level efforts in wildfire management and the substantial <br>burden placed on state resources during peak wildfire seasons [Data: Reports <br>(2022, Wildfire Management Community); Reports (States, States and Nonfederal <br>Lands in the East)].<br><br>### Coordination and Preparedness<br>The National Interagency Coordination Center (NICC) is pivotal in coordinating <br>wildfire response efforts and providing essential statistics on wildfire <br>occurrences. These statistics are instrumental in shaping policies and <br>preparedness measures [Data: Reports (NICC, Wildfire Impact Community 2022)]. <br>Additionally, the Preparedness Level (PL) is a critical metric used to assess<br>readiness and resource commitment for wildfire suppression, aiding agencies <br>in the effective allocation of resources [Data: Reports (Preparedness Level <br>(PL), Wildfire Impact Community 2022)].<br><br>### Implications and Future Directions<br>The data indicates that both federal and nonfederal entities must continue <br>to adapt and enhance their wildfire management strategies. The significant <br>acreage burned on both federal and nonfederal lands underscores the need <br>for coordinated efforts and resource sharing. As wildfire occurrences <br>remain high, ongoing evaluation and improvement of preparedness and <br>response strategies will be essential to mitigate the impacts of wildfires <br>effectively.<br><br>### conclusion, <br>the response to wildfires has evolved to address the increasing frequency <br>and severity of these events. Both federal and state agencies play crucial <br>roles, and their coordinated efforts are vital in managing wildfire risks <br>and minimizing damage [Data: Reports (2022, Wildfire Impact Community 2022; <br>2023, Wildfire Management Community; NICC, Wildfire Impact Community 2022; <br>Federal Government, Wildfire Management Community; States, States and <br>Nonfederal Lands in the East; Preparedness Level (PL), Wildfire Impact <br>Community 2022)].&#39;]}}</pre><p>Finally, You can directly use these search results as part of your RAG pipeline.</p><pre>r2r rag --query=&quot;what are the key actions taken to reduce wildfire occurrence?&quot; --use-kg-search --kg-search-type=global --max-llm-queries-for-global-search=10</pre><p>the output is as follow:</p><pre>{&#39;results&#39;: {<br>  &#39;completion&#39;: {<br>  &#39;id&#39;: &#39;chatcmpl-A6HpY2V8pfXyzm4mxTnbhdA8xFngo&#39;, <br>  &#39;choices&#39;: [<br>  {<br>       &#39;finish_reason&#39;: &#39;stop&#39;, <br>       &#39;index&#39;: 0, <br>       &#39;logprobs&#39;: None, <br>       &#39;message&#39;: {<br>     &#39;content&#39;: &#39;The major actions taken to reduce wildfire occurrence <br>      include:<br><br>1. **Federal Oversight and Coordination**: <br>The Federal Government oversees various federal agencies that manage wildfire responses, ensuring effective and efficient operations. <br>This includes facilitating the sharing of resources and information among <br>agencies to maintain a unified approach to wildfire management [12].<br><br>2. **Management of Federal Lands**: <br>The Federal Government implements policies and practices aimed at reducing wildfire risks on federal lands. This includes controlled burns and strategic land management to manage vegetation and other combustible materials [12].\n\n3. **State-Level Responsibilities**: States are responsible for managing nonfederal lands, including responding to wildfires. They manage local resources and emergency responses and are involved in long-term management strategies to mitigate wildfire risks [12].\n\n4. **Role of the Forest Service**: The Forest Service manages national forests and grasslands and collaborates with the National Interagency Coordination Center (NICC) to coordinate resources and response efforts during fire incidents. This ensures a cohesive strategy for managing wildfires across different regions [12].\n\n5. **Department of the Interior and NICC**: The Department of the Interior oversees the NICC, which is responsible for managing federal lands, including national parks and wildlife refuges. The NICC coordinates wildfire response efforts and provides essential statistics on wildfire occurrences, shaping policies and preparedness measures <br>for future wildfire seasons [12].<br>These actions collectively aim to mitigate wildfire risks and ensure a <br>coordinated response to wildfire incidents acros the United States.&#39;, <br><br>&#39;refusal&#39;: None, <br>&#39;role&#39;: &#39;assistant&#39;, &#39;function_call&#39;: None, &#39;tool_calls&#39;: None}}], &#39;created&#39;: 1726061872, &#39;model&#39;: &#39;gpt-4o-2024-05-13&#39;, &#39;object&#39;: &#39;chat.completion&#39;, &#39;service_tier&#39;: None, &#39;system_fingerprint&#39;: &#39;fp_25624ae3a5&#39;, &#39;usage&#39;: {&#39;completion_tokens&#39;: 293, &#39;prompt_tokens&#39;: 1630, &#39;total_tokens&#39;: 1923}}, &#39;search_results&#39;: {&#39;vector_search_results&#39;: [{&#39;fragment_id&#39;: &#39;0a56fb2d-7e65-5708-ad8f-af39a1389225&#39;, &#39;extraction_id&#39;: &#39;de935fb3-4077-5c9e-88e2-05a36da9bc67&#39;, &#39;document_id&#39;: &#39;1917b668-4271-5ce4-b784-aee912fd40c9&#39;, &#39;user_id&#39;: &#39;2acb499e-8428-543b-bd85-0d9098718220&#39;, &#39;group_ids&#39;: [], &#39;score&#39;: 0.5725441404418926, &#39;text&#39;: &#39;Wildfires are unplanned fires, including lightning-caused fires, unauthorized human-caused fires, and escaped fires from prescribed burn projects. States are responsible for responding to wildfires that begin on nonfederal (state, local, and private) lands, except for lands protected by federal agencies under cooperative agreements. The federal government is responsible for responding to wildfires that begin on federal lands. The Forest Service (FS)—within the U.S. Department of Agriculture—carries out wildfire management and response across the 193 million acres of the National Forest System (NFS). The Department of the Interior (DOI) manages wildfire response for more than 400 million acres of national parks, wildlife refuges and preserves, other public lands, and Indian reservations.&#39;, &#39;metadata&#39;: {&#39;title&#39;: &#39;IF10244.pdf&#39;, &#39;version&#39;: &#39;v0&#39;, &#39;chunk_order&#39;: 0, &#39;document_type&#39;: &#39;pdf&#39;, &#39;unstructured_filetype&#39;: &#39;application/pdf&#39;, &#39;unstructured_languages&#39;: [&#39;eng&#39;], &#39;unstructured_parent_id&#39;: &#39;255a3758f6916b1d06037f219de720e5&#39;, &#39;unstructured_coordinates&#39;: {&#39;points&#39;: [[57.6, 137.05136000000005], [57.6, 289.96136], [300.3451199999999, 289.96136], [300.3451199999999, 137.05136000000005]], &#39;system&#39;: &#39;PixelSpace&#39;, &#39;layout_width&#39;: 612, &#39;layout_height&#39;: 792}, &#39;unstructured_page_number&#39;: 1, &#39;partitioned_by_unstructured&#39;: True, &#39;associated_query&#39;: &#39;what are the major actions taken to reduce wildfire occurence?&#39;}}, {&#39;fragment_id&#39;: &#39;0ccb57e1-67f0-5a48-a0dc-51cc37deabf9&#39;, &#39;extraction_id&#39;: &#39;79e820a0-6609-57ff-b081-df56eb6c3b9b&#39;, &#39;document_id&#39;: &#39;1917b668-4271-5ce4-b784-aee912fd40c9&#39;, &#39;user_id&#39;: &#39;2acb499e-8428-543b-bd85-0d9098718220&#39;, &#39;group_ids&#39;: [], &#39;score&#39;: 0.5609308481216471, &#39;text&#39;: &#39;Issues for Congress Issues Congress may consider include the strategies and resources used for wildfire prevention, mitigation, and management, as well as wildfires’ impact on both the quality of life and the economies of communities affected by wildfire activity. Other issues relate to post-wildfire recovery and site restoration. Congress also considers the total federal cost of wildfire management, including the cost of suppression operations; these costs vary annually and are difficult to predict.&#39;, &#39;metadata&#39;: {&#39;title&#39;: &#39;IF10244.pdf&#39;, &#39;version&#39;: &#39;v0&#39;, &#39;chunk_order&#39;: 0, &#39;document_type&#39;: &#39;pdf&#39;, &#39;unstructured_filetype&#39;: &#39;application/pdf&#39;, &#39;unstructured_languages&#39;: [&#39;eng&#39;], &#39;unstructured_parent_id&#39;: &#39;02b65f46a42a77ad802305f45be1c490&#39;, &#39;unstructured_coordinates&#39;: {&#39;points&#39;: [[313.25, 591.5908], [313.25, 700.28736], [546.8705199999999, 700.28736], [546.8705199999999, 591.5908]], &#39;system&#39;: &#39;PixelSpace&#39;, &#39;layout_width&#39;: 612, &#39;layout_height&#39;: 792}, &#39;unstructured_page_number&#39;: 2, &#39;partitioned_by_unstructured&#39;: True, &#39;associated_query&#39;: &#39;what are the major actions taken to reduce wildfire occurence?&#39;}}, {&#39;fragment_id&#39;: &#39;06e77cd3-97be-556c-a2a6-20d3c4f5d436&#39;, &#39;extraction_id&#39;: &#39;f595c645-553c-5eeb-92ae-aa7ce115247a&#39;, &#39;document_id&#39;: &#39;1917b668-4271-5ce4-b784-aee912fd40c9&#39;, &#39;user_id&#39;: &#39;2acb499e-8428-543b-bd85-0d9098718220&#39;, &#39;group_ids&#39;: [], &#39;score&#39;: 0.5178843427965446, &#39;text&#39;: &#39;Resources Another metric useful for assessing wildfire activity is the extent to which nationwide resources—including personnel and equipment—are engaged in wildfire suppression. A proxy for resource commitments is the nationwide Preparedness Level (PL) scale, which ranges from 1 (lowest) to 5 (highest). The higher PLs indicate significant commitment of shared resources. In 2022, the nationwide level was 4 for 10 days and never reached the highest level (5). In contrast, the highest level was reached for 68 days in 2021, the longest since at least 2000.&#39;, &#39;metadata&#39;: {&#39;title&#39;: &#39;IF10244.pdf&#39;, &#39;version&#39;: &#39;v0&#39;, &#39;chunk_order&#39;: 0, &#39;document_type&#39;: &#39;pdf&#39;, &#39;unstructured_filetype&#39;: &#39;application/pdf&#39;, &#39;unstructured_languages&#39;: [&#39;eng&#39;], &#39;unstructured_parent_id&#39;: &#39;5d5d84e16dabad197393ed3b4045dc7b&#39;, &#39;unstructured_coordinates&#39;: {&#39;points&#39;: [[313.25, 48.13079999999991], [313.25, 168.13135999999997], [555.05872, 168.13135999999997], [555.05872, 48.13079999999991]], &#39;system&#39;: &#39;PixelSpace&#39;, &#39;layout_width&#39;: 612, &#39;layout_height&#39;: 792}, &#39;unstructured_page_number&#39;: 2, &#39;partitioned_by_unstructured&#39;: True, &#39;associated_query&#39;: &#39;what are the major actions taken to reduce wildfire occurence?&#39;}}, {&#39;fragment_id&#39;: &#39;ded015b5-7f7d-5d18-9dd1-49d195662d04&#39;, &#39;extraction_id&#39;: &#39;697a1581-6043-5053-868a-9595c5b31453&#39;, &#39;document_id&#39;: &#39;1917b668-4271-5ce4-b784-aee912fd40c9&#39;, &#39;user_id&#39;: &#39;2acb499e-8428-543b-bd85-0d9098718220&#39;, &#39;group_ids&#39;: [], &#39;score&#39;: 0.5065002735555018, &#39;text&#39;: &#39;Wildfire statistics help illustrate past U.S. wildfire activity. Nationwide data compiled by the National Interagency Coordination Center (NICC) indicate that the number of annual wildfires is variable but has decreased slightly over the last 30 years. The number of acres affected annually, while also variable, generally has increased (see Figure 1). Since 2000, an annual average of 70,025 wildfires have burned an annual average of 7.0 million acres. The acreage figure is more than double the average annual acreage burned in the 1990s (3.3 million acres), although a greater number of fires occurred annually in the 1990s on average (78,600).&#39;, &#39;metadata&#39;: {&#39;title&#39;: &#39;IF10244.pdf&#39;, &#39;version&#39;: &#39;v0&#39;, &#39;chunk_order&#39;: 0, &#39;document_type&#39;: &#39;pdf&#39;, &#39;unstructured_filetype&#39;: &#39;application/pdf&#39;, &#39;unstructured_languages&#39;: [&#39;eng&#39;], &#39;unstructured_parent_id&#39;: &#39;396d19ebc80f33d147d9ffae264a2757&#39;, &#39;unstructured_coordinates&#39;: {&#39;points&#39;: [[57.6, 302.08135999999996], [57.6, 432.90136], [296.76691999999997, 432.90136], [296.76691999999997, 302.08135999999996]], &#39;system&#39;: &#39;PixelSpace&#39;, &#39;layout_width&#39;: 612, &#39;layout_height&#39;: 792}, &#39;unstructured_page_number&#39;: 1, &#39;partitioned_by_unstructured&#39;: True, &#39;associated_query&#39;: &#39;what are the major actions taken to reduce wildfire occurence?&#39;}}, {&#39;fragment_id&#39;: &#39;4aa69047-72f0-5461-a484-cfc473bd5ca3&#39;, &#39;extraction_id&#39;: &#39;b551af9f-ced1-55ef-b5a6-605ec8b10ba5&#39;, &#39;document_id&#39;: &#39;1917b668-4271-5ce4-b784-aee912fd40c9&#39;, &#39;user_id&#39;: &#39;2acb499e-8428-543b-bd85-0d9098718220&#39;, &#39;group_ids&#39;: [], &#39;score&#39;: 0.49829855571397896, &#39;text&#39;: &#39;More wildfires occur in the East (including the central states), but the wildfires in the West (i.e., Alaska, Arizona, California, Colorado, Idaho, Montana, New Mexico, Nevada, Oregon, Utah, Washington, and Wyoming) are larger and burn more acreage. In 2022, just over 20,000 wildfires burned approximately 5.8 million acres in the West, compared with the over 48,000 fires that burned just over 1.8 million acres in the East. In the East (where there is less federal acreage), most of the fires occur on nonfederal lands; in the West, most of the fires occur on federal lands (see Figure 4). In 2022, 85% (1.5 million acres) of the acreage burned in the East was on nonfederal land, whereas 64% (3.7 million acres) of the acreage burned in the West was on federal land.&#39;, &#39;metadata&#39;: {&#39;title&#39;: &#39;IF10244.pdf&#39;, &#39;version&#39;: &#39;v0&#39;, &#39;chunk_order&#39;: 0, &#39;document_type&#39;: &#39;pdf&#39;, &#39;unstructured_filetype&#39;: &#39;application/pdf&#39;, &#39;unstructured_languages&#39;: [&#39;eng&#39;], &#39;unstructured_parent_id&#39;: &#39;6398d78142b135de705696ecde61d0c3&#39;, &#39;unstructured_coordinates&#39;: {&#39;points&#39;: [[57.6, 368.68136], [57.6, 521.58136], [300.896, 521.58136], [300.896, 368.68136]], &#39;system&#39;: &#39;PixelSpace&#39;, &#39;layout_width&#39;: 612, &#39;layout_height&#39;: 792}, &#39;unstructured_page_number&#39;: 2, &#39;partitioned_by_unstructured&#39;: True, &#39;associated_query&#39;: &#39;what are the major actions taken to reduce wildfire occurence?&#39;}}, {&#39;fragment_id&#39;: &#39;4adf5107-0dc6-5516-9753-75d838d148f1&#39;, &#39;extraction_id&#39;: &#39;e71a7a4b-c0b7-56e7-8cab-cd341fcefba5&#39;, &#39;document_id&#39;: &#39;1917b668-4271-5ce4-b784-aee912fd40c9&#39;, &#39;user_id&#39;: &#39;2acb499e-8428-543b-bd85-0d9098718220&#39;, &#39;group_ids&#39;: [], &#39;score&#39;: 0.48479345531502727, &#39;text&#39;: &#39;From 2013 to 2022, there were an average of 61,410 wildfires annually and an average of 7.2 million acres impacted annually. In 2022, 68,988 wildfires burned 7.6 million acres. Over 40% of those acres were in Alaska (3.1 million acres).&#39;, &#39;metadata&#39;: {&#39;title&#39;: &#39;IF10244.pdf&#39;, &#39;version&#39;: &#39;v0&#39;, &#39;chunk_order&#39;: 0, &#39;document_type&#39;: &#39;pdf&#39;, &#39;unstructured_filetype&#39;: &#39;application/pdf&#39;, &#39;unstructured_languages&#39;: [&#39;eng&#39;], &#39;unstructured_parent_id&#39;: &#39;396d19ebc80f33d147d9ffae264a2757&#39;, &#39;unstructured_coordinates&#39;: {&#39;points&#39;: [[313.25, 313.24136], [313.25, 367.12136000000004], [551.6812, 367.12136000000004], [551.6812, 313.24136]], &#39;system&#39;: &#39;PixelSpace&#39;, &#39;layout_width&#39;: 612, &#39;layout_height&#39;: 792}, &#39;unstructured_page_number&#39;: 1, &#39;partitioned_by_unstructured&#39;: True, &#39;associated_query&#39;: &#39;what are the major actions taken to reduce wildfire occurence?&#39;}}, {&#39;fragment_id&#39;: &#39;40168532-51c4-5e76-b9cb-995bd7f2096d&#39;, &#39;extraction_id&#39;: &#39;1ac90a9a-c82e-532a-95af-b22a044a643f&#39;, &#39;document_id&#39;: &#39;1917b668-4271-5ce4-b784-aee912fd40c9&#39;, &#39;user_id&#39;: &#39;2acb499e-8428-543b-bd85-0d9098718220&#39;, &#39;group_ids&#39;: [], &#39;score&#39;: 0.47282016601322097, &#39;text&#39;: &#39;Wildfire Statistics&#39;, &#39;metadata&#39;: {&#39;title&#39;: &#39;IF10244.pdf&#39;, &#39;version&#39;: &#39;v0&#39;, &#39;chunk_order&#39;: 0, &#39;document_type&#39;: &#39;pdf&#39;, &#39;unstructured_filetype&#39;: &#39;application/pdf&#39;, &#39;unstructured_languages&#39;: [&#39;eng&#39;], &#39;unstructured_coordinates&#39;: {&#39;points&#39;: [[485.98, 24.840000000000032], [485.98, 35.879999999999995], [556.99504, 35.879999999999995], [556.99504, 24.840000000000032]], &#39;system&#39;: &#39;PixelSpace&#39;, &#39;layout_width&#39;: 612, &#39;layout_height&#39;: 792}, &#39;unstructured_page_number&#39;: 3, &#39;partitioned_by_unstructured&#39;: True, &#39;associated_query&#39;: &#39;what are the major actions taken to reduce wildfire occurence?&#39;}}, {&#39;fragment_id&#39;: &#39;fd76a8f9-b4bf-52c3-986b-441b59844892&#39;, &#39;extraction_id&#39;: &#39;1c29fb7f-f464-5bf1-886d-d9ca2e269941&#39;, &#39;document_id&#39;: &#39;1917b668-4271-5ce4-b784-aee912fd40c9&#39;, &#39;user_id&#39;: &#39;2acb499e-8428-543b-bd85-0d9098718220&#39;, &#39;group_ids&#39;: [], &#39;score&#39;: 0.4727874116428257, &#39;text&#39;: &#39;Wildfire Statistics&#39;, &#39;metadata&#39;: {&#39;title&#39;: &#39;IF10244.pdf&#39;, &#39;version&#39;: &#39;v0&#39;, &#39;chunk_order&#39;: 0, &#39;document_type&#39;: &#39;pdf&#39;, &#39;unstructured_filetype&#39;: &#39;application/pdf&#39;, &#39;unstructured_languages&#39;: [&#39;eng&#39;], &#39;unstructured_coordinates&#39;: {&#39;points&#39;: [[57.6, 106.98800000000006], [57.6, 124.98800000000006], [196.09199999999998, 124.98800000000006], [196.09199999999998, 106.98800000000006]], &#39;system&#39;: &#39;PixelSpace&#39;, &#39;layout_width&#39;: 612, &#39;layout_height&#39;: 792}, &#39;unstructured_page_number&#39;: 1, &#39;partitioned_by_unstructured&#39;: True, &#39;associated_query&#39;: &#39;what are the major actions taken to reduce wildfire occurence?&#39;}}, {&#39;fragment_id&#39;: &#39;5fd08a9c-7eb5-5a7c-8d0c-1095963ac8e2&#39;, &#39;extraction_id&#39;: &#39;b3914c5c-169a-576d-9468-79b658d2a927&#39;, &#39;document_id&#39;: &#39;1917b668-4271-5ce4-b784-aee912fd40c9&#39;, &#39;user_id&#39;: &#39;2acb499e-8428-543b-bd85-0d9098718220&#39;, &#39;group_ids&#39;: [], &#39;score&#39;: 0.4727874116428257, &#39;text&#39;: &#39;Wildfire Statistics&#39;, &#39;metadata&#39;: {&#39;title&#39;: &#39;IF10244.pdf&#39;, &#39;version&#39;: &#39;v0&#39;, &#39;chunk_order&#39;: 0, &#39;document_type&#39;: &#39;pdf&#39;, &#39;unstructured_filetype&#39;: &#39;application/pdf&#39;, &#39;unstructured_languages&#39;: [&#39;eng&#39;], &#39;unstructured_coordinates&#39;: {&#39;points&#39;: [[485.98, 24.840000000000032], [485.98, 35.879999999999995], [556.99504, 35.879999999999995], [556.99504, 24.840000000000032]], &#39;system&#39;: &#39;PixelSpace&#39;, &#39;layout_width&#39;: 612, &#39;layout_height&#39;: 792}, &#39;unstructured_page_number&#39;: 2, &#39;partitioned_by_unstructured&#39;: True, &#39;associated_query&#39;: &#39;what are the major actions taken to reduce wildfire occurence?&#39;}}, {&#39;fragment_id&#39;: &#39;3a357a58-71e6-5292-8e58-27cc700abe49&#39;, &#39;extraction_id&#39;: &#39;686dca1b-1ec1-5526-98f2-d603371dbbda&#39;, &#39;document_id&#39;: &#39;1917b668-4271-5ce4-b784-aee912fd40c9&#39;, &#39;user_id&#39;: &#39;2acb499e-8428-543b-bd85-0d9098718220&#39;, &#39;group_ids&#39;: [], &#39;score&#39;: 0.47061704186746534, &#39;text&#39;: &#39;Wildfire Damages Wildfires may affect certain ecological resources beneficially, but wildfires also may have devastating impacts, especially for communities affected by wildfire activity. Statistics showing the level of destruction a wildfire caused can provide useful metrics to evaluate the fire’s effect. Such statistics may include acres burned or impacted, lives lost (firefighters and civilians), and structures (residential, commercial, and other) destroyed. For example, in 2022, over 2,700 structures were burned in wildfires; the majority of the damage occurred in California (see Table 2).&#39;, &#39;metadata&#39;: {&#39;title&#39;: &#39;IF10244.pdf&#39;, &#39;version&#39;: &#39;v0&#39;, &#39;chunk_order&#39;: 0, &#39;document_type&#39;: &#39;pdf&#39;, &#39;unstructured_filetype&#39;: &#39;application/pdf&#39;, &#39;unstructured_languages&#39;: [&#39;eng&#39;], &#39;unstructured_parent_id&#39;: &#39;f2a69199a012bb00be04e8a085259b82&#39;, &#39;unstructured_coordinates&#39;: {&#39;points&#39;: [[313.25, 178.23079999999993], [313.25, 309.16136], [555.3100000000001, 309.16136], [555.3100000000001, 178.23079999999993]], &#39;system&#39;: &#39;PixelSpace&#39;, &#39;layout_width&#39;: 612, &#39;layout_height&#39;: 792}, &#39;unstructured_page_number&#39;: 2, &#39;partitioned_by_unstructured&#39;: True, &#39;associated_query&#39;: &#39;what are the major actions taken to reduce wildfire occurence?&#39;}}], &#39;kg_search_results&#39;: [{&#39;local_result&#39;: None, &#39;global_result&#39;: {&#39;query&#39;: &#39;what are the major actions taken to reduce wildfire occurence?&#39;, &#39;search_result&#39;: [&#39;## Major Actions Taken to Reduce Wildfire Occurrence\n\n### Federal Oversight and Coordination\n\nThe Federal Government plays a pivotal role in overseeing various federal agencies that manage wildfire responses. This oversight ensures that these organizations operate effectively and efficiently, facilitating the sharing of resources and information among agencies. Such coordination is crucial for maintaining a unified approach to wildfire management [Data: Reports (2, 3)].\n\n### Management of Federal Lands\n\nThe management of federal lands is a critical component in preventing and responding to wildfires. The Federal Government implements policies and practices aimed at reducing wildfire risks, such as controlled burns and strategic land management. These measures are designed to mitigate the potential for wildfires by managing vegetation and other combustible materials on federal lands [Data: Reports (1, 1)].\n\n### State-Level Responsibilities\n\nStates hold the authority to govern and manage nonfederal lands, which includes the responsibility of responding to wildfires. This jurisdiction allows states to effectively manage local resources and emergency responses to environmental challenges. States are not only involved in immediate firefighting efforts but also in long-term management strategies to mitigate wildfire risks [Data: Reports (1, 2, 3)].\n\n### Role of the Forest Service\n\nThe Forest Service is a key entity responsible for managing national forests and grasslands, including wildfire management. It collaborates with the National Interagency Coordination Center (NICC) to coordinate resources and response efforts during fire incidents. This collaboration ensures that there is a cohesive strategy in place for managing wildfires across different regions [Data: Reports (1, 3, 4, 5)].\n\n### Department of the Interior and NICC\n\nThe Department of the Interior oversees the NICC and is responsible for managing federal lands, including national parks and wildlife refuges. This oversight is essential for ensuring that wildfire management strategies are effectively implemented across various federal lands. The NICC plays a crucial role in coordinating wildfire response efforts and providing essential statistics on wildfire occurrences, which are instrumental in shaping policies and preparedness measures for future wildfire seasons [Data: Reports (4, 6, 7, 8)].\n\n### Conclusion\n\nIn summary, the major actions taken to reduce wildfire occurrence involve a combination of federal oversight, strategic land management, state-level responsibilities, and coordinated efforts by key entities such as the Forest Service and the NICC. These measures collectively aim to mitigate wildfire risks and ensure a coordinated response to wildfire incidents across the United States.&#39;]}}]}}}<br></pre><p>To conclude, integrating R2R with GraphRAG greatly enhances the functionality of RAG applications. By harnessing the power of graph-based knowledge representations, GraphRAG enables more nuanced and context-sensitive information retrieval. This was demonstrated in our example query with R2R, which not only retrieved relevant data but also delivered a structured analysis of actions taken to reduce wildfire occurrences.</p><p>In the Next blog, we will dive deeper in GraphRAG Theory, and illustrate the difference between GraphRAG and RAG comparing answers from both using the same question, and the most important is how could we ingest multimodal documents which contain text, images , tables, charts and get the best possible results from GraphRAG.</p><p>Ref : <a href="https://r2r-docs.sciphi.ai/introduction">r2r docs</a>, <a href="https://www.sciphi.ai/">Sciphi</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=692bc8778360" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Harnessing RAG for Text, Tables, and Images: A Comprehensive Guide]]></title>
            <link>https://medium.com/@kbouziane.ai/harnessing-rag-for-text-tables-and-images-a-comprehensive-guide-ca4d2d420219?source=rss-8b767210b35c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca4d2d420219</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[multimodal-rag]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[khalid bouziane]]></dc:creator>
            <pubDate>Tue, 28 Nov 2023 10:11:12 GMT</pubDate>
            <atom:updated>2023-11-28T10:11:12.156Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_9o9DiGrZ66TXvHf" /></figure><p>In the realm of information retrieval, Retrieval Augmented Generation (RAG) has emerged as a powerful tool for extracting knowledge from vast amounts of text data. This versatile technique leverages a combination of retrieval and generation strategies to effectively summarize and synthesize information from relevant documents. However, while RAG has gained considerable traction, its application to a broader range of content types, encompassing text, tables, and images, remains relatively unexplored.</p><p><strong>The Challenge of Multimodal Content</strong></p><p>Most real-world documents contain a rich tapestry of information, often combining text, tables, and images to convey complex ideas and insights. While traditional RAG models excel at processing text, they struggle to effectively integrate and comprehend multimodal content. This limitation hinders the ability of RAG to fully capture the essence of these documents, potentially leading to incomplete or inaccurate representations.</p><p>In this post we will explore how to create a Multi-modal RAG that can handle these types of documents.<br>Here is a graph that we will use as a guide to process such documents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SDpKs-GxgosuQsjQrwBjhg.png" /><figcaption>Multi-Modal RAG</figcaption></figure><p><strong>Step 1 : Split the file to raw elements.</strong></p><p>First, let’s import all necessary libraries to our environment</p><pre>import os<br>import openai<br>import io<br>import uuid<br>import base64<br>import time <br>from base64 import b64decode<br>import numpy as np<br>from PIL import Image<br><br>from unstructured.partition.pdf import partition_pdf<br><br>from langchain.chat_models import ChatOpenAI<br>from langchain.schema.messages import HumanMessage, SystemMessage<br>from langchain.vectorstores import Chroma<br>from langchain.storage import InMemoryStore<br>from langchain.schema.document import Document<br>from langchain.embeddings import OpenAIEmbeddings<br>from langchain.retrievers.multi_vector import MultiVectorRetriever<br>from langchain.chat_models import ChatOpenAI<br>from langchain.prompts import ChatPromptTemplate<br>from langchain.schema.output_parser import StrOutputParser<br>from langchain.schema.runnable import RunnablePassthrough, RunnableLambda<br><br>from operator import itemgetter</pre><p>We will use <a href="https://unstructured.io/">Unstructured</a> to parse images, texts, and tables from documents (PDFs), you can run this code directly in this <a href="https://colab.research.google.com/drive/1I9-JMGL76XXzUel7XTjO8pWK7jV-V8WD?usp=sharing">google colab</a>, or download the pdf file from <a href="https://sgp.fas.org/crs/misc/IF10244.pdf">here</a> ,upload it to session storage. and follow steps below.</p><blockquote>( Refer to the installation instructions in google colab to setup your venv before excuting the code )</blockquote><pre># load the pdf file to drive<br># split the file to text, table and images<br>def doc_partition(path,file_name):<br>  raw_pdf_elements = partition_pdf(<br>    filename=path + file_name,<br>    extract_images_in_pdf=True,<br>    infer_table_structure=True,<br>    chunking_strategy=&quot;by_title&quot;,<br>    max_characters=4000,<br>    new_after_n_chars=3800,<br>    combine_text_under_n_chars=2000,<br>    image_output_dir_path=path)<br><br>  return raw_pdf_elements<br>path = &quot;/content/&quot;<br>file_name = &quot;wildfire_stats.pdf&quot;<br>raw_pdf_elements = doc_partition(path,file_name)</pre><p>Once you run the code above, all images included in the file will be extracted and saved in your path. in our case (path = “/content/”)</p><p>Next we will append each raw element to its category, (text to texts ,table to tables, for images, <em>unstructed</em> has taken care of that already..).</p><pre># appending texts and tables from the pdf file<br>def data_category(raw_pdf_elements): # we may use decorator here<br>    tables = []<br>    texts = []<br>    for element in raw_pdf_elements:<br>        if &quot;unstructured.documents.elements.Table&quot; in str(type(element)):<br>           tables.append(str(element))<br>        elif &quot;unstructured.documents.elements.CompositeElement&quot; in str(type(element)):<br>           texts.append(str(element))<br>    data_category = [texts,tables]<br>    return data_category<br>texts = data_category(raw_pdf_elements)[0]<br>tables = data_category(raw_pdf_elements)[1]</pre><p><strong>Step 2 : Image captioning and table summarizing</strong></p><p>For summarizing tables, we will use Langchain and GPT-4. For generating image captions, we will use GPT-4-Vision-Preview. This is because it is the only model that can currently handle multiple images together, which is important for our documents that contain multiple images. For text elements, we will leave them as they are before making them into embeddings.</p><p>Get your OpenAI API key ready</p><pre>os.environ[&quot;OPENAI_API_KEY&quot;] = &#39;sk-xxxxxxxxxxxxxxx&#39;<br>openai.api_key = os.environ[&quot;OPENAI_API_KEY&quot;]</pre><pre># function to take tables as input and then summarize them<br>def tables_summarize(data_category):<br>    prompt_text = &quot;&quot;&quot;You are an assistant tasked with summarizing tables. \<br>                    Give a concise summary of the table. Table chunk: {element} &quot;&quot;&quot;<br><br>    prompt = ChatPromptTemplate.from_template(prompt_text)<br>    model = ChatOpenAI(temperature=0, model=&quot;gpt-4&quot;)<br>    summarize_chain = {&quot;element&quot;: lambda x: x} | prompt | model | StrOutputParser()<br>    table_summaries = summarize_chain.batch(tables, {&quot;max_concurrency&quot;: 5})<br>    <br><br>    return table_summaries<br>table_summaries = tables_summarize(data_category)<br>text_summaries = texts</pre><p>For images we need to encode them to base64 format before feeding them to our model for captioning</p><pre>def encode_image(image_path):<br>    &#39;&#39;&#39; Getting the base64 string &#39;&#39;&#39;<br>    with open(image_path, &quot;rb&quot;) as image_file:<br>        return base64.b64encode(image_file.read()).decode(&#39;utf-8&#39;)<br><br>def image_captioning(img_base64,prompt):<br>    &#39;&#39;&#39; Image summary &#39;&#39;&#39;<br>    chat = ChatOpenAI(model=&quot;gpt-4-vision-preview&quot;,<br>                      max_tokens=1024)<br><br>    msg = chat.invoke(<br>        [<br>            HumanMessage(<br>                content=[<br>                    {&quot;type&quot;: &quot;text&quot;, &quot;text&quot;:prompt},<br>                    {<br>                        &quot;type&quot;: &quot;image_url&quot;,<br>                        &quot;image_url&quot;: {<br>                            &quot;url&quot;: f&quot;data:image/jpeg;base64,{img_base64}&quot;<br>                        },<br>                    },<br>                ]<br>            )<br>        ]<br>    )<br>    return msg.content</pre><p>Now we can append our list of images_base64 and summarize them, then we split base64-encoded images and their associated texts.</p><p>while running the code below you may get this RateLimitError with error code 429. This error occurs when you’ve exceeded the rate limit for requests per minute (RPM) for the gpt-4-vision-preview in your organization, in my case, I have a usage limit of 3 RPM, so after each image captioning, I set 60s as a safety mesure and wait for the rate limit to reset.</p><pre># Store base64 encoded images<br>img_base64_list = []<br><br># Store image summaries<br>image_summaries = []<br><br># Prompt : Our prompt here is customized to the type of images we have which is chart in our case<br>prompt = &quot;Describe the image in detail. Be specific about graphs, such as bar plots.&quot;<br><br># Read images, encode to base64 strings<br>for img_file in sorted(os.listdir(path)):<br>    if img_file.endswith(&#39;.jpg&#39;):<br>        img_path = os.path.join(path, img_file)<br>        base64_image = encode_image(img_path)<br>        img_base64_list.append(base64_image)<br>        img_capt = image_captioning(base64_image,prompt)<br>        time.sleep(60)<br>        image_summaries.append(image_captioning(img_capt,prompt))</pre><pre>def split_image_text_types(docs):<br>    &#39;&#39;&#39; Split base64-encoded images and texts &#39;&#39;&#39;<br>    b64 = []<br>    text = []<br>    for doc in docs:<br>        try:<br>            b64decode(doc)<br>            b64.append(doc)<br>        except Exception as e:<br>            text.append(doc)<br>    return {<br>        &quot;images&quot;: b64,<br>        &quot;texts&quot;: text<br>    }</pre><p><strong>Step 3</strong> : <strong>Create a Multi-vector retriever and store texts, tables, images and their indexes in a Vectore Base</strong></p><p>We have completed the first part, wich include document partitioning to raw elements, summarizing tables and images, now we are ready for the second part, where we will create a multi-vector retriever and store our outputs from part one in chromadb along with their ids.</p><blockquote>1. we create a vectorestore to index the child chunks (summary_texts ,summary_tables, summary_img), and use OpenAIEmbeddings() for embeddings,</blockquote><blockquote>2 .A docstore for the parent documents to store (doc_ids, texts), (table_ids, tables) and (img_ids, img_base64_list)</blockquote><pre># The vectorstore to use to index the child chunks<br>vectorstore = Chroma(collection_name=&quot;multi_modal_rag&quot;,<br>                     embedding_function=OpenAIEmbeddings())<br><br># The storage layer for the parent documents<br>store = InMemoryStore()<br>id_key = &quot;doc_id&quot;<br><br># The retriever (empty to start)<br>retriever = MultiVectorRetriever(<br>    vectorstore=vectorstore,<br>    docstore=store,<br>    id_key=id_key,<br>)<br><br># Add texts<br>doc_ids = [str(uuid.uuid4()) for _ in texts]<br>summary_texts = [<br>    Document(page_content=s, metadata={id_key: doc_ids[i]})<br>    for i, s in enumerate(text_summaries)<br>]<br>retriever.vectorstore.add_documents(summary_texts)<br>retriever.docstore.mset(list(zip(doc_ids, texts)))<br><br># Add tables<br>table_ids = [str(uuid.uuid4()) for _ in tables]<br>summary_tables = [<br>    Document(page_content=s, metadata={id_key: table_ids[i]})<br>    for i, s in enumerate(table_summaries)<br>]<br>retriever.vectorstore.add_documents(summary_tables)<br>retriever.docstore.mset(list(zip(table_ids, tables)))<br><br># Add image summaries<br>img_ids = [str(uuid.uuid4()) for _ in img_base64_list]<br>summary_img = [<br>    Document(page_content=s, metadata={id_key: img_ids[i]})<br>    for i, s in enumerate(image_summaries)<br>]<br>retriever.vectorstore.add_documents(summary_img)<br>retriever.docstore.mset(list(zip(img_ids, img_base64_list)))</pre><p><strong>Step 4 : Wrap all the above using langchain RunnableLambda</strong></p><ul><li>We first compute the context (both “texts” and “images” in this case) and the question (just a RunnablePassthrough here)</li><li>Then we pass this into our prompt template, which is a custom function that formats the message for the gpt-4-vision-preview model.</li><li>And finally we parse the output as a string.</li></ul><pre>from operator import itemgetter<br>from langchain.schema.runnable import RunnablePassthrough, RunnableLambda<br><br>def prompt_func(dict):<br>    format_texts = &quot;\n&quot;.join(dict[&quot;context&quot;][&quot;texts&quot;])<br>    return [<br>        HumanMessage(<br>            content=[<br>                {&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: f&quot;&quot;&quot;Answer the question based only on the following context, which can include text, tables, and the below image:<br>Question: {dict[&quot;question&quot;]}<br><br>Text and tables:<br>{format_texts}<br>&quot;&quot;&quot;},<br>                {&quot;type&quot;: &quot;image_url&quot;, &quot;image_url&quot;: {&quot;url&quot;: f&quot;data:image/jpeg;base64,{dict[&#39;context&#39;][&#39;images&#39;][0]}&quot;}},<br>            ]<br>        )<br>    ]<br><br>model = ChatOpenAI(temperature=0, model=&quot;gpt-4-vision-preview&quot;, max_tokens=1024)<br><br># RAG pipeline<br>chain = (<br>    {&quot;context&quot;: retriever | RunnableLambda(split_image_text_types), &quot;question&quot;: RunnablePassthrough()}<br>    | RunnableLambda(prompt_func)<br>    | model<br>    | StrOutputParser()<br>      )</pre><p>Now, we are ready to test our Multi-retrieval Rag</p><pre>chain.invoke(<br>    &quot;What is the change in wild fires from 1993 to 2022?&quot;<br>)</pre><p>here is the answer :</p><blockquote>Based on the provided chart, the number of wildfires has increased from 1993 to 2022. The chart shows a line graph with the number of fires in thousands, which appears to start at a lower point in 1993 and ends at a higher point in 2022. The exact numbers for 1993 are not provided in the text or visible on the chart, but the visual trend indicates an increase.</blockquote><blockquote>Similarly, the acres burned, represented by the shaded area in the chart, also show an increase from 1993 to 2022. The starting point of the shaded area in 1993 is lower than the ending point in 2022, suggesting that more acres have been burned in 2022 compared to 1993. Again, the specific figures for 1993 are not provided, but the visual trend on the chart indicates an increase in the acres burned over this time period.to do</blockquote><p><strong>References</strong> :</p><p><a href="https://python.langchain.com/docs/modules/data_connection/retrievers/multi_vector">https://python.langchain.com/docs/modules/data_connection/retrievers/multi_vector</a></p><p><a href="https://blog.langchain.dev/semi-structured-multi-modal-rag/">https://blog.langchain.dev/semi-structured-multi-modal-rag/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca4d2d420219" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>