<?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 Sushmitha on Medium]]></title>
        <description><![CDATA[Stories by Sushmitha on Medium]]></description>
        <link>https://medium.com/@sushmithabhanu24?source=rss-4050e369ea27------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*rYoF-8kFdCjny8cRfJMQTw.jpeg</url>
            <title>Stories by Sushmitha on Medium</title>
            <link>https://medium.com/@sushmithabhanu24?source=rss-4050e369ea27------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 14:58:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sushmithabhanu24/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[Retrieval in LangChain: Part 4— Retrievers]]></title>
            <link>https://sushmithabhanu24.medium.com/retrieval-in-langchain-part-4-retrievers-4dd9036bb8d9?source=rss-4050e369ea27------2</link>
            <guid isPermaLink="false">https://medium.com/p/4dd9036bb8d9</guid>
            <dc:creator><![CDATA[Sushmitha]]></dc:creator>
            <pubDate>Tue, 09 Apr 2024 16:30:23 GMT</pubDate>
            <atom:updated>2024-04-09T16:30:23.559Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*UxrLbvAMs0sEcYdW" /><figcaption>Photo by <a href="https://unsplash.com/@michael75">Michael</a> on <a href="https://unsplash.com/">Unsplash</a></figcaption></figure><p>Who doesn&#39;t love retriever puppies ❤ but we are gonna talk about Retrievers in LangChain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/0*j883FjJJX7eQPL9k.jpeg" /></figure><h3>What are Retrievers?</h3><p>Retrievers are designed to retrieve (extract) specific information from a given corpus. They <strong><em>fetch </em></strong>(like our furry friend) relevant linguistic elements based on a user query. LangChain provides a user-friendly interface that helps us return documents given a query that is more general than a vector store.</p><p>We already saw how we can retrieve information using vector store retrievers like <em>FAISS</em> and <em>ChromaDB</em> that utilize MMR and Similarity Score Threshold to extract the relevant documents. Let’s learn about a few more types of Retrievers.</p><h3><strong>MultiQuery Retriever:</strong></h3><p>What if we want to pass more than one query and extract all the relevant information for all of the queries simultaneously? This way we are efficiently using the computational resources. The <strong><em>MultiQueryRetriever </em></strong>automates the prompt tuning process by generating multiple queries for a given user query, retrieving relevant documents for each of the queries, and putting together all of them to get a more comprehensive collection of documents.</p><pre>from langchain.retrievers.multi_query import MultiQueryRetriever<br>mq_retriever = MultiQueryRetriever.from_llm(retriever=retriever, llm=chat)</pre><pre># Set logging for the queries<br><br>import logging<br>logging.basicConfig()<br>logging.getLogger(&#39;langchain.retrievers.multi_query&#39;).setLevel(logging.INFO)</pre><pre>#This will return a list of queries along with the relevant documents<br>mq_retriever.get_relevant_documents(query=query)</pre><h3>Contextual Compression:</h3><p>In many scenarios, along with relevant information irrelevant information also gets retrieved from the documents which might distract the LLM from the relevant context and take up space as well. To tackle this problem, <strong><em>DocumentCompressor</em> </strong>can be used on top of the retrieved documents. What it does is compress the documents with the relevant context rather than returning the retrieved documents as it is. This way we can pass more information to the LLM.</p><pre># Document compressor<br><br>from langchain.retrievers.document_compressors import LLMChainExtractor<br><br>compressor = LLMChainExtractor.from_llm(llm=chat)</pre><p>One more useful feature that LangChain provides is <strong><em>ContextualCompressionRetriever</em></strong> which wraps both the retriever and document compressor and automates the process.</p><pre># Compression Retriever<br><br>from langchain.retrievers import ContextualCompressionRetriever<br><br>compression_retriever = ContextualCompressionRetriever(base_compressor=compressor, base_retriever=retriever)<br>matched_docs = compression_retriever.get_relevant_documents(query=query)</pre><h3><strong>Parent Document Retriever:</strong></h3><p>Often we want to have smaller chunks that better capture the context. The <strong><em>ParentDocumentRetriever </em></strong>gets the small chunks and also fetches the larger documents (larger chunks or raw documents) that hold these smaller chunks to preserve the context.</p><pre>from langchain.text_splitter import CharacterTextSplitter<br>from langchain.retrievers import ParentDocumentRetriever<br>from langchain.storage import InMemoryStore<br><br>parent_splitter = CharacterTextSplitter(separator=&quot;\n\n&quot;, chunk_size=1000, chunk_overlap=100)<br>child_splitter = CharacterTextSplitter(separator=&quot;\n&quot;, chunk_size=200, chunk_overlap=50)<br><br>store = InMemoryStore() # parent documents<br>par_doc_retriever = ParentDocumentRetriever(vectorstore=db, docstore=store, child_splitter=child_splitter, parent_splitter=parent_splitter)<br>par_doc_retriever.add_documents(docs)<br>par_doc_retriever.get_relevant_documents(query=query)</pre><h3><strong>Time-Weighted Vector Store Retriever:</strong></h3><p>This retriever uses time as a factor and assigns weight to the information. It uses a combination of semantic similarity and time decay. The information gets more based on similarity and less score as it stays longer in the store.</p><pre>semantic_similarity + (1.0 - decay_rate) ^ hours_passed</pre><pre>import faiss<br>from langchain.vectorstores import FAISS<br>from langchain.docstore import InMemoryDocstore<br>from langchain.retrievers import TimeWeightedVectorStoreRetriever<br><br>emb_size = 1024<br>index = faiss.IndexFlatL2(emb_size)<br>temp_db = FAISS(embedding_function, index, docstore=InMemoryDocstore({}), index_to_docstore_id={})<br><br>tw_retriever = TimeWeightedVectorStoreRetriever(vectorstore=temp_db, decay_rate=1/1000000, k=1)<br>tw_retriever.get_relevant_documents(query)</pre><p>The <strong><em>decay_rate </em></strong>close to 0 will keep the memory remembered for longer and <strong><em>decay_rate </em></strong>of 0 means, memories never be forgotten.</p><p>That’s all for now. Thanks for reading!</p><p><em>Reference: </em><a href="https://python.langchain.com/docs/modules/data_connection/retrievers/"><em>https://python.langchain.com/docs/modules/data_connection/retrievers/</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4dd9036bb8d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Retrieval in LangChain: Part 3— Text Embeddings and Vector Stores]]></title>
            <link>https://sushmithabhanu24.medium.com/retrieval-in-langchain-part-3-text-embeddings-and-vector-stores-f8be7fb0508a?source=rss-4050e369ea27------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8be7fb0508a</guid>
            <dc:creator><![CDATA[Sushmitha]]></dc:creator>
            <pubDate>Sat, 23 Mar 2024 17:19:04 GMT</pubDate>
            <atom:updated>2024-03-23T17:19:04.126Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*WPOhNnGTE86QiCE7" /><figcaption>Photo by <a href="https://unsplash.com/@kommumikation">Mika Baumeister</a> on <a href="https://unsplash.com/">Unsplash</a></figcaption></figure><p>Welcome to the third article of the series, where we explore Retrieval in LangChain. If you haven&#39;t checked out the previous articles from this series, here it goes <a href="https://medium.com/@sushmithabhanu24/retrieval-in-langchain-part-1-document-loaders-9bb5be0de74f">Document Loaders</a> and <a href="https://medium.com/@sushmithabhanu24/retrieval-in-langchain-part-2-text-splitters-2d8c9d595cc9">Text Splitters</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/0*6aZhV1j6nYU_bSih.jpeg" /></figure><p>Now that we know how to load the documents and chunk the text, what are we waiting for? We need to understand how to transform this textual data into numerical representations. Let’s delve into the text-embedding capabilities of LangChain in this article.</p><h3><strong>Why do we need embeddings?</strong></h3><p>Embeddings are numerical representations of texts in a multidimensional space that can be used to capture semantic meanings and contextual information and also perform information retrieval.</p><p>It is very simple to get the embeddings for multiple texts and single queries using any embedding model.</p><pre>from langchain.embeddings import OpenAIEmbeddings<br><br>embedding_function = OpenAIEmbeddings()<br><br>embedded_docs = embedding_function.embed_documents(docs) #embeds multiple texts<br>embedded_text  = embedding_function.embed_query(query_text) #embeds a single query</pre><p>OpenAI model produces vectors of dimension 1536 whereas it differs for other models.</p><p>Various embedding models perform better than the OpenAIEmbedding model such as the BGE model created by the BAAI on HuggingFace is the best open-source embedding model.</p><pre>from langchain.embeddings import HuggingFaceBgeEmbeddings<br><br>model_name = &quot;BAAI/bge-base-en-v1.5&quot;<br>model_kwargs = {&quot;device&quot;: &quot;cpu&quot;}<br>encode_kwargs = {&quot;normalize_embeddings&quot;: True}<br><br>hf = HuggingFaceBgeEmbeddings(<br>    model_name=model_name,<br>    model_kwargs=model_kwargs,<br>    encode_kwargs=encode_kwargs<br>)<br><br>embedded_docs = hf.embed_documents(docs)<br>embedded_text  = hf.embed_query(query_text)</pre><p>If you have restrictions on the hardware, go for Fake Embeddings from LangChain for any testing purposes.</p><pre>from langchain_community.embeddings import FakeEmbeddings<br>fake_embeddings = FakeEmbeddings(size=300) # Define the embedding size<br><br>fake_embedded_record = fake_embeddings.embed_query(query)<br>fake_embedded_records = fake_embeddings.embed_documents(text)</pre><p>Once you get the embeddings of your query and the text, store them and search for the similar embedded text to the embedded query to retrieve the required information. This can be done using a vector store which will store the embeddings and perform the search.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*t8CJShORfqtqy7XI.jpg" /><figcaption>Photo by LangChain</figcaption></figure><p>Let’s quickly create a vector store from scratch. Start with loading a document, performing a split to get the chunks, creating embeddings, storing the embeddings, and querying the database.</p><pre>pip install chromadb qdrant-client faiss-cpu<br><br>from langchain_community.document_loaders import WikipediaLoader<br>from langchain.text_splitter import RecursiveCharacterTextSplitter<br>from langchain.embeddings import HuggingFaceBgeEmbeddings<br>from langchain_community.vectorstores import FAISS<br><br>#Document Loading<br>loader = WikipediaLoader(query=title, load_max_docs=5)<br>documents = loader.load()<br><br>#Text splitting<br>text_splitter = RecursiveCharacterTextSplitter(chunk_size=400, chunk_overlap=100)<br>docs = text_splitter.split_documents(documents=documents)</pre><pre>#Defining the embedding function<br>model_name = &quot;BAAI/bge-large-en-v1.5&quot;<br>model_kwargs = {&#39;device&#39;: &#39;cpu&#39;}<br>encode_kwargs = {&quot;normalize_embeddings&quot;: True}<br><br>embedding_function = HuggingFaceBgeEmbeddings(<br>    model_name=model_name,<br>    model_kwargs=model_kwargs,<br>    encode_kwargs=encode_kwargs<br>)<br><br>#Creating a vector database (FAISS - in memory database)<br>db = FAISS.from_documents(<br>    docs,<br>    embedding_function<br>)<br><br>#Querying the vector database<br>matched_docs = db.similarity_search(query=query, k=5)</pre><p>The Vector DB used here is FAISS (<strong>Facebook AI Similarity Search) </strong>which is an in-memory database that doesn&#39;t store anything in the local memory whereas ChromaDB runs on your local machine</p><pre>import chromadb<br>from langchain.vectorstores import Chroma<br><br>db = Chroma.from_documents(docs, embedding_function, persist_directory=output_path)<br>laoded_db = Chroma(persist_directory=output_path, embedding_function=embedding_function)<br><br>matched_docs = db.similarity_search(<br>    query = query,<br>    k = 5<br>)</pre><p>On top of the stored vector database, we can add new information to the same by passing the new information to the vector database.</p><pre>db = Chroma.from_documents(<br>    family_docs, # The new docs that we want to add<br>    embedding_function, # Should be the same embedding function<br>    persist_directory=output_path # Existing vectorstore where we want to add the new records<br>)<br><br>matched_docs = db.similarity_search(query=query, k=5)</pre><p>We can also delete any specific information using <strong><em>db._collection.delete(ids=[]). </em></strong>The vector store can be used to create a retriever as well.</p><pre>retriever = db.as_retriever()<br>matched_docs = retriever.get_relevant_documents(query=query)</pre><p>To optimize the retrieval process, we can use the parameter <strong><em>search_type.</em></strong></p><p><strong>Maximum Marginal Relevance</strong> (MMR) optimizes for similarity to query and diversity among selected documents.</p><pre># Maximal Marginal Relevance<br><br>retriever = db.as_retriever(search_type=&#39;mmr&#39;, search_kwargs={&quot;k&quot;: 1})<br>matched_docs = retriever.get_relevant_documents(query=query)</pre><p><strong><em>similarity_score_threshold </em></strong>can be used to get the top relevant results based on a score.</p><pre>retriever = db.as_retriever(search_type=&quot;similarity_score_threshold&quot;, search_kwargs={&quot;score_threshold&quot;: 0.5})<br>matched_docs = retriever.get_relevant_documents(query=query)</pre><p>That’s all about vector stores. This is a straightforward approach to creating a vector store and retrieving relevant information. In our next article, let&#39;s deep dive into the more advanced methods of retrieval.</p><p>Thanks for reading. If you have any specific questions or need further clarification on any part of the article, feel free to ask!</p><p><strong><em>Reference:</em></strong><a href="https://python.langchain.com/docs/modules/data_connection/text_embedding/"><em>https://python.langchain.com/docs/modules/data_connection/text_embedding/</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8be7fb0508a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Retrieval in LangChain: Part 2— Text Splitters]]></title>
            <link>https://sushmithabhanu24.medium.com/retrieval-in-langchain-part-2-text-splitters-2d8c9d595cc9?source=rss-4050e369ea27------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d8c9d595cc9</guid>
            <dc:creator><![CDATA[Sushmitha]]></dc:creator>
            <pubDate>Sun, 17 Mar 2024 13:50:53 GMT</pubDate>
            <atom:updated>2024-03-17T13:50:53.918Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*971T25rnm8IVbreo" /><figcaption>Photo by <a href="https://unsplash.com/@impatrickt">Patrick Tomasso</a> on <a href="https://unsplash.com/">Unsplash</a></figcaption></figure><p>Welcome to the second article of the series, where we explore the various elements of the retrieval module of LangChain. In the first article, we learned what is RAG, its framework, how RAG works and the first step involved in the process of retrieval — <a href="https://medium.com/@sushmithabhanu24/retrieval-in-langchain-part-1-document-loaders-9bb5be0de74f"><strong><em>Document Loaders</em></strong></a><strong><em>. </em></strong>Let’s get started with the second step which is <strong>Text Splitters — <em>Slice like a pro</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kPSgqK4oCq9beeijmVRK7g.jpeg" /></figure><p>Any NLP task involving a long document might need to be preprocessed or transformed to improve the accuracy or efficiency of the task at hand. Text Splitter comes in handy when it comes to breaking down huge documents into chunks that will enable analysis at a more granular level. LangChain provides the user with various options to transform the documents by chunking them into meaningful portions and then combining the smaller chunks into larger chunks of a particular size with overlap to retain the context. So the focus will be on how the text is split and how the chunk size is measured.</p><h3><strong>Types of Text Splitters:</strong></h3><ol><li><strong>Character Text Splitter: </strong>This is the simplest method of splitting the text by characters which is computationally cheap and doesn&#39;t require the use of any NLP libraries. Here the text split is done on characters and the chunk size is measured by the number of characters.</li></ol><pre>from langchain.text_splitter import CharacterTextSplitter<br><br>text_splitter = CharacterTextSplitter(<br>    chunk_size=1000,<br>    separator=&quot;\n\n&quot;,<br>    chunk_overlap=100,<br>    length_function=len,<br>    is_separator_regex=False<br>)<br><br>texts = text_splitter.create_documents(texts)</pre><p>The parameter <strong><em>chunk_overlap </em></strong>helps in retaining the semantic context between the chunks. The metadata can also be passed along with the documents.</p><p><strong>2.</strong> <strong>NLTK Text Splitter: </strong>When we want to focus more on the nature of the context, we might end up using sentence chunking. The basic approach to sentence chunking is <strong>text.split(“.”). </strong>However, LangChain has a better approach that uses NLTK tokenizers to perform text splitting. Here the text split is done on NLTK tokens and the chunk size is measured by the number of characters.</p><pre>from langchain.text_splitters import NLTKTextSplitter<br><br>text_splitter = NLTKTextSplitter(chunk_size=1000, chunk_overlap = 100)<br><br>texts = text_splitter.split_text(text)</pre><p><strong>3. Spacy Text Splitter: </strong>Another alternative to NLTK is the spaCy tokenizer which offers a more sophisticated sentence segmentation feature that separates the texts into chunks while preserving the context in a better way. Here the text split is done on spaCy tokens and the chunk size is measured by the number of characters.</p><pre>from langchain.text_splitter import SpacyTextSplitter<br><br>text_splitter = SpaCyTextSplitter(chunk_size=1000, chunk_overlap = 100)<br><br>texts = text_splitter.split_text(text)</pre><p><strong>4. Recursive Character Text Splitter: </strong>This type of text splitter comes into the picture when the text exceeds the chunk length and there is no separator to chunk the text. This method uses a set of separators like [“\n\n”, “\n”, “ “, “”] and splits the text into smaller chunks in an iterative manner until the desired chunk is achieved. The resulting chunks will not be of the same size yet of similar sizes. Here the text split is done on the list of characters and the chunk size is measured by the number of characters.</p><pre>from langchain.text_splitter import RecursiveCharacterTextSplitter<br><br>text_splitter = RecursiveCharacterTextSplitter(<br>    separators=[&quot;\n\n&quot;, &quot;\n&quot;, &#39; &#39;, &#39;&#39;],<br>    chunk_size = 1200,<br>    chunk_overlap = 100,<br>    length_function = len_fun,<br>    is_separator_regex =False<br>)<br><br>chunk_list = text_splitter.create_documents(texts)</pre><p>Note: The split first happens at “\n\n”, if the chunk size exceeds, it will move to the next separator, if it still exceeds, it will move to the next separator which is “ “ and so on.</p><p><strong>5. Splitting on tokens: </strong>Handling token limits in language models is pivotal for seamless operations and optimal performance. It is a good practice to count the number of tokens after getting the chunks.</p><p>Tiktoken was created by OpenAI and is a fast BPE. It can be used to track the number of tokens used and better suits OpenAI models. Here the text split is done on the characters passed in and the chunk size is measured by the tiktoken tokenizer.</p><pre>pip install tiktoken</pre><pre>from langchain.text_splitter import CharacterTextSplitter<br><br>text_splitter = CharacterTextSplitter.from_tiktoken_encoder(<br>    separator=&quot;\n\n&quot;, <br>    chunk_size=1200, <br>    chunk_overlap=100, <br>    is_separator_regex=False,<br>    model_name=&#39;text-embedding-3-small&#39;,<br>    encoding_name=&#39;text-embedding-3-small&#39;, <br>)<br><br>doc_list = text_splitter.create_documents([text])<br><br>doc_list</pre><p>The <strong><em>model_name </em></strong>refers to the model used for calculating the tokens. The split text can also be converted to a list of documents.</p><pre>from langchain.docstore.document import Document<br><br>doc_list = []<br><br>for line in line_list:<br>    curr_doc = Document(page_content=line, metadata={&quot;source&quot;: filepath})<br>    doc_list.append(curr_doc)<br><br>doc_list</pre><p><strong>6. Sentence Transformers Token Text Splitter: </strong>This type is a specialized text splitter used with sentence transformer models.</p><pre>from langchain.text_splitters import SentenceTransformersTokenTextSplitter  <br><br>splitter = SentenceTransformersTokenTextSplitter(<br>    tokens_per_chunk=64,<br>    chunk_overlap=0,<br>    model_name=&#39;intfloat/e5-base-v2&#39;)<br><br><br>text_token_count = splitter.split_text(text=text)<br>print(text_token_count)</pre><p><strong>7. Code Splitter: </strong>This type lets you split the code and it comes with multiple language options like Python, java, Latex, HTML, scala, c, and a lot more.</p><pre>from langchain_text_splitters import Language, RecursiveCharacterTextSplitter<br><br>text_splitter = RecursiveCharacterTextSplitter.from_language(<br>    language = Language.PYTHON,<br>    chunk_size=50,<br>    chunk_overlap =10<br>)<br><br>text_splitter.create_documents(texts = [python_code])</pre><p>We can even find the type of separator used for the given language.</p><pre>RecursiveCharacterTextSplitter.get_separators_for_language(Language.PYTHON)</pre><p>And that’s not done there yet. Langchain has a lot of options to perform semantic chunking, token splitters for KoNLPY, Hugging Face, and more.</p><p>That’s all about text splitters. Experimenting with a range of chunk sizes will help in bringing a balance between preserving context and maintaining accuracy. Keep in mind that one solution will not work always, so get started with experimentation.</p><p>Now that we know how to chunk the text, let&#39;s see how we can embed the chunks in our next article. Thanks for reading.</p><p><strong><em>References:</em></strong></p><p>1.<a href="https://python.langchain.com/docs/modules/data_connection/document_transformers/"><em>https://python.langchain.com/docs/modules/data_connection/document_transformers/</em></a></p><p>2.<a href="https://www.pinecone.io/learn/chunking-strategies/"><em>https://www.pinecone.io/learn/chunking-strategies/</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d8c9d595cc9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Retrieval in LangChain: Part 1 — Document Loaders]]></title>
            <link>https://sushmithabhanu24.medium.com/retrieval-in-langchain-part-1-document-loaders-9bb5be0de74f?source=rss-4050e369ea27------2</link>
            <guid isPermaLink="false">https://medium.com/p/9bb5be0de74f</guid>
            <dc:creator><![CDATA[Sushmitha]]></dc:creator>
            <pubDate>Sat, 09 Mar 2024 14:20:05 GMT</pubDate>
            <atom:updated>2024-03-09T14:20:05.099Z</atom:updated>
            <content:encoded><![CDATA[<h3>Retrieval in LangChain: Part 1 — Document Loaders</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qy6lhQKG-jl1d_5qos0j2w.png" /></figure><p>In this new series, we will explore Retrieval in Langchain — Interface with application-specific data.</p><h3><strong>What is RAG?</strong></h3><p>RAG (Retrieval Augmented Generation) is a framework that can be used to improve the performance of an LLM by feeding facts from external sources to refer outside its training data to generate responses. This enables improving the reliability of the generated responses and helps in handling hallucinations. By using RAG, the LLM can connect directly to updated information sources that can provide the latest information to the user.</p><h3><strong>How does RAG work?</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*XNJymJbF87uDCFeC" /></figure><ol><li>The external data is given to the LLM and stored in the form of a vector database.</li><li>Then the user query is converted to a vector representation and matched with the vector database.</li><li>Next, the RAG model augments the user input and adds the input to the relevant retrieved content.</li><li>The augmented prompt will allow the LLM to generate accurate responses to the user queries.</li></ol><p>RAG has various components from loading the data to retrieving the relevant information. In this blog, we will explore the first component involved in the process of Retrieval which is ‘<strong><em>Document Loaders</em></strong>’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kPSgqK4oCq9beeijmVRK7g.jpeg" /></figure><p>The very first step of retrieval is to load the external information/source which can be both structured and unstructured. Langchain provides the user with various loader options like TXT, JSON, CSV, HTML, PDF, public websites, etc. Let&#39;s see how the loaders work.</p><ol><li><strong>CSV Loader:</strong></li></ol><pre>from langchain.document_loaders import CSVLoader<br><br>loader = CSVLoader(file_path=&#39;../datasets/sns_datasets/titanic.csv&#39;) # Lazy Loader<br>data = loader.load()<br><br>data</pre><pre>&gt; [Document(page_content=&#39;survived: 0\npclass: 3\nsex: male\nage: 22.0\nsibsp: 1\nparch: 0\nfare: 7.25\nembarked: S\nclass: Third\nwho: man\nadult_male: True\ndeck: \nembark_town: Southampton\nalive: no\nalone: False&#39;, metadata={&#39;source&#39;: &#39;../datasets/sns_datasets/titanic.csv&#39;, &#39;row&#39;: 0}), Document(page_content=&#39;survived: 1\npclass: 1\nsex: female\nage: 38.0\nsibsp: 1\nparch: 0\nfare: 71.2833\nembarked: C\nclass: First\nwho: woman\nadult_male: False\ndeck: C\nembark_town: Cherbourg\nalive: yes\nalone: False&#39;, metadata={&#39;source&#39;: &#39;../datasets/sns_datasets/titanic.csv&#39;, &#39;row&#39;: 1}), ...]</pre><p>The loader creates a separate document for each of the rows in the CSV.</p><pre># Getting the content of the document<br>print(data[0].page_content) <br><br># Getting the metadata<br>print(data[0].metadata) </pre><pre># content of the document<br>survived: 0<br>pclass: 3<br>sex: male<br>age: 22.0<br>sibsp: 1<br>parch: 0<br>fare: 7.25<br>embarked: S<br>class: Third<br>who: man<br>adult_male: True<br>deck: <br>embark_town: Southampton<br>alive: no<br>alone: False<br><br>#metadata information <br>&gt; {&#39;source&#39;: &#39;../datasets/sns_datasets/titanic.csv&#39;, &#39;row&#39;: 0}</pre><p>Using <em>source_column, the </em>user can mention a specific column and pass it to the loader.</p><p>2.<strong> HTML Loader:</strong></p><pre>from langchain.document_loaders import UnstructuredHTMLLoader<br>loader = UnstructuredHTMLLoader(&#39;../datasets/harry_potter_html/001.htm&#39;)<br>data = loader.load()<br>data</pre><pre>&gt; [Document(page_content=&#39;A Day of Very Low Probability\n\nBeneath the moonlight glints a tiny fragment of silver, a fraction of a line…\n\n ...</pre><p>3. <strong>Markdown Loader:</strong></p><pre>from langchain.document_loaders import UnstructuredMarkdownLoader<br><br>md_filepath = &quot;../datasets/harry_potter_md/001.md&quot;<br><br>loader = UnstructuredMarkdownLoader(file_path=md_filepath)<br>data = loader.load()<br>data</pre><pre>  &gt; [Document(page_content=&#39;A Day of Very Low Probability\n\nBeneath the moonlight glints a tiny fragment of silver ...</pre><p>4. <strong>PDF Loader:</strong></p><pre>from langchain.document_loaders import PyPDFLoader<br><br>loader = PyPDFLoader(&#39;../datasets/harry_potter_pdf/hpmor-trade-classic.pdf&#39;)<br>data = loader.load()<br>data</pre><pre>[Document(page_content=&#39;Harry Potter and the Methods of Rationality&#39;, metadata={&#39;source&#39;: &#39;../datasets/harry_potter_pdf/hpmor-trade-classic.pdf&#39;, &#39;page&#39;: 0}),<br>Document(page_content=&#39;&#39;, metadata={&#39;source&#39;: &#39;../datasets/harry_potter_pdf/hpmor-trade-classic.pdf&#39;, &#39;page&#39;: 1}), ...</pre><p>The PDF loader utilizes different sources like PyPDFium2Loader, PDFMinerLoader, PDFMinerPDFasHTMLLoader, PyMuPDFLoader, and PyPDFDirectoryLoader.</p><p>5. <strong>Wikipedia Loader:</strong></p><pre>from langchain.document_loaders import WikipediaLoader<br><br>loader = WikipediaLoader(query=&#39;India&#39;, load_max_docs=1)<br>data = loader.load()<br>data</pre><pre>&gt; [Document(page_content=&quot;India, officially the Republic of India (ISO: Bhārat Gaṇarājya), ...</pre><p>6. <strong>ArXiv Loader:</strong></p><pre>from langchain_community.document_loaders import ArxivLoader<br><br>loader = ArxivLoader(query=&#39;2201.03916&#39;, load_max_docs=1) # AutoRL paper (article ID -&gt; 2201.03916)<br>data = loader.load()<br>data</pre><pre>&gt; [Document(page_content=&#39;Journal of Artiﬁcial Intelligence Research 74 (2022) ...</pre><p>7. <strong>Youtube Loader:</strong></p><pre>from langchain.document_loaders.generic import GenericLoader<br>from langchain.document_loaders.parsers import OpenAIWhisperParser<br>from langchain.document_loaders.blob_loaders.youtube_audio import YoutubeAudioLoader<br><br>url=&quot;https://www.youtube.com/watch?v=jGwO_UgTS7I&quot;<br>save_dir=&quot;docs/youtube/&quot;<br>loader = GenericLoader(YoutubeAudioLoader([url],save_dir),<br>    OpenAIWhisperParser())<br><br>data = loader.load()<br>data[0]</pre><p>Let’s pass the retrieved information to the LLM</p><pre>from langchain_openai import ChatOpenAI<br>from langchain.globals import set_llm_cache<br>from langchain.cache import InMemoryCache<br><br><br>chat = ChatOpenAI()<br>set_llm_cache(InMemoryCache())</pre><pre># Setting up the prompt templates<br><br>from langchain.prompts.chat import ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate, AIMessagePromptTemplate<br><br>system_template = &quot;You are Peer Reviewer&quot;<br>human_template = &quot;Read the paper with the title: &#39;{title}&#39;\n\nAnd Content: {content} and critically list down all the issues in the paper&quot;<br><br>system_message_prompt = SystemMessagePromptTemplate.from_template(system_template)<br>human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)<br><br>chat_prompt = ChatPromptTemplate.from_messages(messages=[system_message_prompt, human_message_prompt])<br>prompt = chat_prompt.format_prompt(title=data[0].metadata[&#39;Title&#39;], content=data[0].page_content)<br>messages = prompt.to_messages()<br><br>response = chat(messages=messages)<br><br>print(response.content)</pre><p><strong>Creating a bot that can answer questions based on Wikipedia articles</strong></p><pre>def qna_article(topic, question):<br>    chat = ChatOpenAI(max_tokens = 500)<br>    loader = WikipediaLoader(query=topic, load_max_docs = 1)<br>    data = loader.load()<br>    first_record = data[0]<br>    page_content = first_record.page_content<br>    title = first_record.metadata[&#39;title&#39;]<br>    summary = first_record.metadata[&#39;summary&#39;]<br>    user_question = question<br><br>    human_template = &quot;Read the paper with the title: &#39;{title}&#39;\n\n And Content: {content}  and answer the questions {user_question} related to the article&quot;<br><br>    human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)<br><br>    chat_prompt = ChatPromptTemplate.from_messages([human_message_prompt])<br>    prompt = chat_prompt.format_prompt(title = title, content = summary, user_question = question)<br><br>    response = chat(messages = prompt.to_messages())<br><br>    return response.content</pre><pre>qna_article(&#39;India&#39;, &#39;How many languages are being spoken in India?&#39;)</pre><pre>&#39;India is a multilingual country with a diverse linguistic landscape. There are 22 officially recognized languages in India, as listed in the Eighth Schedule of the Indian Constitution. In addition to these official languages, there are hundreds of other languages spoken by different communities across the country.&#39;</pre><p>That&#39;s all about document loaders.</p><p>Thanks for reading.</p><p><em>Reference: </em><a href="https://python.langchain.com/docs/modules/data_connection/document_loaders/"><em>https://python.langchain.com/docs/modules/data_connection/document_loaders/</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9bb5be0de74f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying Output Parsing in LangChain: Simplifying Data Extraction — Part 2]]></title>
            <link>https://sushmithabhanu24.medium.com/demystifying-output-parsing-in-langchain-simplifying-data-extraction-part-2-d62dcb8cda1d?source=rss-4050e369ea27------2</link>
            <guid isPermaLink="false">https://medium.com/p/d62dcb8cda1d</guid>
            <dc:creator><![CDATA[Sushmitha]]></dc:creator>
            <pubDate>Thu, 07 Mar 2024 14:06:05 GMT</pubDate>
            <atom:updated>2024-03-07T14:06:05.745Z</atom:updated>
            <content:encoded><![CDATA[<h3>Demystifying Output Parsing in LangChain: Simplifying Data Extraction — Part 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jAJq0Lj1krA6XGLvIiihKA.jpeg" /></figure><p>In our previous blog, we delved into the world of output parsing — what it is, why it’s indispensable, the various types, associated challenges, benefits, implementation strategies, and ultimately, its crucial role in data interpretation. Let’s explore yet another type of output parser that holds immense promise and utility — the Pydantic Output Parser.</p><h3>Understanding Pydantic Output Parser</h3><p>Pydantic, a Python tool for data validation and parsing library, offers a robust framework for defining and validating data models. Pydantic Output Parser extends this capability to Langchain, providing a powerful mechanism for parsing and validating output data generated by Python components within the Langchain environment.</p><h3>Key Features and Benefits :</h3><p>Pydantic Output Parser brings a host of features and benefits to the table:</p><ol><li>Data Validation</li><li>Automatic Parsing</li><li>Error Handling</li><li>Customization</li></ol><p>From data validation to customization, Pydantic Output Parser provides developers with the flexibility to tailor output parsing according to their requirements.</p><h3>Implementation :</h3><p>Let’s take a look at how the traditional approach works.</p><pre>class Student:<br>    def __init__(self, name: str):<br>        self.name = name<br><br>john = Student(name=&#39;John&#39;)<br>john.name</pre><pre>&gt; &#39;John&#39;</pre><p>Even if we pass an integer, type validation is not restricted.</p><pre>jane = Student(name=1) # Taking int even after defining the name to be str<br>jane.name</pre><pre>&gt; 1</pre><pre>type(jane.name)</pre><pre>&gt; int</pre><p>Look how the Pydantic syntax works on restricting the type validation. Using the BaseModel from Pydantic to perform the same operation.</p><pre>from pydantic import BaseModel<br><br>class Student(BaseModel):<br>    name: str </pre><pre>jane = Student(name=1) <br><br># THIS WILL THROW A VALIDATION ERROR SINCE THE INPUT IS DEFINED AS A STRING</pre><pre>jane = Student(name=&#39;jane&#39;)<br>jane.name</pre><pre>&gt; &#39;jane&#39;</pre><p>Let’s implement it within LangChain.</p><pre>from langchain_core.pydantic_v1 import BaseModel, Field<br>from typing import List<br><br>class Dog(BaseModel):<br>    breed: str = Field(description=&quot;Breed of the dog&quot;)<br>    behavior: str = Field(description=&quot;Behavior of the dog&quot;)<br>    features: List[str] = Field(description=&quot;List of features of the dog&quot;)</pre><h3><strong>Defining a custom parser</strong></h3><p>Now, let’s define a custom output parser using Pydantic:</p><pre>from langchain.output_parsers import PydanticOutputParser<br><br>output_parser = PydanticOutputParser(pydantic_object=Dog)<br><br>print(output_parser.get_format_instructions())</pre><pre>The output should be formatted as a JSON instance that conforms to the JSON schema below.<br><br>As an example, for the schema {&quot;properties&quot;: {&quot;foo&quot;: {&quot;title&quot;: &quot;Foo&quot;, &quot;description&quot;: &quot;a list of strings&quot;, &quot;type&quot;: &quot;array&quot;, &quot;items&quot;: {&quot;type&quot;: &quot;string&quot;}}}, &quot;required&quot;: [&quot;foo&quot;]}<br>the object {&quot;foo&quot;: [&quot;bar&quot;, &quot;baz&quot;]} is a well-formatted instance of the schema. The object {&quot;properties&quot;: {&quot;foo&quot;: [&quot;bar&quot;, &quot;baz&quot;]}} is not well-formatted.<br><br>Here is the output schema:<br>```<br>{&quot;properties&quot;: {&quot;breed&quot;: {&quot;title&quot;: &quot;Breed&quot;, &quot;description&quot;: &quot;Breed of the dog&quot;, &quot;type&quot;: &quot;string&quot;}, &quot;behavior&quot;: {&quot;title&quot;: &quot;Behavior&quot;, &quot;description&quot;: &quot;Behavior of the dog&quot;, &quot;type&quot;: &quot;string&quot;}, &quot;features&quot;: {&quot;title&quot;: &quot;Features&quot;, &quot;description&quot;: &quot;List of features of the dog&quot;, &quot;type&quot;: &quot;array&quot;, &quot;items&quot;: {&quot;type&quot;: &quot;string&quot;}}}, &quot;required&quot;: [&quot;breed&quot;, &quot;behavior&quot;, &quot;features&quot;]}<br>```</pre><pre>human_template = &quot;{human_message}\n{format_instructions}&quot;<br>human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)<br>chat_prompt = ChatPromptTemplate.from_messages([human_message_prompt])<br>prompt = chat_prompt.format_prompt(human_message=&#39;Tell me about the most expensive car in the world&#39;,<br>                                   format_instructions=output_parser.get_format_instructions())<br><br>response = chat(messages=prompt.to_messages())<br>output = output_parser.parse(response.content)<br><br>output</pre><pre>Dog(breed=&#39;Chihuahua&#39;, behavior=&#39;Energetic and alert&#39;, features=[&#39;Small size&#39;, &#39;Large ears&#39;, &#39;Round eyes&#39;]</pre><p>Reference: <a href="https://python.langchain.com/docs/modules/model_io/output_parsers/types/pydantic">https://python.langchain.com/docs/modules/model_io/output_parsers/types/pydantic</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d62dcb8cda1d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying Output Parsing in LangChain: Simplifying Data Extraction]]></title>
            <link>https://sushmithabhanu24.medium.com/demystifying-output-parsing-in-langchain-simplifying-data-extraction-e233fb8f9b9b?source=rss-4050e369ea27------2</link>
            <guid isPermaLink="false">https://medium.com/p/e233fb8f9b9b</guid>
            <dc:creator><![CDATA[Sushmitha]]></dc:creator>
            <pubDate>Fri, 01 Mar 2024 13:02:57 GMT</pubDate>
            <atom:updated>2024-03-01T13:02:57.131Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NZtPANSJm3z1PNnErM7Euw.png" /></figure><p>In the realm of data analysis and computer science, output parsing stands as a silent hero, often overshadowed by flashy algorithms and advanced analytics techniques. Yet, its importance cannot be overstated. In this blog, we’ll delve into the world of output parsing — what it is, why it’s indispensable, the various types, associated challenges, benefits, implementation strategies, and ultimately, its crucial role in data interpretation.</p><h3>What is Output Parsing?</h3><p>Output parsing, in simple terms, refers to the process of extracting relevant information from raw data outputs generated by various systems, tools, or processes. These outputs could be in the form of log files, command line outputs, API responses, or any other unstructured data format. In LangChain, output parsing empowers developers to transform raw data into structured formats that are easier to analyze and utilize.</p><h3>Why is Output Parsing Necessary?</h3><ol><li>Extracting Insights: Cuts through noise to pinpoint relevant data for accurate analysis.</li><li>Automation: Saves time and ensures consistency by automating data extraction.</li><li>Standardization: Simplifies analysis by making outputs consistent across different sources.</li></ol><h3>Types of Output Parsing</h3><ol><li><strong>List Parser</strong>: This parser is designed to parse a comma-separated list into a Python list. It’s particularly useful when dealing with data stored in a comma-delimited format, such as CSV files or simple text inputs.</li><li><strong>DateTime Parser</strong>: This parser converts a datetime string into a Python datetime object. It’s invaluable when working with temporal data and is commonly used for tasks like data preprocessing or handling timestamps in log files.</li><li><strong>Structured Output Parser</strong>: This parser transforms structured text data into a Python dictionary based on a provided schema. It’s ideal for parsing custom schemas where data is organized in a specific format, such as log files or configuration files.</li></ol><p>Users can also define custom parsing functions in LangChain to extract information from output data according to specific requirements. These functions can be tailored to handle different types of output formats and data structures.</p><h3>What if Parser fails?</h3><p>In LangChain, when a parser encounters an error, developers have tools to handle it gracefully:</p><ol><li>Exception Handling: Use try-except blocks to catch parsing errors and execute alternative paths.</li><li>Fallback Mechanisms: Implement fallbacks to provide alternative data or default behaviors.</li><li>Logging and Reporting: Log error details to diagnose issues effectively.</li><li>User Feedback: Provide clear error messages to guide users through any issues.</li></ol><p>In short, parser failures in LangChain are managed with systematic error handling, ensuring smooth application functionality even in challenging situations.</p><h3>Conclusion</h3><p>Output parsing in LangChain is a transformative capability that empowers developers to extract, analyze, and utilize data with ease. By streamlining data extraction workflows, enhancing decision-making, and unlocking the full potential of applications, output parsing in LangChain enables developers to build more intelligent, responsive, and impactful software solutions. As we look to the future, output parsing will remain a cornerstone of data-driven development in LangChain and beyond.</p><p>GitHub: <a href="https://github.com/sushmithabg/Output-Parsing---LangChain">https://github.com/sushmithabg/Output-Parsing---LangChain</a></p><p>Reference: <a href="https://python.langchain.com/docs/modules/model_io/output_parsers/">https://python.langchain.com/docs/modules/model_io/output_parsers/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e233fb8f9b9b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring the power of Few-Shot Prompting in NLP]]></title>
            <link>https://sushmithabhanu24.medium.com/exploring-the-power-of-few-shot-prompting-in-nlp-10c0efafa410?source=rss-4050e369ea27------2</link>
            <guid isPermaLink="false">https://medium.com/p/10c0efafa410</guid>
            <dc:creator><![CDATA[Sushmitha]]></dc:creator>
            <pubDate>Sun, 25 Feb 2024 13:24:19 GMT</pubDate>
            <atom:updated>2024-02-25T13:24:19.552Z</atom:updated>
            <content:encoded><![CDATA[<p>In this rapidly evolving landscape of NLP, innovations are constantly reshaping the way we interact with data and understand it. One such innovation gaining traction is few-shot prompting, a technique that empowers models to learn from minimal examples and generalize to new tasks. In this blog, we will delve into the concept of few-shot prompting, its applications, and its potential to revolutionize NLP tasks.</p><p><strong>What is a Prompt?</strong></p><p>A prompt is a way of interaction between a human and LLM to generate the intended output. It can include a question, text, code, image, etc. The LLM takes these prompts as input and tries to provide more output based on how the prompt is framed. Prompts should be framed in such a way that gives specific instructions to the model to produce accurate and desired outputs. This way we can avoid hallucinations, ambiguity, or biased outputs.</p><p><strong>Few-Shot Prompting:</strong></p><p>Few-shot prompting involves providing a model with a prompt (in-context learning) and a few examples related to a task to steer the model for better performance. This enables the model to learn quickly and apply across various tasks.</p><p><strong>Applications:</strong></p><p>Few-shot prompting has demonstrated its efficacy on various NLP tasks including text classification, question answering, summarization, and many more.</p><p><strong>Advantages:</strong></p><p>One of the key highlights of few-shot prompting is its efficiency in utilizing limited annotated data instead of relying on large data for training. This approach facilitates rapid prototyping and deployment of NLP systems, making it ideal for industries. It also allows the model to continuously learn and adapt to improve with minimal supervision.</p><p><strong>Challenges:</strong></p><p>Though the technique offers promising opportunities, it also comes with certain challenges. One of them is overfitting especially when dealing with complex tasks or ambiguous prompts. To avoid bias or ambiguity, prompt structuring requires expertise and careful consideration.</p><p><strong>Conclusion:</strong></p><p>Few-shot prompting presents an efficient and versatile approach to tackling many NLP tasks with minimal supervision. By leveraging pre-trained models and a small number of examples, this technique offers solutions to data scarcity and rapid adaptation challenges. In short, few-shot prompting holds great promise for driving innovation and advancement in NLP.</p><p><strong>Implementation:</strong></p><pre># import the necessary libraries<br>import os<br>import warnings<br>warnings.filterwarnings(&#39;ignore&#39;)<br>import openai<br>from langchain.schema import SystemMessage, HumanMessage, AIMessage<br><br># Load the .txt file<br>with open(&#39;../openai_api_key.txt&#39;, &#39;r&#39;) as f:<br>    api_key = f.read()<br><br>os.environ[&#39;OPENAI_API_KEY&#39;] = api_key<br><br># Set the system role and user message variables<br># SystemMessage: Role assigned to the AI.<br># HumanMessage: Human request or the prompt.<br># AIMessage: AI Response as per it&#39;s role to the Human request.<br><br>def get_adjusters_response(prompt):<br>  system_message = &quot;You are a claim adjuster working for claims recovery&quot;<br>  client_dialogue1 = &quot;There has been a lot of recoveries happening lately&quot;<br>  sample_response1 = &quot;is this related to any specific line of business? can you give me examples of one or two events ? Does it involve natural calamities? We may have to look into the recent claim records&quot;<br><br>  client_dialogue2 = &quot;Claims related to property seems to be have higher rates compared to other line of businesses&quot;<br>  sample_response2 = &quot;Can you specify whether the claima are related to water damager or fire? does the claims involve any third party? are there enough details regarding the loss and contributory factors ? &quot;<br><br>  client_dialogue3 = &quot;Claims that involves theft or vandalism are usually not considered to be potential for recoveries&quot;<br>  sample_response3 = &quot;what security measures were present in such scenarios? how do you calculate the estimates incase of theft? are there any actions being taken against the perpetrator by the police after the notice ?&quot;<br><br>  messages = [<br>        SystemMessage(content=system_message),<br>        <br>        HumanMessage(content=client_dialogue1),<br>        AIMessage(sample_response1),<br>        <br>        HumanMessage(content=client_dialogue2),<br>        AIMessage(sample_response2),<br>        <br>        HumanMessage(content=client_dialogue3),<br>        AIMessage(sample_response3),<br>        <br>        HumanMessage(content=prompt)<br>    ]<br><br>  response = chat(messages=messages)<br>  return response.content<br><br><br>print(get_adjusters_response(&#39;there is a claim that involves roof damage due to water leakage from defective pipes&#39;))<br></pre><pre>Output:<br>&#39;What was the extent of the damage caused by the water leakage? Was the defect in the pipes due to wear and tear or a manufacturing defect? Have steps been taken to repair the pipes and prevent future leaks? Have you been able to determine the cause of the defect and if there is any liability on the part of the manufacturer or installer of the pipes?&#39;</pre><p>Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10c0efafa410" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>