<?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 Mohamed Ben Ticha on Medium]]></title>
        <description><![CDATA[Stories by Mohamed Ben Ticha on Medium]]></description>
        <link>https://medium.com/@medbenticha?source=rss-cce4b18d0619------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xDA7LbLBS02WwG5nIlfYuA.png</url>
            <title>Stories by Mohamed Ben Ticha on Medium</title>
            <link>https://medium.com/@medbenticha?source=rss-cce4b18d0619------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 10:42:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@medbenticha/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[Dynamic Routing in RAG: Directing User Queries to the Right Vector Store with Open Source Models]]></title>
            <link>https://blog.gopenai.com/dynamic-routing-in-rag-directing-user-queries-to-the-right-vector-store-with-open-source-models-f81acc91c250?source=rss-cce4b18d0619------2</link>
            <guid isPermaLink="false">https://medium.com/p/f81acc91c250</guid>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[llama-3]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <dc:creator><![CDATA[Mohamed Ben Ticha]]></dc:creator>
            <pubDate>Thu, 26 Sep 2024 12:29:42 GMT</pubDate>
            <atom:updated>2024-09-26T13:52:03.572Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yM9uno_vFSgHn93jgLg1vA.png" /></figure><h3>Introduction</h3><p>Routing the information flow in a generative AI (GEN-AI) application based on user intent significantly enhances the accuracy and efficiency of the Retrieval-Augmented Generation (RAG) pipeline. In RAG-based systems, data users interact with can be varied, coming from multiple sources, existing in different formats, or even requiring distribution across different vector stores according to their topics. These complexities pose challenges to ensuring that user queries are matched with the most relevant data.</p><p>To address these challenges, a routing mechanism becomes crucial. A router serves as an additional layer positioned just before the RAG pipeline. Its primary function is to analyze and classify the user’s intent based on their query and then direct it to the most appropriate data source or vector store. By intelligently directing queries, routers help optimize the retrieval process, reduce noise from irrelevant data, and ensure that the generated responses are contextually accurate and relevant. This results in a more streamlined and effective interaction, ultimately enhancing the overall user experience in GEN-AI applications.</p><h3>Different types of routers</h3><p>Routers can generally be divided into two main categories: logical routers, which follow predefined logic without considering user intent, and natural language routers. Natural language routers can be further classified into two types:</p><ul><li><strong>Agentic Routing: </strong>This approach utilizes a large language model (LLM) to classify user queries based on intent by prompting the model to categorize each input.</li><li><strong>Semantic Routing: </strong>This method applies semantic similarity to identify the most relevant route for a given query.</li></ul><p>In this article, we will demonstrate how to implement a semantic router in code. We’ll use an example with three routes, each corresponding to a different vector store, and show how to route user queries to the appropriate store based on their intent.</p><h3>Semantic Routing</h3><p>n our example, we have three vector stores containing research papers on the topics of Machine Learning, Software Engineering, and Economics.</p><p>For embeddings, we’ll use the Nomic embedding model, and for the chat model, we’ll utilize Llama 3.1.</p><pre>from langchain_ollama import OllamaEmbeddings, ChatOllama<br><br>embeddings_model = OllamaEmbeddings(<br>    model=&quot;nomic-embed-text&quot;,<br>)<br><br>llm = ChatOllama(model=&quot;llama3.1&quot;)</pre><p>For our semantic router to work effectively, it’s essential to provide clear and detailed descriptions for each route. This ensures that when we apply cosine similarity to the embeddings, we capture as much relevant information as possible for accurate routing.</p><pre>ml_route = &quot;This route covers topics in machine learning, including transformer models and attention mechanisms, natural language processing with BERT, deep learning methods for scientific discovery, graph neural network methodologies and applications, and advanced object detection techniques for optimizing speed and accuracy. How do transformers and attention mechanisms work in machine learning? What advancements does BERT provide in natural language understanding? How is deep learning applied in scientific research? What are the key applications of graph neural networks? How can object detection models be optimized for speed and accuracy?&quot;<br><br>cs_route = &quot;This route covers topics in computer science, including undesirable patterns in collaborative software development, knowledge graph representation and applications, and automated detection of vulnerabilities in third-party libraries for secure software engineering. What are common problems in collective software development practices? How are knowledge graphs represented and used in AI? What techniques are available for detecting vulnerable APIs in third-party libraries? How can we improve security in software projects by managing dependencies?&quot;<br><br>eco_route = &quot;This route covers topics in economics, including algorithmic collusion and market behavior, the application of first-principles calculations and numerical methods to economic models, network theory from an economic perspective, platform-mediated market consolidation, self-organized criticality in economic and financial systems, and auction mechanisms with quantity constraints. How does algorithmic collusion affect market competition? What are the applications of numerical methods in economic stability analysis? How does network theory apply to economic systems? What is the impact of platform consolidation on market dynamics? How does the self-organized criticality paradigm explain economic fluctuations? What are the challenges in designing uniform price auctions with quantity constraints?&quot;<br><br>route_descriptions = [<br>    (&quot;ml_vs&quot;, ml_route),<br>    (&quot;cs_vs&quot;, cs_route),<br>    (&quot;eco_vs&quot;, eco_route),<br>]<br><br>route_embeddings = [(name, embeddings_model.embed_query(description)) for name, description in route_descriptions]</pre><p>Now we only need to calculate similarity scores between each query and each route, we can do so using the following lines of code:</p><pre>query = &quot;What are the advancements of BERT in natural language understanding and how do transformers contribute to machine learning?&quot;<br>query_embedding = embeddings_model.embed_query(query)<br>    <br>similarities = [(name, cosine_similarity([query_embedding], [embedding])[0][0]) for name, embedding in route_embeddings]<br><br>sorted_similarities = sorted(similarities, key=lambda x: x[1], reverse=True)</pre><p>this will give us the following list containing similarities with each route sorted in an ascending order:</p><pre>[(&#39;ml_vs&#39;, 0.8321084071094975),<br> (&#39;cs_vs&#39;, 0.5518997908764628),<br> (&#39;eco_vs&#39;, 0.4699225172882923)]</pre><p>We’re almost there, but what if we encounter a query that spans more than one topic? It’s simple — we define a threshold! If another route has a similarity score close to the most similar route, we select both routes to cover the query comprehensively.</p><p>If we put everything in one function it will look something like this:</p><pre>from sklearn.metrics.pairwise import cosine_similarity<br><br>def find_routes(query, route_embeddings, threshold=0.15):<br>    <br>    query_embedding = embeddings_model.embed_query(query)<br>    <br>    similarities = [(name, cosine_similarity([query_embedding], [embedding])[0][0]) for name, embedding in route_embeddings]<br><br>    sorted_similarities = sorted(similarities, key=lambda x: x[1], reverse=True)<br>    <br>    if not sorted_similarities:<br>        return []<br><br>    # Find the highest score<br>    highest_score = max(score for _, score in sorted_similarities)<br>    <br>    similar_routes = []<br>    <br>    # Compare each route&#39;s score with the highest score<br>    for route_name, score in sorted_similarities:<br>        if (highest_score - score) &lt; threshold:<br>            similar_routes.append((route_name, score))<br>    <br>    return sorted_similarities, similar_routes</pre><p>Let’s try on the following query that covers both computer software engineering and machine learning:</p><pre>query = &quot;How can knowledge graphs and deep learning techniques be integrated to improve automated vulnerability detection in software systems?&quot;<br>find_routes(query, route_embeddings)</pre><pre>sorted_similarities:<br>([(&#39;cs_vs&#39;, 0.7689649153131043),<br>  (&#39;ml_vs&#39;, 0.637554694832182),<br>  (&#39;eco_vs&#39;, 0.4732484277598316)]<br><br>similar_routes:<br> [(&#39;cs_vs&#39;, 0.7689649153131043), (&#39;ml_vs&#39;, 0.637554694832182)])</pre><p>Our work with semantic routing is done here! But why don’t we go a bit further and implement a full RAG chain?</p><h3>RAG chain with routing</h3><p>As mentioned in the beginning of the article we use three vector stores that contain research papers.</p><p>To add more accuracy to our RAG chain, we will employ two query translation techniques: Multi-query translation and HyDE. If you’re unfamiliar with these concepts, feel free to check out my other article, “<a href="https://medium.com/@medbenticha/hyde-a719f27f4a34">HyDE: Hypothetical Document Embeddings</a>” for more details.</p><p>These are the implementations of each one:</p><pre>from langchain.prompts import ChatPromptTemplate<br>from langchain_core.output_parsers import StrOutputParser<br><br>template = &quot;&quot;&quot;You are an AI language model assistant. Your task is to generate five <br>different versions of the given user question to retrieve relevant documents from a vector <br>database. By generating multiple perspectives on the user question, your goal is to help<br>the user overcome some of the limitations of the distance-based similarity search. <br>Provide these alternative questions separated by newlines. <br>Your answer should only contain the five versions of the user&#39;s question nothing more.<br>Original question: {question}&quot;&quot;&quot;<br>prompt_perspectives = ChatPromptTemplate.from_template(template)<br><br><br>generate_queries = (<br>    prompt_perspectives <br>    | llm <br>    | StrOutputParser() <br>    | (lambda x: x.split(&quot;\n&quot;))<br>)<br><br><br>def get_unique_union(documents: list[list]):<br>    &quot;&quot;&quot; Unique union of retrieved docs &quot;&quot;&quot;<br>    flattened_docs = [dumps(doc) for sublist in documents for doc in sublist]<br>    # Get unique documents<br>    unique_docs = list(set(flattened_docs))<br>    return [loads(doc) for doc in unique_docs]</pre><pre>def hyde(question, retriever):<br>    template = &quot;&quot;&quot;Please write a scientific paper passage to answer the question. <br>    Your answer should only contain the paper passage nothing more.<br>    Question: {question}<br>    Passage:&quot;&quot;&quot;<br>    prompt_hyde = ChatPromptTemplate.from_template(template)<br><br><br>    generate_docs_for_retrieval = (<br>        prompt_hyde | llm | StrOutputParser() <br>    )<br>    <br>    #retrieve<br>    retrieval_chain = generate_docs_for_retrieval | retriever <br>    retireved_docs = retrieval_chain.invoke({&quot;question&quot;:question})<br>    <br>    return retireved_docs</pre><p>Our RAG chain function will begin by selecting the relevant routes based on the query. Next, we will retrieve the pertinent documents from each of the chosen vector stores. Then we the only thing left to do is to feed those documents to our chat LLM.</p><pre>from langchain_chroma import Chroma<br><br>def route_rag_chain(question, method=&quot;hyde&quot;, k=5):<br>    <br>    print(&quot;Input question: &quot;, question)<br>    print(&quot;=&quot;*50)<br>    print(&quot;Selecting the most similar routes...&quot;)<br>    <br>    #sorting the routes <br>    routes_with_scores, similar_routes = find_routes(question, route_embeddings)<br>    print(&quot;Similarity scores for the query against each route:&quot;)<br>    for route_name, score in routes_with_scores:<br>        print(f&quot;Route: {route_name}, Similarity Score: {score:.4f}&quot;)<br>    print(&quot;=&quot;*50)<br>    <br>    #finding the best routes<br>    routes = [route[0] for route in similar_routes]<br>    print(&quot;Routes picked:&quot;)<br>    for route_name in routes:<br>        print(route_name)<br>    print(&quot;=&quot;*50)<br>    <br>    #loading vector stores<br>    vector_database_path = &quot;vector_databases/ml_vs&quot;<br>    ml_vs = Chroma(collection_name=&quot;ml-store&quot;,<br>                    persist_directory=vector_database_path,<br>                  embedding_function=embeddings_model)<br>    <br>    vector_database_path = &quot;vector_databases/cs_vs&quot;<br>    cs_vs = Chroma(collection_name=&quot;cs-store&quot;,<br>                    persist_directory=vector_database_path,<br>                  embedding_function=embeddings_model)<br>    <br>    vector_database_path = &quot;vector_databases/eco_vs&quot;<br>    eco_vs = Chroma(collection_name=&quot;eco-store&quot;,<br>                    persist_directory=vector_database_path,<br>                   embedding_function=embeddings_model)<br>    <br>   <br>    docs=[]<br>#retrieve ml documents<br>    if &quot;ml_vs&quot; in routes:<br>        #ml_retriever<br>        ml_retriever = ml_vs.as_retriever(search_kwargs={&quot;k&quot;: k})<br>        <br>        print(&quot;Retrieving ML documents...&quot;)<br>        if method==&quot;mqt&quot;:<br>            mqt_chain = generate_queries | ml_retriever.map() | get_unique_union<br>            ml_docs = mqt_chain.invoke({&quot;question&quot;:question})<br>        elif method==&quot;hyde&quot;:<br>            ml_docs = hyde(question, ml_retriever)<br>            <br>        for i in ml_docs:<br>            docs.append(i)    <br>    else:<br>        ml_docs=[]       <br><br>#retrieve cs documents        <br>    if &quot;cs_vs&quot; in routes:<br>        <br>        #cs_retriever<br>        cs_retriever = cs_vs.as_retriever(search_kwargs={&quot;k&quot;: k})<br>        <br>        print(&quot;Retrieving CS documents...&quot;)<br>        if method==&quot;mqt&quot;:<br>            mqt_chain = generate_queries | cs_retriever.map() | get_unique_union<br>            cs_docs = mqt_chain.invoke({&quot;question&quot;:question})<br>        elif method==&quot;hyde&quot;:<br>            cs_docs = hyde(question, cs_retriever)<br>            <br>        for i in cs_docs:<br>            docs.append(i)<br>    else:<br>        cs_docs=[]<br>#retrieve eco documents<br>    if &quot;eco_vs&quot; in routes:<br>        <br>        #eco_retriever   <br>        eco_retriever = eco_vs.as_retriever(search_kwargs={&quot;k&quot;: k})<br>        print(&quot;Retrieving ECO documents...&quot;)<br>        if method==&quot;mqt&quot;:<br>            mqt_chain = generate_queries | eco_retriever.map() | get_unique_union<br>            eco_docs = mqt_chain.invoke({&quot;question&quot;:question})<br>        elif method==&quot;hyde&quot;:<br>            eco_docs=hyde(question, eco_retriever)<br>        <br>        for i in eco_docs:<br>            docs.append(i)<br>    else:<br>        eco_docs=[]<br>#generating the response<br><br>    # RAG prompt<br>    template = &quot;&quot;&quot;Answer the following question based on this context:<br><br>                {context}<br><br>                Question: {question}<br>                <br>                dont mention anything about the provided context in your answer<br>                &quot;&quot;&quot;<br>    <br>    prompt = ChatPromptTemplate.from_template(template)<br>    <br>    print(&quot;Generating response...&quot;)<br>    chain = (<br>        prompt<br>        | llm<br>        | StrOutputParser()<br>            )<br>    response = chain.invoke({&quot;context&quot;:docs,&quot;question&quot;:question})<br>    print(&quot;DONE.&quot;)<br><br>        <br>    return response</pre><p>Let’s test our chain on the previous query:</p><pre>query = &quot;How can knowledge graphs and deep learning techniques be integrated to improve automated vulnerability detection in software systems?&quot;<br>response = route_rag_chain(query)</pre><pre>Input question:  How can knowledge graphs and deep learning techniques be integrated to improve automated vulnerability detection in software systems?<br>==================================================<br>Selecting the most similar routes...<br>Similarity scores for the query against each route:<br>Route: cs_vs, Similarity Score: 0.7690<br>Route: ml_vs, Similarity Score: 0.6376<br>Route: eco_vs, Similarity Score: 0.4732<br>==================================================<br>Routes picked:<br>cs_vs<br>ml_vs<br>==================================================<br>Retrieving ML documents...<br>Retrieving CS documents...<br>Generating response...<br>DONE.</pre><p>Response:</p><pre>Knowledge graphs and deep learning techniques can be integrated to improve <br>automated vulnerability detection in software systems by:<br><br>1. **Enhancing Feature Extraction**: Knowledge graphs can represent <br>complex relationships between software components, entities, and <br>vulnerabilities. Deep learning models can then leverage this graph-based <br>representation to extract relevant features for vulnerability detection.<br>2. **Improving Threat Modeling**: By incorporating knowledge graphs into threat<br> modeling processes, developers can visualize and analyze potential attack <br>paths, weaknesses, and vulnerabilities in a more intuitive and scalable manner.<br>3. **Predicting Vulnerability Locations**: Deep learning models trained on <br>labeled knowledge graph data can predict the locations of vulnerabilities <br>within software codebases. This helps focus security efforts on high-risk <br>areas.<br>4. **Automating Vulnerability Scoring**: By integrating deep learning with <br>knowledge graphs, developers can create more accurate and efficient <br>vulnerability scoring systems that take into account various factors such as <br>exploitability, impact, and temporal relevance.<br>5. **Facilitating Collaborative Bug Fixing**: Knowledge graphs can be used to <br>visualize the relationships between bugs, vulnerabilities, and patches. Deep <br>learning models can then help identify the most relevant fixes for a given set <br>of vulnerabilities.<br><br>By integrating knowledge graphs with deep learning techniques, developers can <br>create more effective and automated vulnerability detection systems that <br>improve software security and reliability.</pre><h3>Summary</h3><p>In conclusion, the implementation of a semantic router within a Retrieval-Augmented Generation (RAG) framework significantly enhances the ability of generative AI applications to respond accurately to user queries. By intelligently routing requests based on user intent and leveraging advanced techniques like Multi-query translation and HyDE, we can optimize the retrieval process and ensure that users receive contextually relevant information from a variety of sources.</p><p>Through the example provided, we demonstrated how to effectively categorize and retrieve documents from distinct vector stores based on their content, illustrating the importance of well-defined route descriptions and similarity scoring thresholds. This approach not only streamlines the information flow but also enriches user interactions, resulting in a more satisfying and efficient experience in navigating complex datasets. As the landscape of AI continues to evolve, the integration of sophisticated routing mechanisms like the one discussed here will be crucial in enhancing the performance and accuracy of future applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f81acc91c250" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/dynamic-routing-in-rag-directing-user-queries-to-the-right-vector-store-with-open-source-models-f81acc91c250">Dynamic Routing in RAG: Directing User Queries to the Right Vector Store with Open Source Models</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HyDE]]></title>
            <link>https://blog.gopenai.com/hyde-a719f27f4a34?source=rss-cce4b18d0619------2</link>
            <guid isPermaLink="false">https://medium.com/p/a719f27f4a34</guid>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Mohamed Ben Ticha]]></dc:creator>
            <pubDate>Tue, 24 Sep 2024 16:19:18 GMT</pubDate>
            <atom:updated>2024-09-27T11:40:20.993Z</atom:updated>
            <content:encoded><![CDATA[<h3>HyDE: Hypothetical Document Embeddings</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6aTKhdih8sYS9J0QK3DyHQ.png" /></figure><h3>Introduction</h3><p>HyDE or Hypothetical Document Embedding, is a query translation technique used in RAG applications. In this approach, instead of directly retrieving documents from a knowledge base or corpus, the system first generates a hypothetical document based on the query. This hypothetical document is then used as a query to retrieve real documents that are semantically similar.</p><p>The HyDE approach helps in improving the relevance of retrieved documents by allowing the model to consider what the most relevant document might look like before searching for it. This can be particularly useful in cases where direct retrieval might miss out on relevant documents due to variations in phrasing or context.</p><h3>What is Query translation in RAG?</h3><p>Query translation in Retrieval-Augmented Generation (RAG) refers to the process of transforming a user query or input into a format that is more suitable for retrieving relevant information from a knowledge base or document store. This translation helps bridge the gap between how a user formulates their question and how the information is indexed or stored.</p><p>The goal of query translation is to maximize the chances of retrieving the most relevant information that can then be used to generate a coherent and accurate response by the language model.</p><h3>Multi-Query Translation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dVvK2McZMFwP8y-lOYghfQ.png" /></figure><p>Multiquery translation is one of the more straightforward yet effective techniques in the realm of query translation for Retrieval-Augmented Generation (RAG). It involves taking the initial user query and generating multiple reformulations or variations of the query, each from a different linguistic or conceptual perspective. The underlying idea is that by diversifying the query, we can better capture the range of relevant information that might otherwise be missed if only a single version of the query is used.</p><p>Here’s how the process works in detail:</p><ul><li><strong>Query Diversification</strong>: The original user query is reformulated into different variations by rephrasing, using synonyms, or changing focus and specificity.</li><li><strong>Multidimensional Retrieval</strong>: Each variation is used to perform separate retrieval processes, capturing a broader set of relevant information.</li><li><strong>Union of Results</strong>: The results from each query are merged, removing duplicates to create a comprehensive set of unique, relevant information.</li><li><strong>Aggregation</strong>: The retrieved information is aggregated, offering a rich and diverse dataset for the generation phase based on the different perspectives of the query.</li></ul><p>The multiquery translation technique can be especially beneficial in scenarios where user queries are ambiguous, incomplete, or multifaceted, ensuring that no critical information is left behind. By leveraging multiple query versions, this method enhances both the breadth and depth of the retrieval process, leading to more accurate and contextually relevant responses.</p><h3>HyDE</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*ReLLhbV1b8-h6LXnJOrsiQ.png" /></figure><p>The <strong>Hypothetical Document Embeddings (HyDE)</strong> technique, much like the multiquery translation method, is a query translation technique used just before the retrieval step in Retrieval-Augmented Generation (RAG) to improve the effectiveness of the user’s input query. However, instead of simply rephrasing the query, HyDE operates by generating a hypothetical document based on the query, embedding this document, and using it to guide the retrieval process. This approach enriches the retrieval phase by aligning it more closely with the likely answer space, leading to more relevant results.</p><p>Here is how HyDE work in detail:</p><ul><li><strong>Hypothetical Document Generation</strong>: The system uses an LLM to generate a plausible response based on the user’s query, simulating what an ideal answer might be.</li><li><strong>Embedding the Hypothetical Document</strong>: The generated response is converted into a vector embedding that captures the document’s semantic meaning.</li><li><strong>Guiding Retrieval with the Embedding</strong>: This embedding, instead of the original query, is used to guide retrieval, aligning results with the hypothetical answer and improving relevance.</li><li><strong>Retrieval and Refinement</strong>: The system retrieves documents similar to the hypothetical document embedding, leading to more precise and contextually relevant information.</li><li><strong>Final Output</strong>: The retrieved documents are then used to generate a response, combining the most relevant information.</li></ul><p>The HyDE technique enhances the query-to-retrieval process by enriching the query with context and structure, which helps in cases where the original query might be too short, vague, or open-ended. By generating and embedding a hypothetical answer, the system ensures that retrieval is guided toward the type of documents that contain the most relevant information, making it a powerful tool for improving recall and relevance in RAG pipelines.</p><p>Enough speaking theory for now, let’s see how can we implement it in python.</p><p>We will test this approach using a case where our vector store holds embeddings of scientific papers.</p><p>Let’s begin by defining the hypothetical document generation process. The following code sets up an LLM that generates a scientific paper passage in response to a given question:</p><pre>from langchain.prompts import ChatPromptTemplate<br>from langchain_core.output_parsers import StrOutputParser<br>from langchain_ollama import ChatOllama<br><br>template = &quot;&quot;&quot;Please write a scientific paper passage to answer the question. <br>Your answer should only contain the paper passage nothing more.<br>Question: {question}<br>Passage:&quot;&quot;&quot;<br>prompt = ChatPromptTemplate.from_template(template)<br><br><br>generate_doc = (<br>    prompt | ChatOllama(model=&quot;llama3.1&quot;, temperature=0) | StrOutputParser() <br>)</pre><p>As you can see, this setup is straightforward: we define an LLM to handle the task of generating the hypothetical document. Now, let’s test it:</p><pre>query = &quot;What are the advancements of BERT in natural language understanding and how do transformers contribute to machine learning?&quot;<br>generate_docs_for_retrieval.invoke(query)</pre><p>This generates the following passage:</p><pre>&quot;&quot;&quot;The Bidirectional Encoder Representations from Transformers (BERT) model <br>has revolutionized the field of natural language understanding by achieving <br>state-of-the-art results on a wide range of tasks, including question <br>answering, sentiment analysis, and text classification. The key advancements <br>of BERT lie in its ability to leverage contextual information through <br>bidirectional encoding and pre-training on large-scale corpora. Specifically, <br>BERT&#39;s use of multi-layer bidirectional transformers enables the model to <br>capture complex linguistic relationships between words, such as syntax and <br>semantics, which are essential for understanding natural language. <br>Furthermore, the transformer architecture employed by BERT has contributed <br>significantly to machine learning by providing a more efficient and <br>parallelizable framework for processing sequential data, such as text. <br>The self-attention mechanism in transformers allows the model to weigh <br>the importance of different input elements relative to each other, <br>rather than relying on fixed positional encodings or recurrent neural <br>networks (RNNs). This has led to significant improvements in model performance <br>and efficiency, making it possible to train large-scale language models like <br>BERT that can generalize well across a wide range of tasks.&quot;&quot;&quot;</pre><p>The next step is to define the retriever to use the generated document for retrieval. To combine everything into a single function, we can write the following:</p><pre>def hyde(question, retriever):<br>    template = &quot;&quot;&quot;Please write a scientific paper passage to answer the question. <br>    Your answer should only contain the paper passage nothing more.<br>    Question: {question}<br>    Passage:&quot;&quot;&quot;<br>    prompt_hyde = ChatPromptTemplate.from_template(template)<br><br><br>    generate_docs_for_retrieval = (<br>        prompt_hyde | ChatOllama(model=&quot;llama3.1&quot;, temperature=0) | StrOutputParser() <br>    )<br>    <br>    #retrieve<br>    retrieval_chain = generate_docs_for_retrieval | retriever <br>    retireved_docs = retrieval_chain.invoke({&quot;question&quot;:question})<br>    <br>    return retireved_docs</pre><p>This function seamlessly integrates hypothetical document generation and retrieval based on the generated document.</p><h3>Summary</h3><p>In conclusion, the HyDE technique offers a powerful enhancement to query translation in Retrieval-Augmented Generation (RAG) pipelines. By generating a hypothetical document and embedding it for retrieval, HyDE improves the accuracy and relevance of retrieved documents, particularly in cases where the user’s query may be ambiguous or insufficiently detailed. This method, combined with a robust retrieval process, ensures that the system captures a wider array of contextually appropriate information, making it a highly effective tool for tasks like scientific paper retrieval.</p><p>With a straightforward Python implementation using LLMs, we demonstrated how to apply HyDE to real-world scenarios, showing its potential to enhance RAG applications, especially in complex domains such as scientific research.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a719f27f4a34" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/hyde-a719f27f4a34">HyDE</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Knowledge Graph based RAG : Transforming the ai-arxiv-chunks dataset into a knowledge graph]]></title>
            <link>https://blog.gopenai.com/knowledge-graph-based-rag-transforming-the-ai-arxiv-chunks-dataset-into-a-knowledge-graph-c38cb252b204?source=rss-cce4b18d0619------2</link>
            <guid isPermaLink="false">https://medium.com/p/c38cb252b204</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[neo4j]]></category>
            <category><![CDATA[knowledge-graph]]></category>
            <dc:creator><![CDATA[Mohamed Ben Ticha]]></dc:creator>
            <pubDate>Mon, 26 Aug 2024 18:35:14 GMT</pubDate>
            <atom:updated>2024-08-28T12:55:04.873Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Knowledge Graph based RAG : Transforming the ai-arxiv-chunks dataset into a knowledge graph</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TTfgbzsvDrH4N21AwsA_yg.png" /></figure><h3><strong>INTRODUCTION</strong></h3><p>Every machine learning enthusiast must’ve used or at least heard of <a href="https://arxiv.org/">arXiv</a> — a free, open-access repository that hosts a vast collection of scholarly research papers across various fields. The wealth of knowledge within arXiv is immense, making it a go-to resource for researchers, academics, and developers alike. However, the challenge lies not only in accessing this information but in effectively organizing and utilizing it, particularly when dealing with large-scale datasets.</p><p>In this article, we will focus on transforming the ai-arxiv-chunks dataset, meticulously compiled by <a href="https://jamescalam.medium.com/">James Briggs</a>, into a structured knowledge graph. This transformation will enable more efficient retrieval and utilization of information within the dataset, paving the way for advanced applications like Retrieval-Augmented Generation (RAG) pipelines.</p><p>RAG is a cutting-edge approach that enhances language models by integrating external knowledge sources, enabling more informed and contextually relevant responses. However, when this external knowledge is structured as a graph, the system can leverage the rich interconnections between concepts, authors, and papers, leading to even more precise and insightful results.</p><p>By the end of this article, you’ll gain insights into how to transform a textual dataset into a graph-based knowledge structure and how to integrate this into a RAG pipeline, pushing the boundaries of what’s possible with AI and machine learning.</p><h3>RAG vs GraphRAG</h3><p>Retrieval Augmented Generation (RAG) can be defined as a process to enhance the output of a large language model by giving him access to external knowledge sources.</p><h4><strong>How does RAG work ?</strong></h4><p>In a RAG pipeline you will usually start by splitting your data into smaller chunks (refer to this <a href="https://medium.com/gopenai/mastering-text-splitting-chunking-techniques-b95dad5b5a7b">article</a> to know more about chunking), then storing them in a vector store. After you have your vector store populated you can use it for retrieving the appropriate documents based on the similarity with the user’s input query. Therefor, you can feed those documents to your llm to give him the context in which it needs to respond.</p><h4><strong>Difference between RAG and GraphRAG</strong></h4><p>In the other hand, <strong>GraphRAG </strong>can be defined as an advanced RAG that uses knowledge graphs to enhance generation. In a knowledge graph, you can store entities and the relations between them, allowing for more insights and context when retrieving information.</p><h3>The ai-arxiv-chunks dataset</h3><p>You can check the original dataset used in this article via this <a href="https://huggingface.co/datasets/jamescalam/ai-arxiv-chunked/viewer/default/train?p=1">link</a>.</p><p>Let’s start by loading the dataset :</p><pre>from datasets import load_dataset<br><br>data = load_dataset(&quot;jamescalam/ai-arxiv-chunked&quot;, split=&quot;train&quot;)<br>data</pre><pre>Dataset({<br>    features: [&#39;doi&#39;, &#39;chunk-id&#39;, &#39;chunk&#39;, &#39;id&#39;, &#39;title&#39;, &#39;summary&#39;, &#39;source&#39;, &#39;authors&#39;, &#39;categories&#39;, &#39;comment&#39;, &#39;journal_ref&#39;, &#39;primary_category&#39;, &#39;published&#39;, &#39;updated&#39;, &#39;references&#39;],<br>    num_rows: 41584<br>})</pre><p>Since we will not need all the columns in the original dataset, let’s perform a simple mapping transformation to keep only relevant info:</p><pre>data = data.map(lambda x: {<br>    &quot;id&quot;: f&#39;{x[&quot;id&quot;]}-{x[&quot;chunk-id&quot;]}&#39;,<br>    &quot;text&quot;: x[&quot;chunk&quot;],<br>    &quot;metadata&quot;: {<br>        &quot;title&quot;: x[&quot;title&quot;],<br>        &quot;url&quot;: x[&quot;source&quot;],<br>        &quot;primary_category&quot;: x[&quot;primary_category&quot;],<br>        &quot;published&quot;: x[&quot;published&quot;],<br>        &quot;updated&quot;: x[&quot;updated&quot;],<br>        &quot;authors&quot;:x[&quot;authors&quot;]<br>    }<br>})<br># drop uneeded columns<br>data = data.remove_columns([<br>    &quot;title&quot;, &quot;summary&quot;, &quot;source&quot;,<br>    &quot;authors&quot;, &quot;categories&quot;, &quot;comment&quot;,<br>    &quot;journal_ref&quot;, &quot;primary_category&quot;,<br>    &quot;published&quot;, &quot;updated&quot;, &quot;references&quot;,<br>    &quot;doi&quot;, &quot;chunk-id&quot;,<br>    &quot;chunk&quot;<br>])</pre><p>Now the rows of the dataset will look something like this</p><pre>{&#39;id&#39;: &#39;1910.01108-0&#39;,<br> &#39;text&#39;: &#39;DistilBERT, a distilled version of BERT: smaller,\nfaster, <br>cheaper and lighter, ... model is cheaper to pre-train and we demonstrate its&#39;,<br> &#39;metadata&#39;: {&#39;authors&#39;: [&#39;Victor Sanh&#39;,<br>   &#39;Lysandre Debut&#39;,<br>   &#39;Julien Chaumond&#39;,<br>   &#39;Thomas Wolf&#39;],<br>  &#39;primary_category&#39;: &#39;cs.CL&#39;,<br>  &#39;published&#39;: &#39;20191002&#39;,<br>  &#39;title&#39;: &#39;DistilBERT, a distilled version of BERT: smaller, faster, cheaper and lighter&#39;,<br>  &#39;updated&#39;: &#39;20200301&#39;,<br>  &#39;url&#39;: &#39;http://arxiv.org/pdf/1910.01108&#39;}}</pre><h3>The Knowledge Graph</h3><p>The next step is to determine the key entities and relationships we want to represent in our graph. For simplicity ,in this tutorial, I’ve chosen to include the following entities in our graph:</p><ul><li><strong>AUTHOR</strong>: Represents the name of the author.</li><li><strong>ARTICLE</strong>: Contains the title of the paper along with some metadata.</li><li><strong>CHUNK</strong>: Represents sections of the article.</li><li><strong>CATEGORY</strong>: Denotes the primary category of the paper.</li></ul><p>For the relationships between these entities, we can establish the following connections:</p><ul><li><strong>AUTHOR</strong> -[AUTHORED]-&gt; <strong>ARTICLE</strong></li><li><strong>ARTICLE</strong> -[IN_CATEGORY]-&gt; <strong>CATEGORY</strong></li><li><strong>CHUNK</strong> -[IN_ARTICLE]-&gt; <strong>ARTICLE</strong></li><li><strong>CHUNK</strong> -[NEXT]-&gt; <strong>CHUNK</strong></li></ul><p>Later in the article, we’ll delve deeper into the <strong>NEXT</strong> relationship and explore how it can enhance the generation process.</p><p>Our final graph structure will resemble the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ivt1Efrq6Mfq5Gt8ruyKrA.png" /><figcaption>Graph structure</figcaption></figure><h3>Creating and populating the graph</h3><p>In this tutorial, we will use neo4j as the graph database management system, so just go ahead and create a neo4j account and create an instance to connect to.</p><h4>Connecting to the graph</h4><p>Fortunately for us langchain has an integration of neo4j, we can connect to our graph using the following one line of code:</p><pre>from langchain_community.graphs import Neo4jGraph<br>graph=Neo4jGraph(<br>    url=NEO4J_URI,<br>    username=NEO4J_USERNAME,<br>    password=NEO4J_PASSWORD,<br>)</pre><p>You can get the url, username and password once you connect to the free instance that neo4j offer.</p><h4>Cypher query language</h4><p>Cypher is neo4j’s graph query language that lets you retrieve and write data into the graph. It can be considered like SQL but for graphs, so if you are familiar with SQL it should be easy to get, but no worries, even if you’re not, the queries we will use are simple and will be explained.</p><h4>Creating the nodes</h4><p>In order to create a new node in the graph we can use either the <strong>CREATE </strong>or the<strong> MERGE </strong>clauses. The difference between them is that the <strong>MERGE</strong> clause is used to either match an existing node or create a new one if it doesn’t already exist, while the <strong>CREATE</strong> clause will create the node even if it exists. In our case we will use the MERGE clause since it ensures us that we avoid duplicates.</p><p>To create an AUTHOR and a CATEGORY node for example we can use the following queries :</p><pre>query = &quot;&quot;&quot; <br>        MERGE (n:AUTHOR {name: $name})<br>        &quot;&quot;&quot;<br>graph.query(query, params={&#39;name&#39; : author_name})<br><br>query = &quot;&quot;&quot; <br>        MERGE (c:CATEGORY {category: category}) <br>        &quot;&quot;&quot;<br>graph.query(query, params={&#39;category&#39; : category})</pre><p>Similar queries will be used to create ARTICLE and CHUNK nodes, the only difference that we will pass more parameters.</p><p>We can use the following function to create and populate the graph nodes :</p><pre>from tqdm import tqdm<br><br>#create and populate the graph nodes<br>def create_nodes(data, start=0, end=len(data)):<br>    &quot;&quot;&quot;<br>    Creates and populates nodes in a graph database for authors, categories, articles, and chunks.<br>    <br>    Parameters:<br>    - data: dict<br>        A dictionary containing data about authors, categories, articles, and text chunks.<br>    - start: int, optional<br>        The starting index in the data from which we start populating nodes.<br>    - end: int, optional<br>        The ending index in the data.<br>    &quot;&quot;&quot;<br>        <br>    eyedee = data[&#39;id&#39;][0].split(&#39;-&#39;)[0]<br>    print(&quot;creating authors nodes&quot;)<br>    for i in tqdm(range(start, end)):<br>        #ensure that we don&#39;t go over the same author more than once<br>        if eyedee==data[&#39;id&#39;][i].split(&#39;-&#39;)[0] and i!=0 :<br>            pass<br>        else :<br>            eyedee=data[&#39;id&#39;][i].split(&#39;-&#39;)[0]<br>            query = &quot;&quot;&quot;<br>            UNWIND $names AS name<br>            MERGE (n:AUTHOR {name: name})<br>            &quot;&quot;&quot;<br>            graph.query(query, params={&quot;names&quot;: data[&#39;metadata&#39;][i][&#39;authors&#39;]})        <br>    print(&quot;=&quot;*50)<br>    <br>    eyedee = data[&#39;id&#39;][0].split(&#39;-&#39;)[0]<br>    print(&quot;creating categories nodes&quot;)<br>    for i in tqdm(range(start, end)):<br>        #ensure that we don&#39;t go over the same category more than once<br>        if eyedee==data[&#39;id&#39;][i].split(&#39;-&#39;)[0] and i!=0 :<br>             pass<br>        else:<br>            eyedee=data[&#39;id&#39;][i].split(&#39;-&#39;)[0]<br>            query = &quot;&quot;&quot;<br>            UNWIND $categories AS category<br>            MERGE (c:CATEGORY {category: category})  <br>            &quot;&quot;&quot;<br><br>            graph.query(query, params={&quot;categories&quot;: data[&#39;metadata&#39;][i][&#39;primary_category&#39;]})<br>    print(&quot;=&quot;*50)<br>    <br>    eyedee = data[&#39;id&#39;][0]<br>    print(&quot;creating articles nodes&quot;)<br>    for i in tqdm(range(start, end)):<br>        #ensure that we don&#39;t go over the same article more than once<br>        if eyedee==data[&#39;id&#39;][i].split(&#39;-&#39;)[0] and i!=0 :<br>             pass<br>        else:<br>            eyedee=data[&#39;id&#39;][i].split(&#39;-&#39;)[0]<br>            query = &quot;&quot;&quot;<br>            UNWIND $titles AS title <br>            UNWIND $ids AS id<br>            UNWIND $sources AS source<br>            UNWIND $published AS published<br>            UNWIND $updated AS updated<br>            MERGE (t:ARTICLE {title: title, id: id, source: source, published: published, updated:updated})  <br>            &quot;&quot;&quot;<br><br>            graph.query(query, params={&quot;titles&quot;: data[&#39;metadata&#39;][i][&#39;title&#39;], &quot;ids&quot;: data[&#39;id&#39;][i].split(&#39;-&#39;)[0], &quot;sources&quot;: data[&#39;metadata&#39;][i][&#39;url&#39;], &quot;published&quot;: data[&#39;metadata&#39;][i][&#39;published&#39;],&quot;updated&quot;: data[&#39;metadata&#39;][i][&#39;updated&#39;]})<br>    print(&quot;=&quot;*50)<br>    <br>    print(&quot;creating chunks nodes&quot;)<br>    for i in tqdm(range(start, end)):<br>        query = &quot;&quot;&quot;<br>        UNWIND $texts AS text <br>        UNWIND $ids AS id<br>        MERGE (c:CHUNK {text: text, id: id})  <br>        &quot;&quot;&quot;<br><br>        graph.query(query, params={&quot;texts&quot;: data[&#39;text&#39;][i], &quot;ids&quot;: data[&#39;id&#39;][i]})<br>    print(&quot;=&quot;*50)</pre><h4>Creating the relations between nodes</h4><p>Let’s start by creating the AUTHORED relation, the following query can be used to do so:</p><pre> query = &quot;&quot;&quot;<br>            UNWIND $authors as author<br>            MATCH (a:AUTHOR{name: author}), (t:ARTICLE{title: $title})<br>            MERGE (a)-[r:AUTHORED]-&gt;(t)<br>         &quot;&quot;&quot;<br>graph.query(query, params={&quot;authors&quot;: authors, &quot;title&quot;: article})  </pre><p>Let’s break this query down :</p><ul><li><strong><em>UNWIND $authors as author</em></strong> : this clause takes a list of author names provided by the <strong>$authors</strong> parameter and processes each name individually, referring to each one as <strong>author</strong>.</li><li><strong><em>MATCH (a:AUTHOR{name: author}), (t:ARTICLE{title: $title})</em></strong> : The <strong><em>MATCH</em></strong> clause is used to find nodes that already exist in the graph. In this query, for example <strong><em>(a:AUTHOR{name: author}) </em></strong>searches for an <strong>AUTHOR</strong> node where the <strong>name</strong> property matches the current author value from the <strong>UNWIND</strong> operation.</li><li><strong><em>MERGE (a)-[r:AUTHORED]-&gt;(t) </em></strong>: The <strong>MERGE</strong> clause here is used to create a relationship between the <strong>AUTHOR</strong> and <strong>ARTICLE</strong> nodes if it doesn&#39;t already exist.</li></ul><p>Similar queries are used for creating IN_ARTICLE and IN_CATEGORY relations.</p><p>Now for the NEXT relation we will use a query to processes all <strong>CHUNK</strong> nodes, group them by their corresponding article, order them sequentially based on their position in the article, and then creates <strong>NEXT</strong> relationships between each chunk and the following one. This effectively links chunks within the same article in the order they appear, allowing for the traversal of chunks in sequence.</p><pre>    query = &quot;&quot;&quot;<br>    MATCH (c:CHUNK)<br>    WITH c, SPLIT(c.id, &quot;-&quot;)[0] AS articleId, TOINTEGER(SPLIT(c.id, &quot;-&quot;)[1]) AS chunkOrder<br>    ORDER BY articleId, chunkOrder<br>    WITH articleId, collect(c) AS chunks<br>    UNWIND RANGE(0, size(chunks)-2) AS i<br>    WITH chunks[i] AS currentChunk, chunks[i+1] AS nextChunk<br>    MERGE (currentChunk)-[:NEXT]-&gt;(nextChunk)<br><br>    &quot;&quot;&quot;<br><br>    graph.query(query)</pre><p>We can use this function to create all the relationships between our nodes in the graph :</p><pre>def create_relations(data,start=0, end=len(data)) :<br>    &quot;&quot;&quot;<br>    Creates and populates relationships between nodes in a graph database, including:<br>    - AUTHORED: Between authors and articles.<br>    - IN_CATEGORY: Between articles and categories.<br>    - IN_ARTICLE: Between text chunks and their respective articles.<br>    - NEXT: Between sequential text chunks within the same article.<br>    - Sets &#39;first&#39; and &#39;last&#39; flags on chunks to indicate their position within an article.<br>    <br>    Parameters:<br>    - data: dict<br>        A dictionary containing data about authors, categories, articles, and text chunks.<br>    - start: int, optional<br>        The starting index in the data from which we start creating the relations.<br>    - end: int, optional<br>        The ending index in the data .<br>    &quot;&quot;&quot;<br>    <br>    eyedee = data[&#39;id&#39;][0].split(&#39;-&#39;)[0]<br>    print(&quot;creating AUTHORED relation&quot;)<br>    for i in tqdm(range(start, end)):<br>        if eyedee==data[&#39;id&#39;][i].split(&#39;-&#39;)[0] and i!=0 :<br>            pass<br>        else :<br>            eyedee=data[&#39;id&#39;][i].split(&#39;-&#39;)[0]<br>            article=data[&#39;metadata&#39;][i][&#39;title&#39;]<br>            authors=data[&#39;metadata&#39;][i][&#39;authors&#39;]<br>            query = &quot;&quot;&quot;<br>            UNWIND $authors as author<br>            MATCH (a:AUTHOR{name: author}), (t:ARTICLE{title: $title})<br>            MERGE (a)-[r:AUTHORED]-&gt;(t)<br>            &quot;&quot;&quot;<br>            graph.query(query, params={&quot;authors&quot;: authors, &quot;title&quot;: article})    <br>    print(&quot;=&quot;*50)<br>    <br>    eyedee = data[&#39;id&#39;][0].split(&#39;-&#39;)[0]<br>    print(&quot;creating IN_CATEGORY relation&quot;)<br>    for i in tqdm(range(start, end)):<br>        if eyedee==data[&#39;id&#39;][i].split(&#39;-&#39;)[0] and i!=0 :<br>            pass<br>        else :<br>            eyedee=data[&#39;id&#39;][i].split(&#39;-&#39;)[0]<br>            article=data[&#39;metadata&#39;][i][&#39;title&#39;]<br>            category=data[&#39;metadata&#39;][i][&#39;primary_category&#39;]<br>            query = &quot;&quot;&quot;<br>            MATCH (c:CATEGORY{category: $category}), (t:ARTICLE{title: $title})<br>            MERGE (t)-[r:IN_CATEGORY]-&gt;(c)<br>            &quot;&quot;&quot;<br>            graph.query(query, params={&quot;category&quot;: category, &quot;title&quot;: article})    <br>    print(&quot;=&quot;*50)<br>    <br>    print(&quot;creating IN_ARTICLE relation&quot;)<br>    query = &quot;&quot;&quot;<br>    MATCH (c:CHUNK)<br>    WITH c, SPLIT(c.id, &quot;-&quot;)[0] AS articleId<br>    MATCH (a:ARTICLE {id: articleId})<br>    MERGE (c)-[:IN_ARTICLE]-&gt;(a)<br>    &quot;&quot;&quot;<br><br>    graph.query(query)<br>    print(&quot;=&quot;*50)<br>    <br>    print(&quot;creating NEXT relation&quot;)<br>    query = &quot;&quot;&quot;<br>    MATCH (c:CHUNK)<br>    WITH c, SPLIT(c.id, &quot;-&quot;)[0] AS articleId, TOINTEGER(SPLIT(c.id, &quot;-&quot;)[1]) AS chunkOrder<br>    ORDER BY articleId, chunkOrder<br>    WITH articleId, collect(c) AS chunks<br>    UNWIND RANGE(0, size(chunks)-2) AS i<br>    WITH chunks[i] AS currentChunk, chunks[i+1] AS nextChunk<br>    MERGE (currentChunk)-[:NEXT]-&gt;(nextChunk)<br><br>    &quot;&quot;&quot;</pre><p>Now the graph is finally complete! Here is an overview of it in neo4j :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*Hsk4M8PKIATVoNbmBFPOXA.png" /><figcaption>Graph overview</figcaption></figure><h3>Creating the RAG pipeline</h3><p>There is still only one step before we can be able to retrieve from our graph data base, that’s right, we need to create a vector index and the embeddings of each chunk in order to be able to perform similarity search.</p><h4>Creating the vector index</h4><p>The following query will be used to create our chunks_vector index :</p><pre>#query to create the vector index<br>graph.query(&quot;&quot;&quot;<br>         CREATE VECTOR INDEX `chunks_vector` IF NOT EXISTS<br>          FOR (c:CHUNK) ON (c.textEmbedding) <br>          OPTIONS { indexConfig: {<br>            `vector.dimensions`: 1536,<br>            `vector.similarity_function`: &#39;cosine&#39;    <br>         }}<br>&quot;&quot;&quot;)</pre><ul><li><strong>CREATE VECTOR INDEX `chunks_vector` IF NOT EXISTS :</strong> This part of the query creates a vector index named chunks_vector, and ensures that the index is only created if it doesn&#39;t already exist, preventing errors or duplicate indices.</li><li><strong>FOR (c:CHUNK) :</strong> This specifies that the index is being created for nodes labeled CHUNK, which are referred to as c.</li><li><strong>ON (c.textEmbedding) :<em> </em></strong>This indicates that the index will be applied to the <strong><em>textEmbedding</em></strong> property of the CHUNK nodes. The <strong><em>textEmbedding</em></strong> is typically a vector representation of the chunk&#39;s text content.</li><li><strong>`vector.dimensions`: 1536 :</strong> Specifies that the vectors stored in the <strong><em>textEmbedding</em> </strong>property have 1536 dimensions. This is a common dimensionality for embeddings produced by certain models, like OpenAI&#39;s embeddings (the one we will be using in our case).</li><li><strong>`vector.similarity_function`: ‘cosine’ : </strong>Specifies that the similarity function used for this index will be the cosine similarity.</li></ul><h4>Embedding the chunks texts</h4><p>For embedding the text of each chunk we will use OpenAI, our cypher query will look something like this :</p><pre>graph.query(&quot;&quot;&quot;<br>        MATCH (chunk:CHUNK) <br>        WHERE chunk.textEmbedding IS NULL<br>        WITH chunk, genai.vector.encode(<br>            chunk.text, <br>            &quot;OpenAI&quot;, <br>            { token: $openAiApiKey }<br>        ) AS vector<br>        CALL db.create.setNodeVectorProperty(chunk, &quot;textEmbedding&quot;, vector)<br>        &quot;&quot;&quot;, <br>        params={&quot;openAiApiKey&quot;: OPENAI_API_KEY})</pre><p>Lets explain what is hapening here :</p><ul><li>We first match all the chunks in the graph that have the textEmbedding proprety set to NULL</li><li>Then we provide the text we want to encode to our<strong><em> genai.vector.encode</em></strong> function, along with the model and the OpenAI api key to generate our text embeddings.</li><li>Finally we just assign the vector values to the textEmbedding proprety of that chunk node.</li></ul><p>Now we can check our final graph schema</p><pre>graph.refresh_schema()<br>print(graph.schema)</pre><p>It should look something like this</p><pre>Node properties:<br>AUTHOR {name: STRING}<br>CATEGORY {category: STRING}<br>ARTICLE {source: STRING, published: STRING, id: STRING, title: STRING, updated: STRING}<br>CHUNK {source: STRING, id: STRING, text: STRING, textEmbedding: LIST, last: BOOLEAN, first: BOOLEAN}<br>Relationship properties:<br><br>The relationships:<br>(:AUTHOR)-[:AUTHORED]-&gt;(:ARTICLE)<br>(:ARTICLE)-[:IN_CATEGORY]-&gt;(:CATEGORY)<br>(:CHUNK)-[:IN_ARTICLE]-&gt;(:ARTICLE)<br>(:CHUNK)-[:NEXT]-&gt;(:CHUNK)</pre><p>We can finally start chatting and retrieving from our graph!</p><h4>Retrieving relevant documents from the knowledge graph</h4><p>We can perform retrieval by using the following cypher query</p><pre>question = &quot;can you explain why we would want to do rlhf?&quot;<br><br>#retieving documents<br>kg.query(&quot;&quot;&quot;<br>    WITH genai.vector.encode(<br>        $question, <br>        &quot;OpenAI&quot;, <br>        {<br>          token: $openAiApiKey<br>        }) AS question_embedding<br>    CALL db.index.vector.queryNodes(<br>        &#39;chunks_vector&#39;, <br>        $top_k, <br>        question_embedding<br>        ) YIELD node AS chunk, score<br>    RETURN chunk.source, chunk.text, score<br>    &quot;&quot;&quot;, <br>    params={&quot;openAiApiKey&quot;:OPENAI_API_KEY,<br>            &quot;question&quot;: question,<br>            &quot;top_k&quot;: 5<br>            })</pre><ul><li>First we get the embeddings of the question using the same function from earlier</li><li>Then by providing those embeddings to the <strong><em>db.index.vector.queryNodes</em></strong> function along with the vector index name and how many documents we want to retrieve</li><li>This function will give us back list of chunks nodes and the similarity score with our input query.</li></ul><h4>Setting up a QA chain</h4><p>Remember the NEXT relation we discussed earlier? This relation can significantly enhance our LLM’s generation by providing richer context. Instead of simply feeding the retrieved documents directly into the LLM, we can leverage the NEXT relation to gather consecutive chunks — essentially creating a sliding window of context. This approach offers a more cohesive flow of information, giving the LLM a better foundation to generate accurate and relevant responses.</p><p>We first define the query to retrieve the window of chunks</p><pre>retrieval_query_window = &quot;&quot;&quot;<br>MATCH window=<br>    (:CHUNK)-[:NEXT*0..1]-&gt;(node)-[:NEXT*0..1]-&gt;(:CHUNK)<br>WITH node, score, window as longestWindow <br>  ORDER BY length(window) DESC LIMIT 1<br>WITH nodes(longestWindow) as chunkList, node, score<br>  UNWIND chunkList as chunkRows<br>WITH collect(chunkRows.text) as textList, node, score<br>RETURN apoc.text.join(textList, &quot; \n &quot;) as text,<br>    score,<br>    node {.source} AS metadata<br>&quot;&quot;&quot;</pre><p>This query identifies the longest sequence of CHUNK nodes surrounding a given node, collects the text from these chunks, and returns the combined text along with the node&#39;s score and metadata.</p><p>Now using this query we can extend the vector store definition to accept a Cypher query. The Cypher query takes the results of the vector similarity search and then modifies them in some way. So we can define a window retrieval query to get consecutive chunks</p><pre>from langchain_community.vectorstores import Neo4jVector<br>from langchain.chains import RetrievalQAWithSourcesChain<br>from langchain_openai import ChatOpenAI<br><br>import textwrap<br><br>VECTOR_INDEX_NAME = &#39;chunks_vector&#39;<br>VECTOR_NODE_LABEL = &#39;CHUNK&#39;<br>VECTOR_SOURCE_PROPERTY = &#39;text&#39;<br>VECTOR_EMBEDDING_PROPERTY = &#39;textEmbedding&#39;<br><br>llm = ChatOpenAI(model=&quot;gpt-4o&quot;,temperature=0)<br><br>#Set up a QA chain that will use the window retrieval query<br>vector_store_window = Neo4jVector.from_existing_graph(<br>    embedding=OpenAIEmbeddings(),<br>    url=NEO4J_URI,<br>    username=NEO4J_USERNAME,<br>    password=NEO4J_PASSWORD,<br>    index_name=VECTOR_INDEX_NAME,<br>    node_label=VECTOR_NODE_LABEL,<br>    text_node_properties=[VECTOR_SOURCE_PROPERTY],<br>    embedding_node_property=VECTOR_EMBEDDING_PROPERTY,<br>    retrieval_query=retrieval_query_window,<br>)<br><br># Create a retriever from the vector store<br>retriever_window = vector_store_window.as_retriever()<br><br># Create a chatbot Question &amp; Answer chain from the retriever<br>chain_window = RetrievalQAWithSourcesChain.from_chain_type(<br>    llm,<br>    chain_type=&quot;stuff&quot;, <br>    retriever=retriever_window<br>)</pre><p>Phewh!! Let’s finally ask some questions :</p><pre>question = &quot;can you explain why we would want to do rlhf?&quot;<br><br>answer = chain_window.invoke(question)<br>print(textwrap.fill(answer[&quot;answer&quot;]))</pre><pre>RLHF (Reinforcement Learning from Human Feedback) is pursued to fine-<br>tune Large Language Models (LLMs) and significantly enhance their<br>performance. This method allows models to be iteratively aligned with<br>human expectations and preferences by incorporating feedback from<br>human users. It has been shown to address issues related to<br>factuality, toxicity, and helpfulness that cannot be resolved merely<br>by scaling up LLMs. The approach has been successfully applied across<br>various tasks, demonstrating its effectiveness in improving model<br>outputs and ensuring they are more useful and engaging.</pre><p>Wait a minute, we are not done here. The most fun part is about to start!</p><h4>Chat with graph</h4><p>There is another way we can to exploit this knowledge graph. We can instruct an LLM to translate the user’s input query to cypher query and then retrieve data from the graph based on that.</p><p>Here is how we can do it in code .</p><p>First we define our system prompt:</p><pre>from langchain.prompts.prompt import PromptTemplate<br><br>CYPHER_GENERATION_TEMPLATE = &quot;&quot;&quot;Task: Generate Cypher statement to query a graph database.<br>Instructions:<br>Use only the provided relationship types and properties in the schema.<br>Do not use any other relationship types or properties that are not provided.<br>Schema:<br>{schema}<br>Note: Do not include any explanations or apologies in your responses.<br>Do not respond to any questions that might ask anything else than for you to construct a Cypher statement.<br>Do not include any text except the generated Cypher statement.<br>Examples: Here are a few examples of generated Cypher statements for particular questions:<br><br># Who authored the article titled &quot;Graph Databases 101&quot;?<br>MATCH (author:AUTHOR)-[:AUTHORED]-&gt;(article:ARTICLE)<br>    WHERE article.title = &#39;Graph Databases 101&#39;<br>RETURN author.name<br><br># What are the categories for the article with ID &#39;12345&#39;?<br>MATCH (article:ARTICLE)-[:IN_CATEGORY]-&gt;(category:CATEGORY)<br>    WHERE article.id = &#39;12345&#39;<br>RETURN category.category<br><br># What are the next chunks following the chunk with ID &#39;chunk-001&#39;?<br>MATCH (chunk:CHUNK)-[:NEXT]-&gt;(nextChunk:CHUNK)<br>    WHERE chunk.id = &#39;chunk-001&#39;<br>RETURN nextChunk.text<br><br>The question is:<br>{question}&quot;&quot;&quot;<br><br>CYPHER_GENERATION_PROMPT = PromptTemplate(<br>    input_variables=[&quot;schema&quot;, &quot;question&quot;], <br>    template=CYPHER_GENERATION_TEMPLATE<br>)</pre><p>Now we only need to import langchain’s GraphCypherQAChain to do the hard work for us :</p><pre>from langchain.chains import GraphCypherQAChain<br><br>cypherChain = GraphCypherQAChain.from_llm(<br>    llm,<br>    graph=graph,<br>    verbose=True,<br>    cypher_prompt=CYPHER_GENERATION_PROMPT,<br>)<br><br>def prettyCypherChain(question: str) -&gt; str:<br>    response = cypherChain.run(question)<br>    print(textwrap.fill(response, 60))</pre><p>We can for example ask about the authors of a certain article</p><pre>prettyCypherChain(&quot;Who authored the article titled Text and Patterns: For Effective Chain of Thought, It Takes Two to Tango?&quot;)<br></pre><pre>&gt; Entering new GraphCypherQAChain chain...<br>Generated Cypher:<br>cypher<br>MATCH (author:AUTHOR)-[:AUTHORED]-&gt;(article:ARTICLE)<br>    WHERE article.title = &#39;Text and Patterns: For Effective Chain of Thought, It Takes Two to Tango&#39;<br>RETURN author.name<br><br>Full Context:<br>[{&#39;author.name&#39;: &#39;Aman Madaan&#39;}, {&#39;author.name&#39;: &#39;Amir Yazdanbakhsh&#39;}]<br><br>&gt; Finished chain.<br>Aman Madaan, Amir Yazdanbakhsh authored the article titled<br>Text and Patterns: For Effective Chain of Thought, It Takes<br>Two to Tango.</pre><p>As you can see, our chain translated the user’s query into a cypher query, executed it on the graph, and the gave back the response based on the result.</p><p>Here is another example</p><pre>prettyCypherChain(&quot;give me three articles names that belong to the stat.ML category &quot;)</pre><pre>&gt; Entering new GraphCypherQAChain chain...<br>Generated Cypher:<br>MATCH (article:ARTICLE)-[:IN_CATEGORY]-&gt;(category:CATEGORY)<br>    WHERE category.category = &#39;stat.ML&#39;<br>RETURN article.title<br>LIMIT 3<br>Full Context:<br>[{&#39;article.title&#39;: &#39;Mitigating Statistical Bias within Differentially Private Synthetic Data&#39;}, {&#39;article.title&#39;: &#39;Partitioned Variational Inference: A unified framework encompassing federated and continual learning&#39;}, {&#39;article.title&#39;: &#39;UMAP: Uniform Manifold Approximation and Projection for Dimension Reduction&#39;}]<br><br>&gt; Finished chain.<br>Mitigating Statistical Bias within Differentially Private<br>Synthetic Data, Partitioned Variational Inference: A unified<br>framework encompassing federated and continual learning,<br>UMAP: Uniform Manifold Approximation and Projection for<br>Dimension Reduction</pre><h3>Conclusion</h3><p>In conclusion, transforming the <strong>ai-arxiv-chunks</strong> dataset into a structured knowledge graph offers a powerful way to harness and explore the wealth of information contained within scholarly research papers. By leveraging the capabilities of <strong>GraphRAG</strong>, this approach not only enhances traditional <strong>RAG</strong> pipelines but also allows for deeper insights through the rich interconnections captured in the graph.</p><p>With entities like authors, articles, and categories mapped out, and relationships like <strong>AUTHORED</strong> and <strong>NEXT</strong> defined, the knowledge graph becomes a dynamic tool for advanced retrieval and generation tasks.</p><p>Integrating such a graph with cutting-edge techniques like vector embeddings and similarity search further pushes the boundaries of what’s possible with AI and machine learning, making it easier to access, analyze, and generate knowledge from large-scale datasets.</p><p>This transformation highlights the growing importance of knowledge graphs in AI-driven research and development, setting the stage for even more innovative applications in the future.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c38cb252b204" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/knowledge-graph-based-rag-transforming-the-ai-arxiv-chunks-dataset-into-a-knowledge-graph-c38cb252b204">Knowledge Graph based RAG : Transforming the ai-arxiv-chunks dataset into a knowledge graph</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Text Splitting & Chunking Techniques]]></title>
            <link>https://blog.gopenai.com/mastering-text-splitting-chunking-techniques-b95dad5b5a7b?source=rss-cce4b18d0619------2</link>
            <guid isPermaLink="false">https://medium.com/p/b95dad5b5a7b</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[langchain]]></category>
            <dc:creator><![CDATA[Mohamed Ben Ticha]]></dc:creator>
            <pubDate>Mon, 12 Aug 2024 12:30:26 GMT</pubDate>
            <atom:updated>2024-08-19T12:31:16.027Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*nWKzY99GFTiskgPsO0H8TQ.png" /></figure><h3>Introduction</h3><p>In the rapidly evolving field of natural language processing (NLP), text splitting has emerged as a critical component in the design and implementation of retrieval-augmented generation (RAG) pipelines. As data volumes grow and the complexity of language models increases, effective text splitting techniques become essential for managing and processing vast amounts of textual information. Text splitting involves dividing large documents or corpora into smaller, more manageable segments, facilitating more efficient retrieval, processing, and generation of relevant information.</p><p>In a RAG pipeline, where the goal is to enhance the generation of responses by retrieving and integrating relevant external information, proper text splitting ensures that these segments are contextually meaningful and operationally efficient. By breaking down text into coherent chunks, systems can perform more accurate retrievals, reduce computational load, and improve the overall quality of generated outputs.</p><p>There are mainly 5 types of text splitting that will help you squeeze out more performance from your LLM application which we will be exploring in this article, but what about some theory first ?</p><h3>Theory</h3><p>Before diving into more details about the different types of text splitting let’s first discover the theory behind text splitting. Why split text in the first place ? Why not pass the whole document to the LLM ? Passing the document as a whole entity to the LLM could be the best and simplest solution if the next two limitations did not exist :</p><p>1- First of all, large language models have a limited context length, which is basically the upper bound of the amount of data you can pass in one shot, so if you pass a complete document to a large language model it may surpass that upper bound and therefore the application won’t be able to process it.</p><p>2- The second reason, which is not less important than the first one, is related to the signalto-noise (SNR) ratio in the data. In other words, if the SNR increases your application will perform better, thus removing information that is not helpful to your task is in fact beneficial. So text splitting into chunks is like pruning your data to make it optimum for your task and your large language model. Okay now we are ready to go through the types of text splitting.</p><h3><strong>1- Character Text Splitting</strong></h3><p>This the simplest and most basic one, it simply splits your text based on characters. It splits your text into chunks with the size that you specify regardless of their content or form. Note that this type of text splitting is not recommended to use in any application, but it is a good starting point to get familiar with the basics. This how you can implement it in code using langchain:</p><pre>from langchain.text_splitter import CharacterTextSplitter<br>text_splitter = CharacterTextSplitter(<br> chunk_size=20,<br> chunk_overlap=0,<br> strip_whitespace=False,<br> separator=&quot;&quot;<br>)<br>text = &quot;This is the text we will split into chunks. It will serve as an example text to demonstrate the character splitter functionality.&quot;<br>text_splitter.create_documents([text])</pre><p>The chunk_overlap parameter here determines how many characters from the end of one chunk are repeated at the beginning of the next chunk.</p><p>The results of this code snippet will look something like this:</p><pre>[Document(page_content=&#39;This is the text we &#39;),<br> Document(page_content=&#39;will split into chun&#39;),<br> Document(page_content=&#39;ks. It will serve as&#39;),<br> Document(page_content=&#39; an example text to &#39;),<br> Document(page_content=&#39;demonstrate the char&#39;),<br> Document(page_content=&#39;acter splitter funct&#39;),<br> Document(page_content=&#39;ionality.&#39;)]</pre><p>The separator parameter defines the character or sequence of characters that the text will be split on. For example if we’d like to use “It” as a separator here the result will be the following:</p><pre>[Document(page_content=&#39;This is the text we will split into chunks. &#39;),<br> Document(page_content=&#39; will serve as an example text to demonstrate the character splitter functionality.&#39;)]</pre><p>P.S : You may notice here that the chunks have uneven sizes, that is because the separator overwrites the chunk_size parameter.</p><p>It is quite noticeable this method is not optimal since there is incomplete information in some of the chunks. While this can be solved in our case by playing with the chunk_size parameter, it will not be the same in a real case scenario.</p><h3>2- Recursive Character Text Splitting</h3><p>The problem with Character Text Splitting is that we don’t really take into account the structure of a document, we just split based on a fixed size. Well, that’s why this method exists: Recursive Character Text Splitting breaks down a text into smaller chunks by recursively trying different separators, starting with larger sections (like paragraphs or sentences) and moving to smaller ones (like words or characters). This approach ensures that chunks are as large as possible without exceeding a specified size, while keeping the text meaningfully intact by avoiding splits in the middle of important content.</p><p>Let’s see how it is implemented in code :</p><pre>from langchain_text_splitters import RecursiveCharacterTextSplitter<br><br>text_splitter = RecursiveCharacterTextSplitter(<br>    chunk_size=200,<br>    chunk_overlap=0,<br>    separators=[&quot;\n\n&quot;, &quot;\n&quot;, &quot; &quot;, &quot;&quot;] #this the default value<br>)<br><br>text = &quot;&quot;&quot; Artificial intelligence (AI) is rapidly transforming industries around the world.<br>           From healthcare to finance, AI systems are being deployed to improve efficiency, reduce costs, and enhance decision-making.<br>           The potential of AI is vast, and its applications are only beginning to be realized.<br>           For instance, in the healthcare sector, AI can assist in diagnosing diseases, personalizing treatment plans, and even predicting patient outcomes.<br>           Meanwhile, in finance, AI algorithms are being used to detect fraudulent transactions, automate trading, and<br>           provide personalized financial advice. As AI technology continues to evolve, it will undoubtedly play an even<br>           greater role in shaping the future of various industries. However, the rapid advancement of AI also raises<br>           important ethical questions, such as the impact on jobs, privacy concerns, and the potential for biased decision-making.&quot;&quot;&quot;<br><br><br>text_splitter.create_documents([text])</pre><pre>[Document(page_content=&#39;Artificial intelligence (AI) is rapidly transforming industries around the world.&#39;),<br> Document(page_content=&#39;From healthcare to finance, AI systems are being deployed to improve efficiency, reduce costs, and enhance decision-making.&#39;),<br> Document(page_content=&#39;The potential of AI is vast, and its applications are only beginning to be realized.&#39;),<br> Document(page_content=&#39;For instance, in the healthcare sector, AI can assist in diagnosing diseases, personalizing treatment plans, and even predicting patient outcomes.&#39;),<br> Document(page_content=&#39;Meanwhile, in finance, AI algorithms are being used to detect fraudulent transactions, automate trading, and&#39;),<br> Document(page_content=&#39;provide personalized financial advice. As AI technology continues to evolve, it will undoubtedly play an even&#39;),<br> Document(page_content=&#39;greater role in shaping the future of various industries. However, the rapid advancement of AI also raises&#39;),<br> Document(page_content=&#39;important ethical questions, such as the impact on jobs, privacy concerns, and the potential for biased decision-making.&#39;)]</pre><p>Notice how we have many chunks that end with “.”, it means it is and end of a sentence. That’s a lot better than ending up with incomplete words isn’t it ?</p><h3>3- Document Based Splitting</h3><p>The fist two methods of splitting that we saw work on textual data, but what if we have python code ? HTML script ? or Markdown ? It would be better to deal with those more specifically than dealing with text documents.</p><p>In this section we will see how to deal with a python code, but you can check the whole list in <a href="https://python.langchain.com/v0.1/docs/modules/data_connection/document_transformers/">langchain’s official documentation</a>.</p><p>For python scripts you can simply use PythonCodeTextSplitter since it is designed specifically for splitting Python source code, respecting function and class boundaries.</p><pre>from langchain.text_splitter import PythonCodeTextSplitter<br><br>code = &quot;&quot;&quot;<br>class Person:<br>    def __init__(self, name, age):<br>        self.name = name<br>        self.age = age<br><br>    def greet(self):<br>        print(f&quot;Hello, my name is {self.name} and I am {self.age} years old.&quot;)<br><br>class Employee(Person):<br>    def __init__(self, name, age, position):<br>        super().__init__(name, age)<br>        self.position = position<br><br>    def work(self):<br>        print(f&quot;{self.name} is working as a {self.position}.&quot;)<br><br>def main():<br>    p = Person(&quot;Alice&quot;, 30)<br>    p.greet()<br><br>    e = Employee(&quot;Bob&quot;, 40, &quot;Engineer&quot;)<br>    e.greet()<br>    e.work()<br><br>if __name__ == &quot;__main__&quot;:<br>    main()<br>&quot;&quot;&quot;<br><br>text_splitter = PythonCodeTextSplitter(<br>    chunk_size=250,<br>    chunk_overlap=0<br>)<br><br>chunks = text_splitter.create_documents([code])</pre><pre>Chunk 1:<br>class Person:<br>    def __init__(self, name, age):<br>        self.name = name<br>        self.age = age<br><br>    def greet(self):<br>        print(f&quot;Hello, my name is {self.name} and I am {self.age} years old.&quot;)<br><br>Chunk 2:<br>class Employee(Person):<br>    def __init__(self, name, age, position):<br>        super().__init__(name, age)<br>        self.position = position<br><br>    def work(self):<br>        print(f&quot;{self.name} is working as a {self.position}.&quot;)<br><br>Chunk 3:<br>def main():<br>    p = Person(&quot;Alice&quot;, 30)<br>    p.greet()<br><br>    e = Employee(&quot;Bob&quot;, 40, &quot;Engineer&quot;)<br>    e.greet()<br>    e.work()<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><h3>4- Semantic Text Splitting</h3><p>Embedding a sentence can help represent its semantic meaning, so instead of splitting a text based on a fixed “chunk_size” it would be a lot better splitting it based on semantic meaning of its sentences. This is exactly what SemanticChunker is for, it splits text based on semantic similarity by comparing embeddings of different texts and infer the relationship between chunks.</p><p>Like the other types of splitting langchain made it simple to implement this splitting technique :</p><pre>from langchain_experimental.text_splitter import SemanticChunker<br>from langchain_openai.embeddings import OpenAIEmbeddings<br><br>text_splitter = SemanticChunker(OpenAIEmbeddings())<br><br>text = &quot;The text to split goes here&quot;<br><br>docs = text_splitter.create_documents([text])<br>print(docs[0].page_content)</pre><p>As mentioned in <a href="https://python.langchain.com/v0.1/docs/modules/data_connection/document_transformers/semantic-chunker/">langchain’s documentation</a> “this splits into sentences, then groups into groups of 3 sentences, and then merges one that are similar in the embedding space.”</p><h3>5- Agentic Text Splitting</h3><p>This method might be the most effective one, it consists of prompting a large language model to split the text into chunks. By leveraging the model’s understanding of context and content, it can divide the text in a way that preserves coherence and meaning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*LseSjnFxvPBruZLWLRkmqQ.png" /></figure><p>This agentic approach ensures that the chunks are not only appropriately sized but also contextually relevant, which is crucial for maintaining the integrity of the information. Additionally, this technique can adapt to different types of texts, making it versatile for various applications.</p><h3>Conclusion</h3><p>In conclusion, effective text splitting and chunking are pivotal in optimizing the performance of large language models, especially in complex NLP tasks like retrieval-augmented generation. By employing the right technique — whether it’s character-based, recursive, document-specific, semantic, or agentic — developers can significantly enhance the relevance, coherence, and efficiency of text processing. As NLP continues to evolve, mastering these techniques will be essential for building systems that can handle large-scale textual data with precision and speed, ultimately leading to more accurate and meaningful outcomes in various applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b95dad5b5a7b" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/mastering-text-splitting-chunking-techniques-b95dad5b5a7b">Mastering Text Splitting &amp; Chunking Techniques</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>