<?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 Fynn Fluegge on Medium]]></title>
        <description><![CDATA[Stories by Fynn Fluegge on Medium]]></description>
        <link>https://medium.com/@fynnfluegge?source=rss-8b3f39d8fdc6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*LKYSb3SJ3dlETyGVStnVxg.jpeg</url>
            <title>Stories by Fynn Fluegge on Medium</title>
            <link>https://medium.com/@fynnfluegge?source=rss-8b3f39d8fdc6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 08:23:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@fynnfluegge/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[100% Serverless RAG on AWS]]></title>
            <link>https://medium.com/@fynnfluegge/serverless-rag-on-aws-bf8029f8bffd?source=rss-8b3f39d8fdc6------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf8029f8bffd</guid>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[faiss]]></category>
            <dc:creator><![CDATA[Fynn Fluegge]]></dc:creator>
            <pubDate>Sat, 23 Mar 2024 19:55:42 GMT</pubDate>
            <atom:updated>2024-03-26T17:39:24.292Z</atom:updated>
            <content:encoded><![CDATA[<h3>Serverless RAG on AWS</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*46ttd2iWf-4ANTqK7lzEPg.jpeg" /></figure><p>In this article I present a lightweight approach to run a Serverless RAG pipeline on AWS with Faiss and Langchain by using Lambda, DynamoDB and S3. I use this setup myself in a playground project together with OpenAI’s <em>text-embedding-ada-002</em> and GPT-3.5 Turbo. However, it is also possible to easily utilize e.g. Sentence Transformers embeddings together with any preferred LLM like Anthropic’s Claude 3 as drop-in replacement.</p><p>You can find the RAG pipeline in operation as part of this project:<br><a href="https://github.com/fynnfluegge/rocketnotes">https://github.com/fynnfluegge/rocketnotes</a></p><h4>The components</h4><p>Two lambda functions, one acting as the chat handler and another one acting as the vector embeddings handler responsible to keep the Faiss vector index in sync with the documents, are required. The Faiss index is stored in S3. Vector Ids to identify vectors related to a specific document are maintained in DynamoDB.</p><p>Both lambda functions are using the same libraries. The requirements.txt looks like:</p><pre>boto3==1.34.0<br>langchain==0.1.5<br>langchain-community==0.0.17<br>langchain-openai==0.0.5<br>faiss-cpu==1.7.0</pre><h4>Vector Embeddings Lambda handler</h4><p>Let’s first start with the Vector Embeddings Handler. The vector embeddings handler needs the following Python dependencies:</p><pre>from pathlib import Path<br><br>import boto3<br>from langchain.schema import Document<br>from langchain.text_splitter import RecursiveCharacterTextSplitter<br>from langchain_community.vectorstores import FAISS<br>from langchain_openai import OpenAIEmbeddings</pre><p>On it’s first execution, the Faiss vector index needs to be initially built and saved to S3. For this, we iterate over all pre-existing documents in our DynamoDB and run a text splitter on each returned document. In this example all documents related to a specific user are fetched by the UserId:</p><pre># Fetch documents by a UserId from DyanmoDB<br>dynamodb = boto3.client(&quot;dynamodb&quot;)<br>filter_expression = &quot;userId = :value&quot;<br>expression_attribute_values = {&quot;:value&quot;: {&quot;S&quot;: userId}}<br><br>result = dynamodb.query(<br>    TableName=&quot;&lt;DOCUMENT_TABLE_NAME&gt;&quot;,<br>    IndexName=&quot;userId-index&quot;,<br>    KeyConditionExpression=filter_expression,<br>    ExpressionAttributeValues=expression_attribute_values,<br>)<br>documents = result.get(&quot;Items&quot;, [])<br><br># Split fetched documents<br>split_documents = []<br>for document in documents:<br>    content = document[&quot;content&quot;][&quot;S&quot;]<br>    documentId = document[&quot;id&quot;][&quot;S&quot;]<br>    title = document[&quot;title&quot;][&quot;S&quot;]<br>    split_documents.extend(split_document(content, documentId, title))</pre><p>In the <em>split_document</em> method we can use any preferred text splitter, e.g. the <em>RecursiveCharacterTextSplitter</em> from Langchain for common usage:</p><pre>def split_document(document, documentId, title):<br>    chunk_size = 512<br>    chunk_overlap = 32<br>    text_splitter = RecursiveCharacterTextSplitter(<br>        chunk_size=chunk_size, chunk_overlap=chunk_overlap<br>    )<br><br>    documents = []<br>    for splitted_document in md_header_splits:<br>        document = Document(<br>            page_content=splitted_document.page_content,<br>            metadata={<br>                &quot;documentId&quot;: documentId,<br>                &quot;title&quot;: title,<br>            },<br>        )<br>        documents.append(document)<br><br>    return documents</pre><p>Now we are ready to create the Faiss index from our splitted documents with <em>text-embedding-ada-002</em> model from OpenAI:</p><pre>embeddings_model = OpenAIEmbeddings(<br>    client=None, model=&quot;text-embedding-ada-002&quot;<br>)<br>db = FAISS.from_documents(split_documents, embeddings_model)</pre><p>To use e.g. Sentence Transformers as embeddings use the following as drop-in replacement for <em>embeddings_model</em>:</p><pre>from langchain_community.embeddings import HuggingFaceEmbeddings<br>embeddings_model = HuggingFaceEmbeddings(<br>    model_name=&quot;sentence-transformers/all-mpnet-base-v2&quot;<br>)</pre><p>After creating the Faiss index, the <em>faiss</em> and <em>pkl </em>files are saved to local storage and then uploaded to <em>S3. </em>It is important to specify <em>tmp</em> as local destination path since the lambda runtime has only write access there.</p><pre>file_path = f&quot;/tmp/&quot;<br>Path(file_path).mkdir(parents=True, exist_ok=True)<br>file_name = &quot;faiss_index.bin&quot;<br>db.save_local(index_name=file_name, folder_path=file_path)<br>s3 = boto3.client(&quot;s3&quot;)<br>s3.upload_file(Filename=file_path + &quot;/&quot; + file_name + &quot;.faiss&quot;, Bucket=&quot;&lt;BUCKET_NAME&gt;&quot;, Key=&quot;my_faiss.faiss&quot;)<br>s3.upload_file(Filename=file_path + &quot;/&quot; + file_name + &quot;.pkl&quot;, Bucket=&quot;&lt;BUCKET_NAME&gt;&quot;, Key=&quot;my_faiss.pkl&quot;)</pre><p>As a last step we need to keep track of all vector Ids for each document to update the vectors if a document has been modified or deleted later. As a prerequisite let’s load the vectors for all document splits of the previously created Faiss index. For that we can use the <em>documentId</em> from the metadata in the document splits:</p><pre>document_vectors = get_vectors_from_faiss_index(<br>    split_documents, db, db.index_to_docstore_id<br>)<br><br>def get_vectors_from_faiss_index(documents, db, index_to_docstore_id):<br>  document_vectors = {}<br>  for i in range(len(documents)):<br>      document = db.docstore.search(index_to_docstore_id[i])<br>      if document:<br>          if document.metadata[&quot;documentId&quot;] not in document_vectors:<br>              document_vectors[document.metadata[&quot;documentId&quot;]] = [<br>                  index_to_docstore_id[i]<br>              ]<br>          else:<br>              document_vectors[document.metadata[&quot;documentId&quot;]].append(<br>                  index_to_docstore_id[i]<br>              )<br>  return document_vectors</pre><p>Now we can save the vector Ids to DynamoDB:</p><pre>for documentId, vectors in document_vectors.items():<br>  newItem = {&quot;id&quot;: {}, &quot;vectors&quot;: {}}<br>  newItem[&quot;id&quot;][&quot;S&quot;] = documentId<br>  newItem[&quot;vectors&quot;][&quot;SS&quot;] = vectors<br>  dynamodb.put_item(TableName=&quot;&lt;VECTOR_TABLE_NAME&gt;&quot;, Item=newItem)</pre><p>The first part of the vector embeddings function is done. Once the Faiss index with it’s vector IDs are saved to S3 and DynamoDB, it can be loaded on subsequent document updates to keep the Faiss index in sync with the document contents. Now on each document update the <em>faiss</em> and <em>pkl</em> files need to be loaded from S3:</p><pre>s3.download_file(Bucket=&quot;&lt;BUCKET_NAME&gt;&quot;, Key=&quot;my_faiss.faiss&quot;, Filename=file_path)<br>s3.download_file(Bucket=&quot;&lt;BUCKET_NAME&gt;&quot;, Key=&quot;my_faiss.pkl&quot;, Filename=file_path)</pre><p>From the loaded <em>faiss</em> and <em>pkl</em> files we can load the Faiss index to memory:</p><pre>db = FAISS.load_local(<br>    index_name=&quot;my_faiss&quot;,<br>    folder_path=file_path,<br>    embeddings=embeddings_model,<br>)</pre><p>It needs to be distinguished if a document was updated or added. If a document has been updated, we need to update also the related vectors in the Faiss index. For that we load the vector Ids of the document from DyanmoDB and delete the outdated vectors from the in-memory Faiss index:</p><pre>vectors = dynamodb.get_item(<br>    TableName=&quot;&lt;VECTOR_TABLE_NAME&gt;&quot;,<br>    Key={&quot;id&quot;: {&quot;S&quot;: documentId}},<br>)<br><br>if &quot;Item&quot; in vectors:<br>    vectors = vectors[&quot;Item&quot;][&quot;vectors&quot;][&quot;SS&quot;]<br>    db.delete(vectors)</pre><p>From now on there is no difference between adding or updating a document. The document content needs to be splitted similar as we did when initializing the Faiss index in the beginning. Finally the vector Ids needs to be fetched from our in-memory Faiss index and saved to DynamoDB as we did in the beginning.</p><pre>content = document[&quot;content&quot;][&quot;S&quot;]<br>documentId = document[&quot;id&quot;][&quot;S&quot;]<br>title = document[&quot;title&quot;][&quot;S&quot;]<br>document_splits = split_document(content, documentId, title)<br>document_vectors = get_vectors_from_faiss_index(<br>    document_splits, db, db.index_to_docstore_id<br>)<br>db.save_local(index_name=file_name, folder_path=file_path)<br>s3.upload_file(Filename=file_path + &quot;/&quot; + file_name + &quot;.faiss&quot;, Bucket=&quot;&lt;BUCKET_NAME&gt;&quot;, Key=&quot;my_faiss.faiss&quot;)<br>s3.upload_file(Filename=file_path + &quot;/&quot; + file_name + &quot;.pkl&quot;, Bucket=&quot;&lt;BUCKET_NAME&gt;&quot;, Key=&quot;my_faiss.pkl&quot;)<br>add_vectors_to_dynamodb(documentId, document_vectors[documentId])</pre><h4>Chat Lambda handler</h4><p>With the Faiss index available in S3 we can now chat with our documents by providing context to the LLM. The chat handler needs the following Python dependencies:</p><pre>from pathlib import Path<br><br>import boto3<br>from langchain.chains import ConversationalRetrievalChain<br>from langchain.memory import ConversationSummaryMemory<br>from langchain_community.vectorstores import FAISS<br>from langchain_openai import ChatOpenAI, OpenAIEmbeddings</pre><p>First the Faiss index needs to be downloaded from S3:</p><pre>file_path = f&quot;/tmp&quot;<br>Path(file_path).mkdir(parents=True, exist_ok=True)<br>s3.download_file(Bucket=bucket_name, Key=&quot;my_faiss.faiss&quot;, Filename=f&quot;{file_path}/my_faiss.faiss&quot;)<br>s3.download_file(Bucket=bucket_name, Key=&quot;my_faiss.pkl&quot;, Filename=f&quot;{file_path}/my_faiss.pkl&quot;)</pre><p>Now let’s load the Faiss index to memory:</p><pre>embeddings = OpenAIEmbeddings(client=None, model=&quot;text-embedding-ada-002&quot;)<br>db = FAISS.load_local(<br>    index_name=&quot;my_faiss&quot;,<br>    folder_path=file_path,<br>    embeddings=embeddings_model,<br>)</pre><p>Finally, we can ask a question with our documents as context with <em>ConversationalRetrievalChain</em> from Langchain:</p><pre>retriever = db.as_retriever(search_type=&quot;mmr&quot;, search_kwargs={&quot;k&quot;: 8})<br><br>chat_model = ChatOpenAI(temperature=0.9, max_tokens=2048, model=&quot;gpt-3.5-turbo&quot;)<br>memory = ConversationSummaryMemory(<br>    llm=chat_model, memory_key=&quot;chat_history&quot;, return_messages=True<br>)<br>qa = ConversationalRetrievalChain.from_llm(<br>    chat_model, retriever=retriever, memory=memory<br>)<br>result = qa(prompt)</pre><p>The conversational memory content can be returned and used as optional for further conversation in a single chat window.<br>To utilize e.g. Anthropic’s Claude 3 you can use the following code snippet as drop-in replacement for <em>chat_model</em>:</p><pre>from langchain_anthropic import ChatAnthropic<br>chat_model = ChatAnthropic(temperature=0.9, model_name=&quot;claude-3-opus-20240229&quot;)</pre><h4><strong>Conclusion</strong></h4><p>Using Serverless RAG is a lightweight alternative to dedicated vector DB instances or services. It is very powerful and cost efficient for smaller projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf8029f8bffd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>