<?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 Izabel Barros on Medium]]></title>
        <description><![CDATA[Stories by Izabel Barros on Medium]]></description>
        <link>https://medium.com/@izabel.barros?source=rss-8766084aca29------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ZLhcIW0jOOSeEbo1eAur3A.png</url>
            <title>Stories by Izabel Barros on Medium</title>
            <link>https://medium.com/@izabel.barros?source=rss-8766084aca29------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 11:13:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@izabel.barros/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[Building a translator assistant with the ChatGPT API]]></title>
            <link>https://medium.com/indiciumtech/building-a-translator-assistant-with-the-chatgpt-api-eb0afd48bb82?source=rss-8766084aca29------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb0afd48bb82</guid>
            <category><![CDATA[translators]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[openai-api]]></category>
            <dc:creator><![CDATA[Izabel Barros]]></dc:creator>
            <pubDate>Fri, 12 Jul 2024 20:29:49 GMT</pubDate>
            <atom:updated>2024-07-12T20:29:49.217Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PQYccBxLqLIClg8gCy44Mg.jpeg" /></figure><p>In today’s globalized world, effective communication across different languages is more important than ever. Therefore, a tool able to translate accurately and efficiently is necessary.</p><p>Whether you’re a student, a professional, a traveler, or simply someone passionate about languages, the ability to translate with quality can open up a world of opportunities.</p><p>With that and our exciting expansion into the U.S. in mind, I decided to build a quick and simple tool to help achieve that goal of effective communication in English from Portuguese (our native language here in Brazil): a translator assistant!</p><p>The ChatGPT API, developed by OpenAI, enables developers to integrate their language model into various applications, such as chatbots, virtual assistants (like the one we’re gonna build), content creation, and more.</p><p>With this API, it is possible to create interactive and intelligent systems that not only understand context, answer questions, generate coherent and contextually relevant text, but also perform tasks based on prompts.</p><p>The translator assistant is going to provide immediate translations and help users who are learning English understand the vocabulary better. It is also going to provide tips and insights to them.</p><p>Finally, it will be a facilitator for communication to people who are still learning the language, breaking down the barriers and promoting better understanding between our contributors.</p><p><strong>Step 1: setting up</strong></p><p>First, we need to set up our Python environment. I suggest doing everything online to easily manage version control. So, let’s start by setting that up.</p><pre>python3 -m venv .venv<br>source .venv/bin/activate</pre><p>We also need to install OpenAI to access the API and the “dotenv” library to set up our key on the next step.</p><pre>pip install openai<br>pip install dotenv</pre><p>Now, we need to set up our OpenAI key so we can use the API. If you don’t have one ready, create an account on the<a href="https://platform.openai.com/signup"> OpenAI website</a> and generate one.</p><p>Create a new Python file (I’m naming mine “translator_assistant.py”), import the tools, and define the OpenAI key.</p><pre># translator_assistant.py<br>import os<br>import openai<br>from dotenv import load_dotenv, find_dotenv<br>_ = load_dotenv(find_dotenv()) # read local .env file<br>openai.api_key = os.environ[&#39;OPENAI_API_KEY&#39;]</pre><p><strong>Step 2: creating the translator</strong></p><p>With the environment set up, we are going to create a function that will call the API and send the query to the model, which we are calling “get_translation”. The OpenAI function “create” helps us tune our response with its parameters:</p><ul><li>The “messages” parameter is a Python dictionary that helps us shape the model’s response, and it’s going to feed the user’s query to it. I’m going to talk more about it in the next step!</li><li>The “model” parameter specifies which version of OpenAI’s language model you want to use.</li><li>The “temperature” parameter controls the randomness of the text generated by the model. Lower values (closer to 0) make the output more deterministic and focused, while higher values (closer to 1) introduce more randomness, leading to more creative and varied responses.</li><li>The “max_token” parameter ​​sets the maximum length of the output text by limiting the number of tokens the model will be allowed to generate.</li></ul><pre>def get_translation(messages, model=&quot;gpt-3.5-turbo&quot;, temperature=0, max_tokens=500):<br>response = openai.chat.completions.create(<br>model=model,<br>messages=messages,<br>temperature=temperature,<br>max_tokens=max_tokens,<br>)<br>return response.choices[0].message.content</pre><p><strong>Step 3: putting it all together</strong></p><p>Let’s build our main function step by step together.</p><p>The languages were kept in a variable so they can be easily changed whenever needed.</p><pre>def main():<br>source_lang = &quot;Portuguese&quot;<br>target_lang = &quot;English&quot;</pre><p>To make this script more user-accessible, let’s print a welcome message that briefly explains what it does. I wanted the assistant to have a friendly English teacher tone to it, so let’s use that welcome text snip to showcase that to the user.</p><pre>print(f&quot;Welcome! I&#39;m your {target_lang} teacher for today! I&#39;ll help you translate messages in {source_lang} to {target_lang}.&quot;)</pre><p>Now, we collect the user’s query.</p><p>To keep it user-accessible, let’s make an input box with a question label to help guide the user and save it in a variable “user_message”.</p><pre>user_message = input(&quot;How can I help you today? &quot;)</pre><p>Saving the user input in a variable is going to help us build the “message” dictionary, a key component for structuring the input to the model.</p><p>Each “message” dictionary contains two keys: “role” and “content”. The “role” key specifies the role of the message sender, which can be system, user, or assistant. The “content” key holds the actual message the role outputs.</p><p>The user message content represents the input from the person interacting with the model, so its content will be the “user_message” variable.</p><pre>messages = [<br>{&#39;role&#39;: &#39;system&#39;, &#39;content&#39;: system_message},<br>{&#39;role&#39;: &#39;user&#39;, &#39;content&#39;: user_message},<br>{&#39;role&#39;: &#39;assistant&#39;, &#39;content&#39;: assistant_message}<br>]</pre><p>The system message content defines the behavior and sets the context for the assistant, like instructions or background information.</p><p>Our system message here not only sets up how we want the assistant to interact with and respond to the user, but also asks that it answers them with the translation, tips, and insights. The better you explain what you want to the model, the better it will interact with your user.</p><pre>system_message = f&quot;&quot;&quot;<br>You&#39;re a {target_lang} teacher. Your task is to correctly translate the message the user gives you in {source_lang} to {target_lang}, in a cheerful tone. You have to provide the user some helpful tips and further explanation on the translation, giving some more insight and tips on {target_lang}. Respond in a friendly and helpful tone, with concise answers. Don&#39;t congratulate the user on the successful translation. Don&#39;t make up things you don&#39;t know.<br>&quot;&quot;&quot;</pre><p>The assistant messages content is used to provide responses from the assistant, either for generating continued dialogue or for context in ongoing interactions. Here, we can use it to help further model our assistant’s behavior by providing some examples.</p><pre>example_input_1 = &quot;&quot;&quot;<br>traduzir &quot;Vamos marcar uma reunião<br>&quot;&quot;&quot;&quot;<br>example_output_1 = &quot;&quot;&quot;<br>&quot;Let&#39;s schedule a meeting.&quot;<br>In English, the verb &quot;to schedule&quot; is commonly used when setting up appointments, meetings, or events. It&#39;s a versatile word that can be used in various contexts. Remember to use &quot;let&#39;s&quot; before the verb to suggest doing something together. Keep up the good work!<br>&quot;&quot;&quot;<br></pre><p>This is how our “message” dictionary is going to look like:</p><pre>messages = [<br>{&#39;role&#39;: &#39;system&#39;, &#39;content&#39;: system_message},<br>{&#39;role&#39;: &#39;user&#39;, &#39;content&#39;: example_input_1},<br>{&#39;role&#39;: &#39;assistant&#39;, &#39;content&#39;: example_output_1},<br>{&#39;role&#39;: &#39;user&#39;, &#39;content&#39;: user_message}<br>]</pre><p>Now, we are ready to call our “get_translation” function.</p><pre>translation = get_translation(messages)</pre><p>And print out the result to the user!</p><p>Let’s use a label to mark the output to keep our assistant as user-friendly as possible — plus it helps to keep with the cheerful English teacher tone.</p><pre>print(&quot;\nTeacher:&quot;)<br>print(translation)</pre><p>Last but not least, let’s add moderation to our input and output.</p><p>​​Moderation helps ensure that the assistant is up with safety guidelines and legal requirements by filtering out harmful, inappropriate, or illegal content.</p><p>Since this is thought to be used within our company, moderation will help maintain a positive brand image by preventing the assistant from generating offensive or controversial responses that could damage the brand’s reputation or are not in compliance with its culture and guidelines.</p><pre>moderation_input = openai.moderations.create(input=user_message)<br>if moderation_input.results[0].flagged:<br>return print(&quot;Sorry, we cannot process this request.&quot;)<br>moderation_output = openai.moderations.create(input=translation)<br>if moderation_output.results[0].flagged:<br>return print(&quot;Sorry, we cannot process this request.&quot;)</pre><p>Now that we have all the pieces set up, this is how the main function will look like:</p><pre>def main():<br>source_lang = &quot;Portuguese&quot;<br>target_lang = &quot;English&quot;<br>print(f&quot;Welcome! I&#39;m your English teacher for today! I&#39;ll help you translate messages in {source_lang} to {target_lang}.&quot;)<br>user_message = input(&quot;How can I help you today? &quot;)<br>moderation_input = openai.moderations.create(input=user_message)<br>if moderation_input.results[0].flagged:<br>return print(&quot;Sorry, we cannot process this request.&quot;)<br>system_message = f&quot;&quot;&quot;<br>You&#39;re a {target_lang} teacher. Your task is to correctly translate the message the user gives you in {source_lang} to {target_lang}, in a cheerful tone. You have to provide the user some helpful tips and further explanation on the translation, giving some more insight and tips on {target_lang}. Respond in a friendly and helpful tone, with concise answers. Don&#39;t congratulate the user on the successful translation. Don&#39;t make up things you don&#39;t know.<br>&quot;&quot;&quot;<br>example_input_1 = &quot;&quot;&quot;<br>traduzir &quot;Vamos marcar uma reunião&quot;<br>&quot;&quot;&quot;<br>example_output_1 = &quot;&quot;&quot;<br>&quot;Let&#39;s schedule a meeting.&quot;<br>In English, the verb &quot;to schedule&quot; is commonly used when setting up appointments, meetings, or events. It&#39;s a versatile word that can be used in various contexts. Remember to use &quot;let&#39;s&quot; before the verb to suggest doing something together. Keep up the good work!<br>&quot;&quot;&quot;<br>messages = [<br>{&#39;role&#39;: &#39;system&#39;, &#39;content&#39;: system_message},<br>{&#39;role&#39;: &#39;user&#39;, &#39;content&#39;: example_input_1},<br>{&#39;role&#39;: &#39;assistant&#39;, &#39;content&#39;: example_output_1},<br>{&#39;role&#39;: &#39;user&#39;, &#39;content&#39;: user_message}<br>]<br>translation = get_translation(messages)<br>moderation_output = openai.moderations.create(input=translation)<br>if moderation_output.results[0].flagged:<br>return print(&quot;Sorry, we cannot process this request.&quot;)<br>print(&quot;\nTeacher:&quot;)<br>print(translation)</pre><p><strong>Step 4: running your translator assistant</strong></p><p>Now, all you need to do is type the following command line on your terminal to call our assistant!</p><pre>python3 translator_assistant.py</pre><p>Remember to change the name of the file on the command line if you named it something else.</p><p><strong>Conclusion</strong></p><p>In conclusion, having a tool like ChatGPT’s API to create a translator assistant offers a powerful and flexible solution for real-time language translation needs.</p><p>By building a highly responsive translation tool, we can quickly bridge the gap between contributors that speak different languages and make such valuable knowledge super accessible to help further their skills.</p><p><strong>Acknowledgment</strong></p><p>This blog post was inspired by the insights and knowledge gained from the Building Systems with the ChatGPT API course offered by deeplearning.ai.</p><p>This blogpost is also accompanied by a GitHub repository, where you can find the script showcased here and interact with it!</p><p><a href="https://github.com/belbarros/translator-assistant">https://github.com/belbarros/translator-assistant</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb0afd48bb82" width="1" height="1" alt=""><hr><p><a href="https://medium.com/indiciumtech/building-a-translator-assistant-with-the-chatgpt-api-eb0afd48bb82">Building a translator assistant with the ChatGPT API</a> was originally published in <a href="https://medium.com/indiciumtech">Indicium AI Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring LangChain: four powerful memory types for conversational AI]]></title>
            <link>https://medium.com/indiciumtech/exploring-langchain-four-powerful-memory-types-for-conversational-ai-acfd1fbac287?source=rss-8766084aca29------2</link>
            <guid isPermaLink="false">https://medium.com/p/acfd1fbac287</guid>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[langchain-memory]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Izabel Barros]]></dc:creator>
            <pubDate>Mon, 01 Jul 2024 13:11:22 GMT</pubDate>
            <atom:updated>2024-07-01T13:11:22.522Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*Piheg61_GZ504KHtzjWNIQ.png" /></figure><p>In the rapidly evolving world of artificial intelligence, creating more human-like and context-aware interactions has become the gold standard. But how can we create an AI that not only remembers your previous discussions but also understands the context of your ongoing dialogue, making interactions more fluid and natural? LLMs are stateless by nature, and do not remember the conversation you’ve had so far.</p><p>This is where Langchain comes in.</p><p>LangChain provides a sophisticated framework for managing conversational context. Whether you’re developing a customer support chatbot, a virtual assistant, or any AI-driven conversational tool, incorporating memory capabilities can significantly improve user experience, making interactions more engaging and effective.</p><p>The chat memory feature significantly improves the user experience by providing personalization, continuity, and efficiency. By remembering past interactions, user preferences, and context, chatbots can tailor responses, maintain conversation flow, and anticipate user needs more effectively. This creates a smoother, more engaging experience for the user.</p><p>Additionally, chatbots with memory can engage in multiturn conversations, offer more accurate solutions, and continuously improve through iterative learning. It contributes to building stronger connections between users and chatbots, leading to higher satisfaction and engagement.</p><p>In this blogpost we will be talking about four Langchain memory types, with code snippets to show them in action. Join us as we explore this tool LangChain provides, that is transforming how machines understand and engage with humans.</p><h3>ConversationBufferMemory</h3><p>At its core, <strong><em>ConversationBufferMemory</em></strong> is the most basic memory type that allows AI models to retain a complete running history of interactions. This memory buffer captures and stores the raw dialogue data in its entirety. By maintaining this context, the AI can generate more accurate and relevant responses.</p><pre>from langchain.chat_models import ChatOpenAI<br>from langchain.chains import ConversationChain<br>from langchain.memory import ConversationBufferMemory<br>llm = ChatOpenAI(temperature=0.0, model=llm_model)<br>memory = ConversationBufferMemory()<br>conversation = ConversationChain(<br>llm=llm,<br>memory = memory,<br>verbose=False<br>)<br>conversation.predict(input=&quot;Hello, my name is Izabel!&quot;)<br>conversation.predict(input=&quot;Whats the weather today in Florianópolis?&quot;)<br>conversation.predict(input=&quot;Whats my name?&quot;)<br><br># Human: Hello, my name is Izabel!<br># AI: Hello Izabel! It&#39;s nice to meet you. My name is OpenAI. How can I assist you today?<br># Human: Whats the weather today in Florianópolis?<br># AI: According to my sources, the current weather in Florianópolis is mostly cloudy with a high of 25 degrees Celsius and a low of 19 degrees Celsius. There is a chance of scattered thunderstorms throughout the day. Would you like me to provide more detailed information or a forecast for the upcoming days?<br># Human: Whats my name?<br># AI: Your name is Izabel, as you mentioned earlier.</pre><p>With <strong><em>ConversationBufferMemory</em></strong>, the AI can provide responses that are contextually relevant, reducing misunderstandings and enhancing the quality of the conversation.</p><p>As the conversation grows, the memory requirements increase significantly, leading to higher costs. This is because sending a large number of tokens to the language model (which typically charges based on the number of tokens processed) becomes more expensive.</p><h3>ConversationBufferWindowMemory</h3><p><strong><em>ConversationBufferWindowMemory</em></strong> is an option to solve that problem. Unlike ConversationBufferMemory, which stores the entire conversation history, this feature maintains a dynamic window of recent interactions.</p><p>It works by retaining a “window” of recent dialogue exchanges, defined by the “k” parameter. This window shifts with each new interaction, discarding the oldest entries to make room for new ones. This allows the AI to reference recent context while keeping memory usage and processing costs in check.</p><pre>from langchain.chat_models import ChatOpenAI<br>from langchain.chains import ConversationChain<br>from langchain.memory import ConversationBufferWindowMemory<br>memory = ConversationBufferWindowMemory(k=1)<br>llm = ChatOpenAI(temperature=0.0, model=llm_model)<br>memory = ConversationBufferWindowMemory(k=1)<br>conversation = ConversationChain(<br>llm=llm,<br>memory = memory,<br>verbose=False<br>)<br>conversation.predict(input=&quot;Hello, my name is Izabel!&quot;)<br># Human: Hello, my name is Izabel!<br># AI: Hello Izabel! It&#39;s nice to meet you. My name is OpenAI. How can I assist you today?<br>conversation.predict(input=&quot;Whats the weather today in Florianópolis?&quot;)<br># Human: Whats the weather today in Florianópolis?<br># AI: According to my sources, the current weather in Florianópolis is mostly cloudy with a high of 25 degrees Celsius and a low of 19 degrees Celsius. There is a chance of scattered thunderstorms throughout the day. Would you like me to provide more detailed information or a forecast for the upcoming days?<br>conversation.predict(input=&quot;Whats my name?&quot;)<br># Human: Whats my name?<br># AI: I&#39;m sorry, but I don&#39;t have access to that information. Could you please tell me your name?</pre><p>As we can see from the example above, the AI only remembers the latest interaction, because the parameter “k” is set to 1, so it can’t access older information.</p><p>Limiting the amount of memory reduces the number of tokens sent to the language model, which helps manage and reduce operational costs. It also ensures the system remains efficient and responsive, even as the conversation grows, making it ideal for applications with high user engagement.</p><h3>ConversationTokenBufferMemory</h3><p>The ConversationTokenBufferMemory operates by maintaining a buffer of recent tokens within a predefined limit, set on the “max_token_limit” parameter. This buffer continuously updates with each new interaction, discarding the oldest tokens to accommodate new ones.</p><pre>from langchain.chat_models import ChatOpenAI<br>from langchain.chains import ConversationChain<br>from langchain.memory import ConversationTokenBufferMemory<br>llm = ChatOpenAI(temperature=0.0, model=llm_model)<br>memory = ConversationTokenBufferMemory(llm=llm, max_token_limit=50)<br>conversation = ConversationChain(<br>llm=llm,<br>memory=memory,<br>verbose=True<br>)<br>conversation.predict(input=&quot;Hello, my name is Izabel!&quot;)<br># Human: Hello, my name is Izabel!<br># AI: Hello Izabel! It&#39;s nice to meet you. My name is OpenAI. How can I assist you today?<br>conversation.predict(input=&quot;I&#39;m going to a party tonight&quot;)<br># Human: I&#39;m going to a party tonight<br>AI: That sounds like fun! Do you need any help with party planning or outfit ideas? I can provide suggestions based on your preferences and the latest fashion trends.<br>conversation.predict(input=&quot;Whats my name?&quot;)<br># Human: Whats my name?<br>AI: I&#39;m sorry, I don&#39;t have access to that information. Would you like me to call you by a specific name or nickname?</pre><p>As shown on the example above, the AI cannot access the information asked because it was replaced by newer interactions, following the token limitation set to 50.</p><p>This approach also helps keep the reduced costs and steady efficiency and responsiveness when dealing with bigger, more complex applications.</p><h3>ConversationSummaryMemory</h3><p>The last memory type we are gonna see is the <strong><em>ConversationSummaryMemory.</em></strong> It optimizes memory management by summarizing past interactions. Instead of storing every detail of a conversation, this tool generates summaries of the conversation over time.</p><p>These summaries replace the detailed logs of the conversation, allowing the AI to reference the essential context without needing to process large volumes of tokens. However, it’s worth noting that one of its downsides is that you cannot choose what’s stored in the summarization, since it’s done by the LLM chosen.</p><pre>from langchain.chat_models import ChatOpenAI<br>from langchain.chains import ConversationChain<br>from langchain.memory import ConversationSummaryBufferMemory<br>​​llm = ChatOpenAI(temperature=0.0, model=llm_model)<br>memory = ConversationSummaryBufferMemory(llm=llm, max_token_limit=50)<br>conversation = ConversationChain(<br>llm=llm,<br>memory=memory,<br>verbose=True<br>)<br>conversation.predict(input=&quot;Hello, my name is Izabel!&quot;)<br>conversation.predict(input=&quot;I&#39;m going to a party tonight&quot;)<br># System: The human introduces themselves as Izabel and the AI, OpenAI, greets them. OpenAI asks how they can assist Izabel and she mentions that she is going to a party tonight.<br>AI: That sounds like fun! Do you need any help with party planning or outfit ideas? I can provide suggestions based on your preferences and the latest fashion trends.</pre><h3>Conclusion</h3><p>With those four main memory types and so many others, LangChain provides tools to optimize both performance and cost. Each memory type addresses specific challenges, enabling developers to tailor their AI applications to meet the unique needs of their users.</p><p>As you integrate these memory solutions into your projects, you will not only streamline your AI’s performance but also unlock new possibilities for creating more engaging and intelligent conversational experiences.</p><h3>Acknowledgment</h3><p>This blog post was inspired by the insights and knowledge gained from the LangChain for LLM Application Development course offered by deeplearning.ai.</p><p>This blogpost is also accompanied by a GitHub repository, where you can find the scripts showcased here and interact with them!</p><p><a href="https://github.com/belbarros/langchain-memories">https://github.com/belbarros/langchain-memories</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=acfd1fbac287" width="1" height="1" alt=""><hr><p><a href="https://medium.com/indiciumtech/exploring-langchain-four-powerful-memory-types-for-conversational-ai-acfd1fbac287">Exploring LangChain: four powerful memory types for conversational AI</a> was originally published in <a href="https://medium.com/indiciumtech">Indicium AI Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhancing Document Interaction with LangChain VectorStore Retrieval]]></title>
            <link>https://medium.com/indiciumtech/enhancing-document-interaction-with-langchain-vectorstore-retrieval-27d0be6a1832?source=rss-8766084aca29------2</link>
            <guid isPermaLink="false">https://medium.com/p/27d0be6a1832</guid>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[retrieval]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[vector-store]]></category>
            <dc:creator><![CDATA[Izabel Barros]]></dc:creator>
            <pubDate>Fri, 14 Jun 2024 14:25:57 GMT</pubDate>
            <atom:updated>2024-06-14T14:25:57.896Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/889/1*Gd947ct1JnUEvo8Sj6fiEg.png" /></figure><p>In today’s world, the ability to find relevant information quickly and accurately in an optimized way is very important, especially when dealing with large amounts of documents.<br>LangChain helps us achieve that by providing the tools to build a ChatBot on our documents with Retrieval Augmented Generation (RAG). In this blogpost, we are gonna explore one of its key elements: the retrievers, more specifically VectorStore Retrievals.</p><p>Retrieval-Augmented Generation (RAG) is a method that first retrieves relevant documents from a knowledge base or a dataset and then uses this retrieved information to generate more accurate and contextually relevant responses. RAG helps overcome the limitations of LLMs by providing them with up-to-date and specific information that improves their outputs.</p><p>In the context of LangChain, a retriever is a tool that helps extract relevant information from a source. It’s like setting up a search engine specifically to work with language models on your pre-loaded document. Retrievers fetch pertinent information that can aid the LLM in generating accurate and contextually relevant responses. It’s an efficient way to handle large sources, and since it delivers more pertinent information, it makes the interactions more satisfying and efficient for the user.</p><p>LLMs, despite their capabilities, sometimes generate generic or less accurate responses when they lack specific context. Retrievers bridge this gap by supplying the model with precise information, increasing the accuracy of the generated output. Because they pre-select relevant information from a vast dataset, retrievers can also help reduce the amount of data that needs to be processed by the LLM, not only speeding up the response time but also lowering computational costs.</p><p>VectorStore Retrievals are a type of retrieval that works on a vector database, using document embeddings to perform their search. Unlike traditional keyword-based retrieval, VectorStore retrieval captures the context and meaning behind the words, enabling more accurate and relevant document fetching.</p><p>There are several types of VectorStore Retrievals, but today we are gonna focus on two: Similarity Search and Maximum Marginal Relevance.</p><h4>Setting up</h4><p>Before we can see our retrievers in action, let’s make sure that we have our OpenAPI key and our environment set up.</p><pre>import os<br>import openai<br>from dotenv import load_dotenv, find_dotenv<br>_ = load_dotenv(find_dotenv())<br>openai.api_key = os.environ[&#39;OPENAI_API_KEY&#39;]</pre><p>After that, let’s install LangChain.</p><pre>pip install langchain</pre><p>To better showcase the differences between the two types of retrievals, we are going to query a simple text database, but this could be scaled to any size of database needed.</p><pre>texts = [<br>    &quot;&quot;&quot;The Amanita phalloides has a large and imposing epigeous (aboveground) fruiting body (basidiocarp).&quot;&quot;&quot;,<br>    &quot;&quot;&quot;A mushroom with a large fruiting body is the Amanita phalloides. Some varieties are all-white.&quot;&quot;&quot;,<br>    &quot;&quot;&quot;A. phalloides, a.k.a Death Cap, is one of the most poisonous of all known mushrooms.&quot;&quot;&quot;,<br>]</pre><p>Then, we move to embedding. Embedding documents in LangChain converts text into numerical vectors, allowing for efficient similarity searches and better understanding by the language model. After that, we load those embedding vectors into a vector store, a specialized database for storing and retrieving document embeddings. We are using Chroma today.</p><pre>from langchain.embeddings.openai import OpenAIEmbeddings<br>from langchain.vectorstores import Chroma</pre><pre>persist_directory = &#39;docs/chroma/&#39;</pre><pre>embedding = OpenAIEmbeddings()<br>vectordb = Chroma(<br>    persist_directory=persist_directory,<br>    embedding_function=embedding<br>)<br>smalldb = Chroma.from_texts(texts, embedding=embedding)</pre><h4>Using similarity_search</h4><p>Similarity search involves retrieving documents that are semantically similar to a given query.</p><p>Unlike traditional keyword-based search, which depends on exact matches of keywords, similarity search uses embeddings to capture the contextual meaning of the text. This allows for more accurate and relevant document retrieval.</p><p>We are gonna give our database a query and we are going to showcase similarity search first.</p><pre>question = &quot;Tell me about all-white mushrooms with large fruiting bodies&quot;</pre><pre>docs_ss = smalldb.similarity_search(question, k=2)<br>print(docs_ss[0], docs_ss[1])<br>#page_content=&#39;A mushroom with a large fruiting body is the Amanita phalloides. Some varieties are all-white.&#39; <br>page_content=&#39;The Amanita phalloides has a large and imposing epigeous (aboveground) fruiting body (basidiocarp).&#39;</pre><p>Our query got converted into a numerical vector representation using document embeddings. Then, with LangChain, it searches through the vector representations of all documents in our Vector Store to find the ones that are most similar to the query vector, and gives us an answer that was semantically similar to our query.</p><h4>Using MMR</h4><p>Maximum Marginal Relevance (MMR) is a retrieval type that balances relevance and diversity in the results. MMR considers both the relevance of documents to the query and the novelty of the information they provide compared to already selected documents.</p><pre>docs_mmr = smalldb.max_marginal_relevance_search(question,k=2, fetch_k=3)<br>print(docs_mmr[0], docs_mmr[1])</pre><pre># page_content=&#39;A mushroom with a large fruiting body is the Amanita phalloides. Some varieties are all-white.&#39;<br>page_content=&#39;A. phalloides, a.k.a Death Cap, is one of the most poisonous of all known mushrooms.&#39;</pre><p>One of its biggest benefits is that MMR ensures that retrieved documents provide diverse perspectives and information, reducing redundancy. It also maintains a high level of relevance to the original query while ensuring that the information is varied and comprehensive.</p><p>All that combined improves the quality of user experience, because they receive a broader range of relevant information, making their interactions more satisfying for the user.</p><h4>Conclusion</h4><p>As seen in our blogpost, LangChain’s Similarity Search and Maximal Marginal Relevance (MMR) are just two examples on how powerful retrievers can be. They leverage document embeddings and similarity measures to efficiently search through any size collections of documents and prioritize relevant results.</p><p>It’s important to remember that LangChain offers a variety of other retrievers, each with its own unique features and capabilities. You can also explore these two retrievers shown here in more depth to further refine their information retrieval tasks,using fine-tuning parameters, integrating with other algorithms, or customizing for specific use cases.</p><p>With a deeper understanding and exploration of LangChain’s retrievers, users can maximize the potential of their natural language processing workflows and achieve more accurate and insightful results.</p><h4>Acknowledgements</h4><p>This blog post was inspired by the insights and knowledge gained from the LangChain: Chat with Your Data course offered by deeplearning.ai.</p><p>This blogpost is also accompanied by a GitHub repository, where you can find the scripts showcased here and interact with them!<br><a href="https://github.com/belbarros/langchain-vectorstore/tree/main">https://github.com/belbarros/langchain-vectorstore/tree/main</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27d0be6a1832" width="1" height="1" alt=""><hr><p><a href="https://medium.com/indiciumtech/enhancing-document-interaction-with-langchain-vectorstore-retrieval-27d0be6a1832">Enhancing Document Interaction with LangChain VectorStore Retrieval</a> was originally published in <a href="https://medium.com/indiciumtech">Indicium AI Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>