<?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 Devang Parekh on Medium]]></title>
        <description><![CDATA[Stories by Devang Parekh on Medium]]></description>
        <link>https://medium.com/@de.marek?source=rss-481a2d15e58d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*uFApHpXSsjmy2-CaTxLdsQ.png</url>
            <title>Stories by Devang Parekh on Medium</title>
            <link>https://medium.com/@de.marek?source=rss-481a2d15e58d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 10:32:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@de.marek/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[How Uber Optimized Query Generation: Faster SQL Query Authoring with QueryGPT]]></title>
            <link>https://medium.com/@de.marek/how-uber-optimized-query-generation-faster-sql-query-authoring-with-querygpt-0ed8b35692f1?source=rss-481a2d15e58d------2</link>
            <guid isPermaLink="false">https://medium.com/p/0ed8b35692f1</guid>
            <category><![CDATA[uber]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Devang Parekh]]></dc:creator>
            <pubDate>Thu, 20 Feb 2025 16:52:02 GMT</pubDate>
            <atom:updated>2025-02-20T17:20:10.842Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IIHbR0AWnhz1lAgXV-44Ng.jpeg" /></figure><p><a href="https://notebooklm.google.com/notebook/cd39fc97-517b-45a9-a225-935f7312a688/audio">Sign in</a></p><p>Okay, so picture this you’re leading Uber’s Operations team, and you need to know how many trips got canceled in Toronto last week. Normally, you’d open your SQL editor, search through the data dictionary, figure out which tables hold trip and cancellation data, then carefully craft the SQL query. This could take you a solid 10–15 minutes longer if the schema is complex.</p><p>But what if, instead, you could just type: <em>“</em><strong><em>How many trips were canceled in Toronto last week because of snowstorm?</em></strong><em>”</em> and within seconds, receive a fully formed SQL query, ready to run?</p><p>That’s exactly what <strong>QueryGPT</strong> is designed to do, and that’s what we’re diving into in this blog.</p><h3>Why Build QueryGPT in the First Place?</h3><p>Uber processes around <strong>1.2 million interactive queries</strong> each month. And here’s the kicker roughly <strong>36%</strong> of those come from the Operations team alone. Every one of those queries takes time. Not because the users lack SQL skills, but because understanding internal data models, navigating complex schemas, and writing optimized queries is time-intensive.</p><p>Now, scale that up. If each query takes, say, <strong>10 minutes</strong> to author, that’s a staggering amount of hours spent just crafting SQL.</p><p>Let’s do a little math here.</p><h4>Calculate the number of complex queries</h4><ul><li>Total queries by operations team: <strong>432,000</strong></li><li>Percentage of complex queries: let’s say roughly ~<strong>30%</strong></li><li>Number of complex queries: <strong>0.30×432,000=129,600 complex queries</strong></li></ul><h4>Calculate the total time required to process complex queries</h4><ul><li>Time per complex query: <strong>10 minutes</strong></li><li>Total time in minutes: <strong>129,600×10=1,296,000 minutes</strong></li><li>Total Hours: <strong>1,296,000/60​=21,600 hours</strong></li></ul><h4>Calculate the number of people required</h4><ul><li>Each person works <strong>40 hours per week</strong>.</li><li>Number of weeks in a month: <strong>4 weeks</strong>.</li><li>Monthly person hours: (<strong>40 hours/week) × (4 weeks)=160 hours/month</strong></li><li>Number of people required:<strong> (21,600 hrs)/(160 hrs/person)​=135 people</strong></li></ul><p><strong>QueryGPT</strong> slashes that time down to <strong>3</strong> minutes on average, and by allocating <strong>3 </strong>minutes to each complex query, the required personnel count drops from <strong>135</strong> to ~<strong>40</strong> a <strong>reduction of around 70% in workforce</strong> demand, which is a good deal from any business perspective. (<strong><em>Nah man, AI ain’t taking anyone’s jobs!, LMAO!!</em></strong>)</p><h3>So, How Does QueryGPT Actually Work?</h3><p>It’s easy to assume that <strong>QueryGPT</strong> is just another chatbot layered over a database, but in reality, it’s a much more sophisticated system. Its goal isn’t just to <strong>understand what you’re asking </strong>it’s also about <strong>translating that natural language</strong> into highly accurate, production-ready <strong>SQL queries</strong> that work smoothly with Uber’s vast data ecosystem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FWMeLl17sZCcO1IH044-iQ.png" /><figcaption>Source: Uber Engineering — QueryGPT</figcaption></figure><p>Let’s break down how QueryGPT actually works, step by step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_k2lPBtgF1-8R865eB8HJA.jpeg" /></figure><p>At its core, <strong>QueryGPT</strong> uses the <strong>Azure OpenAI GPT-4 Turbo model</strong> with a <strong>128K token limit</strong>, enabling it to handle complex queries efficiently. It also leverages <strong>vector databases</strong> and <strong>similarity searches</strong> to ensure contextually accurate results optimized for Uber’s data infrastructure.</p><h4>1. Workspaces in QueryGPT: Tailoring Data Access for Precision</h4><p>In its current architecture, <strong>Uber</strong> introduced <strong>Workspaces</strong> curated collections of <strong>SQL samples</strong> and <strong>tables</strong> designed for specific business domains such as <strong>Ads, Mobility,</strong> and <strong>Core Services</strong>. These workspaces help narrow the focus for the <strong>Large Language Model (LLM)</strong>, significantly enhancing the <strong>relevance</strong> and <strong>accuracy</strong> of the generated queries.</p><p>To streamline the query generation process, Uber has identified common business domains and established them as <strong>System Workspaces</strong> within the backend. One of the foundational domains is <strong>Mobility</strong>, which encompasses queries related to <strong>trips, drivers, document details</strong>, and more.</p><p>For example:<br><strong><em>Write a query to find the number of trips completed by </em></strong>Mercedes<strong><em> in Montreal yesterday.</em></strong></p><p>The <strong>Mobility Workspace</strong> ensures that the system immediately targets the correct datasets, reducing the need for manual table selection and improving query accuracy.</p><p>In addition to <strong>Mobility</strong>, Uber has developed <strong>other system workspaces</strong>, covering domains like:</p><ul><li><strong>Core Services</strong></li><li><strong>Platform Engineering</strong></li><li><strong>IT</strong></li><li><strong>Ads </strong>and many more.</li></ul><p>Recognizing that predefined workspaces may not always fit every use case, Uber also integrated the ability for users to create <strong>Custom Workspaces.</strong> This feature allows users to tailor the data environment to their specific needs, ensuring maximum flexibility while maintaining the efficiency and accuracy of query generation.</p><h4>Intent Agent: Understanding User Queries with Precision</h4><p>Every incoming user prompt is first processed by the <strong>Intent Agent.</strong> The primary role of this agent is to <strong>map the user’s NL Query</strong> to one or more relevant <strong>workspaces</strong>, which are directly linked to specific <strong>SQL samples</strong> and <strong>tables</strong>.</p><p>When a user submits a query, the <strong>Intent Agent</strong> leverages a <strong>Language Model </strong>call to accurately <strong>identify the intent</strong> behind the question. Based on this analysis, it maps the query to either a predefined <strong>System Workspace</strong> (like <strong>Mobility</strong> or <strong>Ads</strong>) or a user-defined <strong>Custom Workspace.</strong> This step ensures that the query generation process is contextually aligned with the user’s goal.</p><p>For example, if a user asks:<br><strong><em>How many trips were completed by hybrid vehicles in Waterloo during peak hours last week?</em></strong></p><p>The <strong>Intent Agent</strong> identifies the <strong>Mobility</strong> domain as the relevant workspace, focusing the search on tables containing trip and cancellation data.</p><p>By effectively <strong>narrowing the search radius</strong> for the <strong>Retrieval-Augmented Generation (RAG)</strong> process, the Intent Agent improves both the <strong>efficiency</strong> and <strong>accuracy</strong> of query generation. It ensures that QueryGPT doesn’t waste resources sifting through irrelevant data, allowing the system to focus solely on the most pertinent datasets.</p><h4>Table Agent: Ensuring Accurate Table Selection</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*eul99prS5bEisMkW" /><figcaption>Source: Uber Engineering — QueryGPT</figcaption></figure><p>The <strong>Table Agent</strong> introduced in response to user feedback regarding incorrect table selection during query generation. Some users noticed that the automatically chosen tables didn’t always align with their specific data needs.</p><p>To address this, the <strong>Table Agent</strong> now selects the most relevant tables and presents them to the user for review. Users can either <strong>ACK</strong> the selection or <strong>edit the list</strong> to refine the tables used for query generation.</p><p>This added layer of user control ensures greater <strong>accuracy</strong> and <strong>flexibility</strong>, reducing errors and improving the overall reliability of the generated queries.</p><h4>Column Prune Agent: Optimizing Token Usage</h4><p>As <strong>QueryGPT</strong> scaled to a larger user base, an <strong>intermittent token size issue</strong> emerged during query generation. Despite using the <strong>OpenAI GPT-4 Turbo model</strong> with a <strong>128K token limit</strong>, certain requests still exceeded this limit, especially when involving tables with extensive schemas that consumed a significant number of tokens.</p><p>To resolve this, <strong>Uber</strong> introduced the <strong>Column Prune Agent</strong>. This agent uses an <strong>LLM call</strong> to <strong>prune irrelevant columns</strong> from the table schemas before sending them to the model. By streamlining the input data, this approach reduces <strong>token usage</strong>, minimizes <strong>latency</strong>, and optimizes <strong>costs</strong>, all while maintaining the accuracy of query generation.</p><pre>{<br>  &quot;pruned_schema&quot;: {<br>    &quot;explanation&quot;: &quot;The user&#39;s question is about the number <br>of trips completed by hybrid vehicles in Waterloo during peak hours last week.<br> The table provided is a dimension table for cities and vehicle types. <br>To answer the question, we need the &#39;name_of_city&#39; and &#39;vehicle_type&#39; columns.<br> Other columns such as &#39;is_operational&#39;, &#39;lang_code&#39;, &#39;ctry_uuid&#39;, &#39;min_score&#39;,<br> &#39;shape_val&#39;, &#39;mg_region&#39;, &#39;market&#39;, &#39;ctry_code&#39;, &#39;tz&#39;, &#39;city_id&#39;, &#39;terr_uuid&#39;,<br> &#39;timestamp&#39;, &#39;dist_unit&#39;, &#39;currency&#39;, &#39;longit&#39;, &#39;country&#39;, &#39;ctry_iso2&#39;, <br>&#39;operational&#39;, &#39;sb_region&#39;, &#39;latit&#39;, &#39;upd_epoch&#39;, &#39;ctry_iso3&#39;, &#39;plan_unit&#39;, <br>&#39;upd_timestamp&#39;, &#39;gfence_uuid&#39;, &#39;display_name&#39;, &#39;ctry_id&#39;, &#39;require_mob_ver&#39;, <br>&#39;lnch_date&#39; are not directly relevant to the question asked. However, without<br> more context on how the trips are linked to cities and vehicle types, <br>it is conservative to keep the &#39;city_id&#39; as it might be used as a foreign key <br>in another table that stores trip data.&quot;,<br>    &quot;schema&quot;: {<br>      &quot;tableName&quot;: &quot;uber.cities_vehicles&quot;,<br>      &quot;tableDescription&quot;: &quot;This dimension table stores one row per city and <br>vehicle type that Uber is operating in or has operated previously, <br>providing any of Uber&#39;s services (e.g., Transport, Food, etc.). <br>This table includes information about vehicle types and excludes cities <br>commissioned for product testing.&quot;,<br>      &quot;columns&quot;: [<br>        {<br>          &quot;name&quot;: &quot;city_id&quot;,<br>          &quot;type&quot;: &quot;BIGINT&quot;,<br>          &quot;isPartitionKey&quot;: false<br>        },<br>        {<br>          &quot;name&quot;: &quot;name_of_city&quot;,<br>          &quot;type&quot;: &quot;STRING&quot;,<br>          &quot;isPartitionKey&quot;: false<br>        },<br>        {<br>          &quot;name&quot;: &quot;vehicle_type&quot;,<br>          &quot;type&quot;: &quot;STRING&quot;,<br>          &quot;isPartitionKey&quot;: false<br>        },<br>        {<br>          &quot;name&quot;: &quot;trip_time&quot;,<br>          &quot;type&quot;: &quot;TIMESTAMP&quot;,<br>          &quot;isPartitionKey&quot;: false<br>        }<br>      ],<br>      &quot;tier&quot;: &quot;TIER_ONE&quot;,<br>      &quot;usagePercentile&quot;: 99.9<br>    }<br>  }<br>}</pre><p>The output would include a skinnier version of each schema that we needed for query generation. This change massively improved not just the token size and by extension the cost of each LLM call, but also reduced the latency since the input size was much smaller.</p><h4>Evaluation</h4><p>To measure <strong>QueryGPT’s</strong> performance and track improvements, Uber follows a <strong>standardized evaluation process</strong>. This ensures that algorithm updates enhance accuracy and efficiency while distinguishing between <strong>consistent and anomalous issues</strong>.</p><h4>Evaluation Set</h4><p>A curated set of <strong>golden question-to-SQL mappings</strong> is used for evaluation. Real user queries from <strong>QueryGPT logs</strong> are manually reviewed to verify <strong>intent, schema selection, and correct SQL output</strong>. These questions cover diverse <strong>datasets and business domains</strong>.</p><h4>Evaluation Procedure</h4><p>QueryGPT’s evaluation is conducted using two approaches:</p><ul><li><strong>Vanilla Testing</strong> — Measures baseline performance by processing a question, inferring intent, selecting datasets, and generating SQL.</li><li><strong>Decoupled Testing</strong> — Evaluates QueryGPT with <strong>human-in-the-loop</strong> adjustments, isolating specific system components from earlier processing steps.</li></ul><p>For each evaluation, key metrics are tracked:</p><ul><li><strong>Intent Accuracy</strong> — Is the assigned intent correct?</li><li><strong>Table Overlap</strong> — Do the selected tables match expected ones?</li><li><strong>Successful Run</strong> — Does the query execute without errors?</li><li><strong>Query Output</strong> — Does execution return valid results (&gt;0 records)?</li><li><strong>Query Similarity</strong> — How closely does the generated SQL match the ideal response? (LLM-based similarity score: 0 to 1)</li></ul><p><strong>Performance trends</strong> are monitored over time to detect regressions and pinpoint areas for improvement.</p><p>To conclude, <strong>QueryGPT</strong> enhances developer productivity by automating SQL generation, reducing query time, and streamlining data access for faster decision-making. While it improves efficiency and minimizes errors, challenges such as LLM variability and token limits remain areas for ongoing improvement.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0ed8b35692f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[QnA RAG for JSON + PDF with Langchain + Chroma]]></title>
            <link>https://medium.com/@de.marek/qna-rag-for-json-pdf-with-langchain-chroma-44833b9008ca?source=rss-481a2d15e58d------2</link>
            <guid isPermaLink="false">https://medium.com/p/44833b9008ca</guid>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[rags]]></category>
            <dc:creator><![CDATA[Devang Parekh]]></dc:creator>
            <pubDate>Sat, 08 Feb 2025 16:08:17 GMT</pubDate>
            <atom:updated>2025-02-08T16:28:55.735Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QHLN9Lc8-IeDGmfQlXzM4A.png" /><figcaption>developer.nvidia.com</figcaption></figure><p>Recently, I was assigned to research RAG (Retrieval-Augmented Generation) a bit to work with existing JSON and document data from our database. Specifically, our manager requested: “I want you guys to build something that can help our clients understand the system and data quickly and monetize.”</p><p>That’s when my colleague and I started researching LangChain. While I’ve been familiar with the concept, I’ve never actually worked hands-on with it before.</p><p><strong>Here are the topics we’ll cover in this blog:</strong></p><ol><li>What is RAG (Retrieval-Augmented Generation)?</li><li>Overview of Huggingface’s Open-Source Models.</li><li>What is LangChain, and its architecture?</li><li>Using ChromaDB and vectorizing documents.</li><li>Dive into implementation.</li><li>Plans include making everything distributed, async, and scalable.</li></ol><p>Retrieval-augmented generation (RAG) focuses on two main aspects:</p><p><strong>Retrieval</strong>: This involves fetching relevant information or documents from a knowledge base, database, or external service (in our case, JSON, PDFs, or other structured/unstructured data sources) in response to a query. The retrieved data provides essential context, enabling the generation of more accurate, relevant, and contextually rich responses.</p><p><strong>Generation</strong>: Once the relevant data is retrieved, it is input for a generative AI model (such as Llama) to produce an <strong>augmented</strong> and <strong>contextually accurate</strong> response. The generative model combines its language understanding with the retrieved context to create factually informed and conversationally fluent answers.</p><p>In short, if you want your model to respond based on custom context, RAG is highly helpful.</p><h3><strong>Overview of Huggingface’s Open-Source Models.</strong></h3><p>Now, if you belong to the data space, you are likely familiar with Hugging Face. Nonetheless, I will explain it to those who are not familiar.</p><p><a href="https://hf.co/">Hugging Face(HF)</a> 🤗 is a leading open-source platform for natural language processing (NLP) and machine learning. They offer a vast library of models, such as LLMs, and Transformers, enabling developers to integrate AI into applications.</p><p>Additionally, HF provides tools and a community for training, deploying, and sharing machine learning models.</p><p>Currently, HF <a href="https://huggingface.co/models">models</a> provide over 1.3 million open-source language models for a wide range of use cases. You can download <a href="https://lmstudio.ai/">LM Studio</a> to load and play with any model that fits your specific local configuration for experimentation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*asOqfBEQPxUREG896LVTiA.png" /><figcaption>hf.co/models</figcaption></figure><h3>What is LangChain, and its architecture?</h3><p><a href="https://www.langchain.com/">LangChain</a> is an open-source toolkit for Python and JavaScript (TypeScript) that simplifies building applications with large language models like GPT. It provides components to integrate LLMs with external computations and data sources, enabling developers to effortlessly add language processing capabilities and connect resources such as APIs and databases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*MwdqCmzOBVa2wrl17Tgd5g.jpeg" /></figure><h3>Key Components of LangChain</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4kEnYyR9JbTjk6e_tpLqlQ.png" /></figure><p><strong>Models/LLMs:</strong></p><ul><li><strong>Description:</strong> Core language models (e.g., GPT-4) that generate text based on prompts.</li><li><strong>Function:</strong> Serve as the foundation for understanding and generating human-like text.</li></ul><p><strong>Prompts:</strong></p><ul><li><strong>Description:</strong> Templates and strategies for crafting input queries to LLMs.</li><li><strong>Function:</strong> Optimize interactions with models to elicit desired responses by structuring questions and instructions effectively.</li></ul><p><strong>Chains:</strong></p><ul><li><strong>Description:</strong> Sequences of interconnected calls to LLMs and other utilities.</li><li><strong>Function:</strong> Enable complex workflows by chaining together multiple operations, such as data retrieval, transformation, and generation.</li></ul><p><strong>Agents:</strong></p><ul><li><strong>Description:</strong> Intelligent agents that use LLMs to decide which actions to take.</li><li><strong>Function:</strong> Allow applications to perform tasks autonomously by interpreting user intents and selecting appropriate tools or functions to execute.</li></ul><p><strong>Memory/Vector Stores:</strong></p><ul><li><strong>Description:</strong> Mechanisms to retain context and information across interactions.</li><li><strong>Function:</strong> Enhance conversational continuity and context awareness by storing previous interactions, enabling more coherent and relevant responses.</li></ul><p><strong>Tools:</strong></p><ul><li><strong>Description:</strong> External APIs, databases, or functionalities that LLMs can interact with.</li><li><strong>Function:</strong> Extend the capabilities of applications by allowing LLMs to perform actions like fetching data, executing code, or interfacing with other services.</li></ul><p><strong>Data Connectors:</strong></p><ul><li><strong>Description:</strong> Interfaces for connecting to various data sources (e.g., databases, APIs).</li><li><strong>Function:</strong> Facilitate seamless data integration, enabling applications to access and utilize diverse datasets for more informed responses.</li></ul><h3>Working with JSON.</h3><p>Now let’s dive into the code and try to implement each of the Langchain’s components, for that, you need to install the LangChain package using the command below.</p><ol><li>Firstly, initialize the virtual environment using the command below</li></ol><pre>python3 -m venv env</pre><p>2. Activate the virtual environment using below</p><pre>source ./env/bin/activate</pre><p>3. Now, install the required packages using below.</p><pre>pip install langchain langchain-chroma langchain-cli langchain-community langchain-core langchain-huggingface langchain-text-splitters</pre><ol><li><strong>langchain</strong>: A framework for developing applications powered by language models, enabling chaining of components for complex workflows.</li><li><strong>langchain-chroma</strong>: Integration of Chroma (a vector database) with LangChain for storing and querying embeddings.</li><li><strong>langchain-cli</strong>: Command-line interface tools for managing and interacting with LangChain projects.</li><li><strong>langchain-community</strong>: Community-contributed modules, tools, and integrations for extending LangChain&#39;s functionality.</li><li><strong>langchain-core</strong>: Core components and utilities of the LangChain framework, providing foundational building blocks.</li><li><strong>langchain-huggingface</strong>: Integration with Hugging Face models and datasets for use within LangChain workflows.</li><li><strong>langchain-text-splitters</strong>: Tools for splitting text into smaller chunks, useful for processing large documents in LangChain.</li></ol><h4>Now, to provide a clearer intuition about RAG, here’s the architecture:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7zj4YGAoNykaBzsbNF_klg.png" /></figure><h4>Step 1: User Query</h4><p>Everything starts when a user asks a question (Query). The system needs to find the most relevant information before answering.</p><h4>Step 2: Embedding Module — Understanding and Storing Knowledge</h4><p>The system has a large collection of documents, data files, and other text-based resources. However, raw text isn’t efficient for searching, so we convert this text into a machine-friendly format. This happens in three steps:</p><p><strong>Split and Vectorize</strong></p><ul><li>The documents are broken into smaller chunks.</li><li>Each chunk is converted into numerical representations called <strong>vectors</strong> using an <strong>embedding model</strong>.</li></ul><p><strong>Chroma Vector Database</strong></p><ul><li>All these vectorized chunks are stored in a special database called <strong>Chroma Vector</strong>.</li><li>This allows the system to quickly find the most relevant pieces of information based on a new query.</li></ul><h4>Step 3: Retrieving Relevant Information</h4><p>When a user asks a question, the system converts the query into a vector and searches for the closest matching data in the <strong>Chroma Vector database</strong>. The best-matching information is retrieved and sent forward.</p><h4>Step 4: Enhancing the Query with System Prompts and Keywords</h4><p>The retrieved information is combined with additional <strong>system prompts and keywords</strong> to improve context and accuracy.</p><h4>Step 5: Generating a Response with a Language Model</h4><p>Finally, the processed query and relevant retrieved data are passed to a <strong>Language Model (LLM)</strong>. The LLM then generates a well-informed, context-aware response.</p><h4>Step 6: Returning the Final Answer</h4><p>The response from the language model is sent back to the user, providing a much more accurate and relevant answer than a model working alone.</p><p>For simplicity, I will roughly add the important scripts and omit the boilerplate.</p><pre># Starting with importing the libraries<br>from langchain_community.embeddings import HuggingFaceEmbeddings<br>from langchain_community.vectorstores import Chroma<br>from langchain.text_splitter import CharacterTextSplitter<br>from langchain_huggingface import HuggingFaceEndpoint<br>from langchain.chains import RetrievalQA<br>from langchain_community.document_loaders import JSONLoader, PyPDFDirectoryLoader<br>from functions.loaders import load_data , truncate_text</pre><h4>1. HuggingFaceEmbeddings</h4><p>HuggingFaceEmbeddings is used to convert text into numerical representations (vectors) that can be stored and searched efficiently. These embeddings help find similar documents based on their meaning rather than exact words.</p><ul><li>We are using it <strong>sentence-transformers/all-MiniLM-L6-v2</strong> as our embedding model (<strong><em>lightweight and fast</em></strong>).</li><li>This model is lightweight yet powerful for generating embeddings that work well for retrieval tasks.</li></ul><h4>2. HuggingFaceEndpoint</h4><p>HuggingFaceEndpoint allows us to connect to Hugging Face&#39;s hosted models through their API. Instead of running a large model locally, we send queries to Hugging Face’s cloud, making it easier and more scalable.</p><ul><li>In our case, we are using <strong>mistralai/Mistral-7B-v0.1</strong> our <strong>language model</strong> to generate responses.</li><li>This is a highly capable open-weight model designed for reasoning and knowledge-intensive tasks.</li></ul><h4>Getting the Hugging Face API Key</h4><p>To use Hugging Face’s hosted models, you need an <strong>API Key</strong>:</p><ol><li>Go to <a href="http://hf.co/">Hugging Face Dashboard</a>.</li><li>Create a new token (or use an existing one).</li><li>Use this key in your code when calling HuggingFaceEndpoint.</li></ol><pre># Helper functions for loading data and truncating text to limit <br># the number of tokens.<br>def load_data(path, isDirectory, data_loader,jq_schema=&quot;.data&quot;, text_content=False):<br>    if isDirectory:<br>        loader = data_loader(path)<br>    else:<br>        if path.endswith(&quot;.json&quot;):<br>            loader = JSONLoader(<br>                file_path=path,<br>                jq_schema=jq_schema,<br>                text_content=False<br>            )<br>        else:<br>            loader = data_loader(path, jq_schema=jq_schema)<br>    <br>    return loader.load()<br><br>def truncate_text(context: str, max_tokens: int = 6500) -&gt; str:<br>    tokens = context.split() <br>    if len(tokens) &gt; max_tokens:<br>        return &quot; &quot;.join(tokens[:max_tokens])<br>    return context</pre><pre># Loading the JSON<br>docs = load_data(<br>    &quot;../data/Data.json&quot;, # Some random json.<br>    isDirectory=False,<br>    data_loader=JSONLoader,<br>    jq_schema=&quot;.data&quot;, # Fetching tha value of .data. {&quot;.data&quot;:{...data}}<br>    text_content=False<br>)# Loading the sample PDFs<br>pdf_docs = load_data(&quot;../data/pdfs/&quot;, True, PyPDFDirectoryLoader)<br><br># Combine JSON and PDF documents<br>docs.extend(pdf_docs)# Split documents into chunks<br>char_text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=100)<br>doc_texts = char_text_splitter.split_documents(docs)<br><br># Chunk overlap ensures continuity between chunks by retaining a <br># portion of the previous chunk in the next one. <br># each 1000-character chunk shares 100 characters with the next,<br># preventing loss of context in split documents.<br></pre><pre># Initialize Hugging Face embeddings<br>embedding_function = HuggingFaceEmbeddings(<br>    model_name=EMBEDDING_FUNCTION_MODEL,<br>)</pre><pre># Create vector store<br>vStore = Chroma.from_documents(doc_texts, embedding_function, persist_directory=&#39;../data/vector_store&#39;)</pre><p>And that’s almost all the code needed to assemble the RAG system. I won’t dive deep into the vector database, as it’s a whole topic for another blog (coming soon). For now, let’s look at how to run the inference.</p><pre>#* Adjust your question<br>question = &quot;Can you give me brief information about client ?&quot;<br><br>#* Retrieve and combine the context<br>retrieved_context = retriever.get_relevant_documents(question)<br>combined_context = &quot; &quot;.join([doc.page_content for doc in retrieved_context])</pre><pre>#* Truncate the context to fit within the token limit<br>truncated_context = truncate_text(combined_context)<br><br>#* Prepare the input as a string<br>input_text = f&quot;Question: {question}\n\nContext: {truncated_context}\n\nAnswer:&quot;</pre><p>Finally, invoking the Language model</p><pre>#* Invoke<br>print(&quot;\n\n\n&quot;)<br>print(&quot;-----------------------------------------------------&quot;)<br>response = llm.invoke(input_text)<br>print(&quot;AI:&quot;, response)</pre><p>Since we built more than just this, I have limited the information in this blog for better readability. In the next post, we will explore the distributed implementation of RAG with a <strong>queuing architecture</strong> (redis-queues, workers).</p><p>We’ll also discuss the <strong>ensemble</strong> approach to prevent unnecessary model invocations for smaller queries that can be handled by a simple database trigger. Additionally, we’ll cover RAG integration with Meta APIs.</p><p>Feel free to connect with me on LinkedIn at <a href="https://www.linkedin.com/in/bravesdevs"><strong>/in/bravesdevs</strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44833b9008ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RUST: A Performance Language for Modern System Design.]]></title>
            <link>https://medium.com/@de.marek/rust-a-performance-language-for-modern-system-design-68ff9ec8f89d?source=rss-481a2d15e58d------2</link>
            <guid isPermaLink="false">https://medium.com/p/68ff9ec8f89d</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[systems-engineering]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Devang Parekh]]></dc:creator>
            <pubDate>Thu, 10 Oct 2024 16:59:08 GMT</pubDate>
            <atom:updated>2024-10-10T16:59:08.278Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Rustup your backend, or risk watching your machine get corrupt on resources.</blockquote><p>So, you want to learn Rust but don’t know where to start? Here, I will encompass the details, roadmap, and basics of Rust to help you begin building performant systems with ease.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*Q48V9sh1SPFDO18t0iwzqA.jpeg" /><figcaption>Source: <a href="https://www.sipexe.com/">www.sipexe.com</a></figcaption></figure><p><strong>We will go through the list of topics below</strong></p><ol><li>Bonjour from Rust.</li><li>Why Rust?</li><li>How to Rust and 101s?</li><li>WTH is borrowing and ownership.</li><li>Next steps.</li></ol><h3>Bonjour from Rust!!</h3><p><strong>The</strong> <strong>broken elevator and unexpected cardio.</strong></p><p>Over 18 years ago, a developer at Mozilla named <a href="https://github.com/graydon">Graydon Hoare</a> was returning from work when he discovered that his building’s elevator was out of order. He had no choice but to climb the <strong>21</strong> floors, and as human nature tends to be, he got annoyed that a software malfunction caused his unexpected cardio session.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2FMF-2KZ4JlwIkdCErIgFw.png" /><figcaption>This is not the elevator which the Hoare was mad on, it’s from TBBT.</figcaption></figure><p>Hoare poured these frustrations into digging into the elevator’s software and learned that the software implementation of the elevator was in C++, which had loopholes and bugs. While C++ provides the flexibility needed to program functions for an application’s successful execution, it also requires developers to manage memory transactions carefully.</p><h4>Yeah Okay!, Why not JAVA?</h4><p>Well, they say with great power comes great heaviness (yeah, I tweaked it a bit). We all know Java has wonderful garbage collection dynamics, but let’s face it, JAVA applications are DAMNNNN slow.</p><p>With the consumption of computing resources increasing each day in the era of AI, someone has to think about resources and the CLIMATE (I’m not a fan of Greta, but that’s a topic for later). All I want is to create systems <em>resourceful with low resources</em> because I don’t want to give my money to $NVDA.</p><h3>Why Rust?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*MBs8pKwGZJH6xMTnSDsIsg.png" /></figure><p><strong>Rust is designed to be fast and safe</strong>. It helps developers write code that dashes while preventing common bugs like crashes or memory leaks.</p><p>Unlike some languages, Rust <strong>doesn’t need a garbage collector</strong> to manage memory, making it more efficient. It also has strong safety rules that catch mistakes before the program runs (single ownership and borrowing), making your software more reliable. Rust is great for building things like systems, games, and web applications where performance and stability matter greatly.</p><p>With strongly typed, Rust is a language that looks like TypeScript and has the power of C++.</p><p><strong>Comparison: Rust vs. C++</strong></p><pre><br>+----------------------+------------------------------------------------------------------------+-------------------------------------------------------------------------------------+<br>|        Aspect        |                                  C++                                   |                                        Rust                                         |<br>+----------------------+------------------------------------------------------------------------+-------------------------------------------------------------------------------------+<br>| Memory Safety        | Prone to memory safety issues (e.g., buffer overflows)                 | Designed with memory safety in mind, prevents common errors through ownership model |<br>| Concurrency          | Offers manual control but can be error-prone                           | Provides safer concurrency primitives, making concurrent programming more reliable  |<br>| Error Handling       | Exception-based, can lead to performance overhead                      | Uses Result/Option pattern, which can be more predictable in terms of performance   |<br>| Standard Library     | Extensive, with many legacy parts                                      | Modern and minimalistic, focusing on safety and performance                         |<br>| Use Case Flexibility | Widely used in various domains, including system programming and games | Increasingly used for system programming, web assembly, and embedded systems        |<br>+----------------------+------------------------------------------------------------------------+-------------------------------------------------------------------------------------+<br><br></pre><h3>How to Rust and 101s?</h3><h4><strong>Roadmap</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hPPQp7RvmxJyvZAZm1dSww.png" /></figure><p>The best roadmap so far, I believe, is the one above (not covering everything, but just the basics and Ownership model to get you started). I am following the steps below:</p><ol><li>Installation and Syntax Basics</li><li>Ownership Model (Most Important)</li><li>Control Flow</li><li>Data Structures</li><li>Structs and Enums</li><li>Modules &amp; Crates</li><li>Error Handling</li><li>Generics &amp; Traits</li><li>Basic I/O</li><li>Getting Started with Web Frameworks (Rocket, Actix Web, Warp, etc.)</li></ol><h4><strong>Installation and Setup</strong></h4><p><strong>On Linux or Mac</strong></p><pre>curl --proto &#39;=https&#39; --tlsv1.2 -sSf https://sh.rustup.rs | sh</pre><p><strong>Rustup is the toolchain installer for Rust</strong>. It helps manage different versions of the Rust compiler and associated tools, allowing developers to easily switch between them. To put it simply, if you’ve worked with NodeJS on Linux or Mac, it’s similar to <strong>NVM</strong> (Node Version Manager). Just like NVM helps manage Node.js versions, Rustup assists with handling Rust versions and installations.</p><p><strong>Configuring the </strong><strong>PATH environment variable</strong></p><p>In the Rust development environment, all tools are installed on the ~/.cargo/bin directory and this is where you will find the Rust toolchain, including rustc, cargo, and rustup.</p><p>1. <strong><em>rustc</em></strong> is the Rust programming language&#39;s compiler. It is the tool that takes your Rust source code, typically written in .rs files, and compiles it into executable binaries or libraries.</p><p>2. <strong><em>cargo i</em></strong>s the package manager and build system for the Rust programming language. It simplifies the process of managing Rust projects and their dependencies, making it easier for developers to create, build, and share Rust applications.</p><p><strong>Configure PATH</strong></p><p>Accordingly, it is customary for Rust developers to include this directory in their <a href="https://en.wikipedia.org/wiki/PATH_(variable)">PATH environment variable</a>. During installation rustup will attempt to configure the PATH. Because of differences between platforms, command shells, and bugs in rustup, the modifications to PATH may not take effect until the console is restarted, or the user is logged out, or it may not succeed at all.</p><p><strong>Windows</strong></p><p>Head over to <a href="https://www.rust-lang.org/tools/install">rust-lang.org/instal</a>l, the website detects that you’re running Windows, and it offers you 64- and 32-bit installers of the rustup tool for Windows, as well as instructions on installing Rust to the Windows Subsystem for Linux (WSL).</p><p>When the Rust installer is finished, you’ll be ready to program with Rust.</p><h4><strong>RUST 101</strong></h4><p>In this section, we are gonna go through the project setup with <strong><em>cargo and </em></strong>some foundational topics like variables, data types, and some practices to keep in mind while developing in Rust.</p><p>Use <strong>Cargo</strong> to create a new Rust project. In your terminal, run:</p><pre>cargo new rust_101<br>cd rust_101</pre><p>This creates a new directory called rust_101 with the following structure:</p><pre>rust_101<br>├── Cargo.toml<br>└── src<br>    └── main.rs</pre><ul><li><strong>Cargo.toml</strong>: This file contains the project’s metadata and dependencies.</li><li><strong>main.rs</strong>: This is the main source file where you’ll write your Rust code.</li></ul><p>The fn main() a function is of paramount significance in Rust, as it serves as the entry point for every Rust binary application. Here’s a detailed explanation of its importance:</p><p><strong>1. Entry Point of Execution</strong></p><p>When you run a Rust program, the execution starts from the main function. This is where the program begins its operations, and it is the first function that the Rust runtime calls.</p><p><strong>2. Required in Every Binary Crate</strong></p><p>Every Rust binary crate must have a main function defined. If you try to compile a binary crate without a main function, the compiler will throw an error. This ensures that there is a clear starting point for the program.</p><h4><strong>Variables &amp; Datatypes</strong></h4><p><strong>Variable Declaration</strong> In Rust, you declare a variable using the let keyword followed by the variable name. Here’s the basic syntax:</p><pre>fn main(){<br>  let variable_name;<br>}</pre><p><strong>Initialization</strong> Initialization refers to assigning a value to a variable when it is declared. This can be done in the same line or later in the code.</p><p><strong>Basic Syntax:</strong></p><pre>fn main() {<br>  let x = 5; // Declaring and initializing a variable with a value of 5<br>}</pre><p>In Rust, data types are categorized into two main groups: <strong>Scalar types</strong> and <strong>Compound types</strong>. Understanding these types is essential for effective programming in Rust. Here’s a detailed breakdown of the different data types available in Rust:</p><h4><strong>Scalar Types</strong></h4><p>Scalar types represent a single value. Rust has four primary scalar types:</p><p><strong>Integers</strong>: These are signed and unsigned whole numbers. Rust provides several integer types with different sizes:</p><ul><li>i8, i16, i32, i64, i128, isize: Signed integers of various sizes (8, 16, 32, 64, 128 bits, and pointer size).</li><li>u8, u16, u32, u64, u128, usize: Unsigned integers of various sizes.</li></ul><pre>let a: i32 = -10; // Signed integer<br>let b: u32 = 10;  // Unsigned integer</pre><p><strong>Floating Point Numbers</strong>: Rust has two floating-point types, which are used to represent decimal numbers:</p><ul><li>f32: 32-bit floating point.</li><li>f64: 64-bit floating point (default type for floating-point numbers).</li></ul><pre>let x: f64 = 3.14; // 64-bit floating point<br>let y: f32 = 2.5;  // 32-bit floating point</pre><p><strong>Booleans</strong>: The bool type represents a truth value, either true or false.</p><pre>let is_rust_fun: bool = true;</pre><p><strong>Characters</strong>: The char type represents a single Unicode character. It is a 4-byte type that can represent any character in the Unicode standard.</p><pre>let letter: char = &#39;D&#39;;</pre><h4><strong>Compound Types</strong></h4><p>Compound types can group multiple values into one. Rust has two primary compound types:</p><p><strong>Tuples</strong>: A tuple is a collection of values of different types grouped. Tuples have a fixed length and can contain any number of elements.</p><pre>let tuple: (i32, f64, char) = (42, 3.14, &#39;A&#39;);<br><br>let (x, y, z) = tuple;<br>println!(&quot;x: {}, y: {}, z: {}&quot;, x, y, z);</pre><p><strong>Arrays</strong>: An array is a collection of values of the same type, with a fixed length. You define arrays with a type followed by a length.</p><pre>let array: [i32; 3] = [1, 2, 3]; // Array of 3 integers<br><br>// Accessing array elements<br>let first_element = array[0];</pre><p><strong>Strings</strong>: Rust has two string types: String and &amp;str (string slice).</p><ul><li>String: A growable, heap-allocated string.</li><li>&amp;str: An immutable string slice, typically used for string literals.</li></ul><pre>let mut string: String = String::from(&quot;Hello&quot;);<br>string.push_str(&quot;, World!&quot;); // Modifying the String<br><br>let slice: &amp;str = &quot;Hello, World!&quot;; // String slice</pre><p><strong>Immutable and Mutable Variables</strong></p><p>In Rust, understanding the concepts of <strong>mutable</strong> and <strong>immutable</strong> variables is fundamental, as it directly impacts memory safety and concurrency. Here’s a detailed explanation of both types of variables:</p><p><strong>Immutable Variables</strong></p><ul><li><strong>Definition</strong>: By default, all variables in Rust are immutable. This means that once a variable is bound to a value, you cannot change that value.</li><li><strong>Syntax</strong>: To declare an immutable variable, you use the let keyword.</li></ul><pre>let x = 5; // Immutable variable<br>// x = 10; // This will cause a compile-time error</pre><p><strong>Mutable Variables</strong></p><ul><li><strong>Definition</strong>: If you want a variable’s value to be changeable, you need to declare it as mutable using the mut keyword.</li><li><strong>Syntax</strong>: You declare a mutable variable by adding mut after the variable name.</li></ul><pre>let mut y = 10; // Mutable variable<br>y = 15; // This is allowed<br>println!(&quot;{}&quot;, y); // Outputs: 15</pre><p><strong>Example Code</strong></p><p>Here’s an example demonstrating the use of mutable and immutable variables:</p><pre>fn main() {<br>    // Immutable variable<br>    let a = 5;<br>    println!(&quot;The value of a is: {}&quot;, a);<br>    // a = 6; // Compile time error.<br><br>    // Mutable variable<br>    let mut b = 10;<br>    println!(&quot;The initial value of b is: {}&quot;, b);<br>    b = 15; // altering the value<br>    println!(&quot;The updated value of b is: {}&quot;, b);<br>}</pre><p>Try running the above code using the command below</p><pre>cargo run</pre><p><strong>Shadowing</strong></p><p>In addition to mutability, Rust also supports a feature called <strong>shadowing</strong>, where you can declare a new variable with the same name as an existing one. The new variable shadows the old one, allowing you to change its type or value.</p><pre>fn main() {<br>    let x = 5;<br>    let x = x + 1; // Shadowing: x is now 6<br>    let x = &quot;Hello&quot;; // x is now a string<br>    println!(&quot;{}&quot;, x); // Outputs: Hello<br>}</pre><h4><strong>Ownership Model (Most Important)</strong></h4><p><em>In Rust, variables on the heap are like hot potatoes — once you pass them, you’ve lost your turn!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*PewJTg49v8UyLdyYfWBy7w.gif" /></figure><p>The <strong>ownership model</strong> in Rust is closely tied to how data is managed in memory, specifically between the <strong>stack</strong> and the <strong>heap</strong>.</p><p>This model allows Rust to ensure memory safety while maintaining high performance without needing a garbage collector. Here’s a detailed explanation of how ownership interacts with the stack and heap, and why Rust uses this model.</p><p><strong>Stack and Heap Basics</strong></p><p><strong>Stack:</strong></p><ul><li>The stack is a region of memory where data is stored in a <strong>Last In, First Out</strong> (LIFO) manner.</li><li>Variables stored on the stack must have a known, fixed size at compile-time.</li><li>Access to data on the stack is <strong>fast</strong> because of its ordered structure and no dynamic allocation is needed.</li><li>Function calls and local variables are generally stored on the stack.</li></ul><p><strong>Heap:</strong></p><ul><li>The heap is a region of memory for storing data that does not have a fixed size at compile time.</li><li>Data on the heap can grow or shrink dynamically (strings or vectors).</li><li>Access to the heap is slower than the stack because the system must allocate and deallocate memory dynamically.</li></ul><p><strong>Ownership and Memory Allocation</strong></p><p>Rust’s ownership model manages how values are stored in either the stack or the heap, ensuring that memory is automatically freed when it is no longer needed. Here’s how the model works with stack and heap data:</p><p><strong>Ownership and the Stack:</strong></p><ul><li>Simple, fixed-size data types like integers, booleans, and tuples of fixed sizes are stored on the stack.</li><li>The compiler can track when these types go out of scope, and the memory is automatically reclaimed when that happens.</li></ul><pre>fn main() {<br>    let x = 5; // &#39;x&#39; is on the stack<br>} // &#39;x&#39; goes out of scope and memory is reclaimed</pre><p><strong>Ownership and the Heap:</strong></p><ul><li>Data types like String, Vec, or user-defined structures that can have dynamic sizes are allocated on the heap. These types consist of two parts: a <strong>pointer</strong> to the heap memory and some metadata (like length) that is stored on the stack.</li><li>When a heap-allocated value goes out of scope, the owner is responsible for freeing the heap memory.</li><li>Ownership makes sure that there is always exactly <strong>one owner</strong> for heap-allocated data, so Rust knows when to free memory safely without causing issues like <strong>dangling pointers</strong> or <strong>memory leaks</strong>.</li></ul><pre>fn main() {<br>    let s = String::from(&quot;Hello&quot;); // &#39;s&#39; is a pointer on stack to heap data<br>} // &#39;s&#39; goes out of scope, and the heap memory is automatically freed</pre><p><strong>Ownership Rules</strong></p><p>Rust’s ownership model operates under a few key rules, which prevent memory management errors:</p><ol><li><strong>Each value has a single owner</strong>: Only one variable can own a piece of heap memory at a time.</li><li><strong>When the owner goes out of scope, the value is dropped</strong>: The memory is freed automatically when the owner goes out of scope.</li><li><strong>References and Borrowing</strong>: You can temporarily borrow a value (without taking ownership) to access it or modify it, but ownership remains with the original variable.</li></ol><p><strong>Stack vs. Heap in Practice with Ownership</strong></p><p>Here’s an example illustrating how Rust manages memory for both stack and heap allocations:</p><pre>fn main() {<br>    let x = 5; // Stored on the stack<br>    let y = x; // &#39;y&#39; is a copy of &#39;x&#39;, also on the stack<br>    println!(&quot;x: {}, y: {}&quot;, x, y);<br><br>    let s1 = String::from(&quot;Hello&quot;); // &#39;s1&#39; points to heap data<br>    let s2 = s1; // Ownership is moved to &#39;s2&#39;<br>    // println!(&quot;{}&quot;, s1); // This would cause a compile-time error because &#39;s1&#39; no longer owns the data<br>    println!(&quot;{}&quot;, s2); // &#39;s2&#39; now owns the heap data<br>}</pre><ul><li>x and y are stack-allocated, so copying x to y is a simple, efficient operation.</li><li>s1 is heap-allocated, and when s1 is assigned to s2, ownership is transferred. Trying to use s1 afterward will cause an error, as s1 no longer owns the heap memory.</li></ul><h4>Concept of Borrowing</h4><p>In Rust, borrowing is a process of using a value without any means of moving it from one place to another. It creates opportunities for functions or code sections to use a variable, receive a value without obtaining ownership of the value, and follow strict rules for secure purposes.</p><p><strong>Two types of borrowing:</strong></p><p><strong>Immutable Borrowing</strong> (&amp;T):</p><ul><li>Allows you to read the data without modifying it.</li><li>Multiple immutable borrows are allowed at the same time.</li></ul><pre>let s = String::from(&quot;hello&quot;);<br>let r1 = &amp;s;  // Immutable borrow<br>let r2 = &amp;s;  // Another immutable borrow<br>println!(&quot;{} {}&quot;, r1, r2);  // Both can access the data but cannot change it.</pre><p><strong>Mutable Borrowing</strong> (&amp;mut T):</p><ul><li>Allows you to modify the data.</li><li>Only one mutable borrow is allowed at a time to prevent data races.</li></ul><pre>let mut s = String::from(&quot;hello&quot;);<br>let r = &amp;mut s;  // Mutable borrow<br>r.push_str(&quot;, world!&quot;);  // Changed the borrowed data<br>println!(&quot;{}&quot;, r);  // Outputs: hello, world!</pre><p>Borrowing ensures safe access to data by enforcing ownership rules and preventing dangling references and data races.</p><h3>Next Steps</h3><p>In upcoming blogs, I’ll dive into <strong>control structures</strong>, explore <strong>data structures and algorithms</strong>, and outline a <strong>simple backend microservice</strong> using <strong>Rocket.rs</strong> as a practical example of systems programming.</p><p>When practicing Rust, focus on the basics and nail down the syntax first. Spend time building a strong foundation, then try solving some Leetcode array problems in Rust — you’ll be amazed by the performance. From there, you can gradually level up to more advanced topics!</p><h3>References</h3><ol><li>Rust official documentation <a href="https://doc.rust-lang.org/beta/">Rust Docs</a>.</li><li><a href="https://www.oreilly.com/library/view/hands-on-data-structures/9781788995528">Hands on Data Structures and Algorithms in Rust</a> by Claus Matzinger.</li><li><a href="https://youtu.be/T_KrYLW4jw8?si=OZe73noG6NhAv_TJ">Rust Programming Tutorial</a> by Tech with Tim on Youtube</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68ff9ec8f89d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>