{"id":10345,"date":"2026-02-11T23:55:15","date_gmt":"2026-02-12T07:55:15","guid":{"rendered":"https:\/\/www.couchbase.com\/developers\/tutorials\/bedrock-serverless-pdf-chat\/"},"modified":"2026-02-11T23:55:15","modified_gmt":"2026-02-12T07:55:15","slug":"bedrock-serverless-pdf-chat","status":"publish","type":"tutorials","link":"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/bedrock-serverless-pdf-chat\/","title":{"rendered":"Serverless PDF Chat App with Couchbase and AWS Bedrock"},"content":{"rendered":"\n<h3 id=\"h-introduction\" class=\"wp-block-heading\">Introduction<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Welcome to this comprehensive guide on constructing an AI-enhanced Chat Application. We will create a dynamic chat interface capable of going deep into PDF documents to extract and provide summaries, key facts, and answers to your queries. By the end of this tutorial, you\u2019ll have a powerful tool at your disposal, transforming the way you interact with and utilize the information contained within PDFs.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This tutorial will demonstrate how to &#8211;<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Construct a <a href=\"https:\/\/www.couchbase.com\/products\/vector-search\/\">Couchbase Vector Search Index<\/a> for doing Vector Search.<\/li>\n\n\n<li>Use AWS Serverless Architecture with services like API Gateway, SQS, Lambdas, Bedrock.<\/li>\n\n\n<li>Chunk PDFs into Vectors with <a href=\"https:\/\/langchain.com\/\">LangChain<\/a> and use <a href=\"https:\/\/python.langchain.com\/docs\/integrations\/vectorstores\/couchbase\/\">Couchbase Vector Store<\/a> to store the vectors into Couchbase.<\/li>\n\n\n<li>Query large language models via the <a href=\"https:\/\/aws.amazon.com\/what-is\/retrieval-augmented-generation\/\">RAG framework<\/a> for contextual insights. We will use <a href=\"https:\/\/aws.amazon.com\/bedrock\/\">AWS Bedrock<\/a> for generating Embeddings and LLM.<\/li>\n\n\n<li>Craft an elegant UI with Streamlit. All these components come together to create a seamless, AI-powered chat experience.<\/li>\n\n<\/ul>\n\n\n\n<h3 id=\"h-prerequisites\" class=\"wp-block-heading\">Prerequisites<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Ensure <a href=\"https:\/\/docs.astral.sh\/uv\/\"><code>uv<\/code><\/a> installed. <code>uv<\/code> helps us manage Python versions and create a lockfile for all the project&#8217;s dependencies for ease of use.<\/li>\n\n\n<li>Couchbase Cluster (Self Managed or Capella) version 7.6.2+ with <a href=\"https:\/\/docs.couchbase.com\/server\/current\/fts\/fts-introduction.html\">Search Service<\/a> and <a href=\"https:\/\/docs.couchbase.com\/server\/current\/eventing\/eventing-overview.html\">Eventing Service<\/a><\/li>\n\n<\/ul>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\">Note that this tutorial is designed to work with the latest Python SDK version (4.3.0+) for Couchbase. It will not work with the older Python SDK versions.<\/p>\n<\/blockquote>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\">Vector Search in Couchbase is only supported at Couchbase Version 7.6+.<\/p>\n<\/blockquote>\n\n\n\n<h3 id=\"h-quick-start-guide\" class=\"wp-block-heading\">Quick Start Guide:<\/h3>\n\n\n\n<h4 id=\"h-cloning-repo\" class=\"wp-block-heading\">Cloning Repo<\/h4>\n\n\n\n<pre class=\"wp-block-code language-shell\"><code>git clone https:\/\/github.com\/couchbase-examples\/rag-aws-bedrock-serverless.git\n<\/code><\/pre>\n\n\n\n<h4 id=\"h-install-dependencies\" class=\"wp-block-heading\">Install Dependencies<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Dependencies for the project are installed via <code>uv<\/code> as mentioned earlier. You can install the dependencies using the following command:<\/p>\n\n\n\n<pre class=\"wp-block-code language-shell\"><code>uv sync\n<\/code><\/pre>\n\n\n\n<h4 id=\"h-setup-database-configuration\" class=\"wp-block-heading\">Setup Database Configuration<\/h4>\n\n\n\n<h5 id=\"h-capella-setup\" class=\"wp-block-heading\">Capella Setup<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">To know more about connecting to your Capella cluster, please follow the <a href=\"https:\/\/docs.couchbase.com\/cloud\/get-started\/connect.html\">instructions<\/a>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Specifically, you need to do the following:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Create the <a href=\"https:\/\/docs.couchbase.com\/cloud\/clusters\/manage-database-users.html\">database credentials<\/a> to access cluster via SDK<\/li>\n\n\n<li><a href=\"https:\/\/docs.couchbase.com\/cloud\/clusters\/allow-ip-address.html\">Allow access<\/a> to the Cluster from the IP on which the application is running.<\/li>\n\n<\/ul>\n\n\n\n<h5 id=\"h-self-managed-setup\" class=\"wp-block-heading\">Self Managed Setup<\/h5>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Follow <a href=\"\/tutorial-couchbase-installation-options\">Couchbase Installation Options<\/a> for installing the latest Couchbase Database Server Instance. Make sure to add the <a href=\"https:\/\/docs.couchbase.com\/server\/current\/fts\/fts-introduction.html\">Search Service<\/a>.<\/li>\n\n<\/ul>\n\n\n\n<h4 id=\"h-create-bucket\" class=\"wp-block-heading\">Create Bucket<\/h4>\n\n\n\n<ul class=\"wp-block-list\">\n<li>For the purpose of this tutorial, we will be using specific bucket, scope and collection. However, you may use any name of your choice but make sure to update names in all the steps.<\/li>\n\n\n<li>Create a bucket named <code>pdf-chat<\/code>. We will use the <code>shared<\/code> scope and <code>docs<\/code> collection of this bucket which needs to be created. <a href=\"https:\/\/docs.couchbase.com\/cloud\/clusters\/data-service\/about-buckets-scopes-collections.html\">Read more<\/a><\/li>\n\n<\/ul>\n\n\n\n<h4 id=\"h-create-the-vector-search-index-on-search-service\" class=\"wp-block-heading\">Create the Vector Search Index on Search Service<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">We need to create the Vector Search Index on the Search Service in Couchbase. For this demo, you can import the following index using the instructions.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>\n<p><a href=\"https:\/\/docs.couchbase.com\/cloud\/search\/import-search-index.html\">Couchbase Capella<\/a><\/p>\n<ul>\n<li>Copy the index definition to a new file index.json.<\/li>\n<li>Import the file in Capella using the instructions in the documentation.<\/li>\n<li>Click on Create Index to create the index.<\/li>\n<\/ul>\n<\/li>\n\n\n<li>\n<p><a href=\"https:\/\/docs.couchbase.com\/server\/current\/search\/import-search-index.html\">Couchbase Server<\/a><\/p>\n<ul>\n<li>Click on Search \u2192 Add Index \u2192 Import.<\/li>\n<li>Copy the following Index definition in the Import screen.<\/li>\n<li>Click on Create Index to create the index.<\/li>\n<\/ul>\n<\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">You may also create a vector search index using Search UI on both <a href=\"https:\/\/docs.couchbase.com\/cloud\/vector-search\/create-vector-search-index-ui.html\">Couchbase Capella<\/a> and <a href=\"https:\/\/docs.couchbase.com\/server\/current\/vector-search\/create-vector-search-index-ui.html\">Couchbase Self Managed Server<\/a>.<\/p>\n\n\n\n<h5 id=\"h-index-definition\" class=\"wp-block-heading\">Index Definition<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">Here, we are creating the index <code>pdf_search<\/code> on the documents. The Vector field is set to <code>embedding<\/code> with 1024 dimensions and the text field set to <code>text<\/code>. We are also indexing and storing all the fields under <code>metadata<\/code> in the document as a dynamic mapping to account for varying document structures. The similarity metric is set to <code>dot_product<\/code>. If there is a change in these parameters, please adapt the index accordingly.<\/p>\n\n\n\n<pre class=\"wp-block-code language-json\"><code>{\n  &quot;name&quot;: &quot;pdf_search&quot;,\n  &quot;type&quot;: &quot;fulltext-index&quot;,\n  &quot;params&quot;: {\n    &quot;doc_config&quot;: {\n      &quot;docid_prefix_delim&quot;: &quot;&quot;,\n      &quot;docid_regexp&quot;: &quot;&quot;,\n      &quot;mode&quot;: &quot;scope.collection.type_field&quot;,\n      &quot;type_field&quot;: &quot;type&quot;\n    },\n    &quot;mapping&quot;: {\n      &quot;default_analyzer&quot;: &quot;standard&quot;,\n      &quot;default_datetime_parser&quot;: &quot;dateTimeOptional&quot;,\n      &quot;default_field&quot;: &quot;_all&quot;,\n      &quot;default_mapping&quot;: {\n        &quot;dynamic&quot;: true,\n        &quot;enabled&quot;: false\n      },\n      &quot;default_type&quot;: &quot;_default&quot;,\n      &quot;docvalues_dynamic&quot;: false,\n      &quot;index_dynamic&quot;: true,\n      &quot;store_dynamic&quot;: false,\n      &quot;type_field&quot;: &quot;_type&quot;,\n      &quot;types&quot;: {\n        &quot;shared.docs&quot;: {\n          &quot;dynamic&quot;: true,\n          &quot;enabled&quot;: true,\n          &quot;properties&quot;: {\n            &quot;embedding&quot;: {\n              &quot;enabled&quot;: true,\n              &quot;dynamic&quot;: false,\n              &quot;fields&quot;: [\n                {\n                  &quot;dims&quot;: 1024,\n                  &quot;index&quot;: true,\n                  &quot;name&quot;: &quot;embedding&quot;,\n                  &quot;similarity&quot;: &quot;dot_product&quot;,\n                  &quot;type&quot;: &quot;vector&quot;,\n                  &quot;vector_index_optimized_for&quot;: &quot;recall&quot;\n                }\n              ]\n            },\n            &quot;metadata&quot;: {\n              &quot;dynamic&quot;: true,\n              &quot;enabled&quot;: true\n            },\n            &quot;text&quot;: {\n              &quot;enabled&quot;: true,\n              &quot;dynamic&quot;: false,\n              &quot;fields&quot;: [\n                {\n                  &quot;index&quot;: true,\n                  &quot;name&quot;: &quot;text&quot;,\n                  &quot;store&quot;: true,\n                  &quot;type&quot;: &quot;text&quot;\n                }\n              ]\n            }\n          }\n        }\n      }\n    },\n    &quot;store&quot;: {\n      &quot;indexType&quot;: &quot;scorch&quot;,\n      &quot;segmentVersion&quot;: 16\n    }\n  },\n  &quot;sourceType&quot;: &quot;gocbcore&quot;,\n  &quot;sourceName&quot;: &quot;pdf-chat&quot;,\n  &quot;sourceParams&quot;: {},\n  &quot;planParams&quot;: {\n    &quot;maxPartitionsPerPIndex&quot;: 64,\n    &quot;indexPartitions&quot;: 16,\n    &quot;numReplicas&quot;: 0\n  }\n}\n<\/code><\/pre>\n\n\n\n<h4 id=\"h-setup-environment-config\" class=\"wp-block-heading\">Setup Environment Config<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Update the <code>.env<\/code> file to include all these required variables. All configuration for communication with the database is read from the environment variables. We will revisit the environment file again to add more fields.<\/p>\n\n\n\n<pre class=\"wp-block-code language-bash\"><code>CB_CONN_STR=connection_string_for_couchbase_cluster\nCB_USERNAME=username_for_couchbase_cluster\nCB_PASSWORD=password_for_couchbase_cluster\nCB_BUCKET=name_of_bucket_to_store_documents\nCB_SCOPE=name_of_scope_to_store_documents\nCB_COLLECTION=name_of_collection_to_store_documents\nINDEX_NAME=name_of_search_vector_index\n<\/code><\/pre>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\">The <a href=\"https:\/\/docs.couchbase.com\/python-sdk\/current\/howtos\/managing-connections.html#connection-strings\">connection string<\/a> expects the <code>couchbases:\/\/<\/code> or <code>couchbase:\/\/<\/code> part. In the end, the connection string must look something like this: <code>couchbases:\/\/capella.connection.string.com<\/code>.<\/p>\n<\/blockquote>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\">For this tutorial, <code>CB_BUCKET = pdf-chat<\/code>, <code>CB_SCOPE = shared<\/code>, <code>CB_COLLECTION = docs<\/code> and <code>INDEX_NAME = pdf_search<\/code>.<\/p>\n<\/blockquote>\n\n\n\n<h4 id=\"h-configuring-aws\" class=\"wp-block-heading\">Configuring AWS<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">We need to set up our AWS Environment and run all the necessary services.<\/p>\n\n\n\n<h5 id=\"h-deploy-lambdas-to-ecr\" class=\"wp-block-heading\">Deploy Lambdas to ECR<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">We will need to use Lambdas deployed as docker container in the <a href=\"https:\/\/aws.amazon.com\/ecr\/\">AWS Elastic Container Registry Service<\/a>. We have two lambdas in the application at directory <code>src\/lambdas<\/code>. For Each of the lambdas a new ECR Repository needs to be created.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Firstly build the docker image for the two of them using <code>docker build<\/code> in the respective folder<\/p>\n\n\n\n<pre class=\"wp-block-code language-bash\"><code>docker build -t &lt;lambda name&gt; .\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Lambda name will be <code>chat<\/code> and <code>ingest<\/code> for the respective folders.\nThen use <a href=\"https:\/\/docs.aws.amazon.com\/AmazonECR\/latest\/userguide\/docker-push-ecr-image.html\">this guide from AWS<\/a> to understand how to push an image to ECR.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Once it&#8217;s pushed, we are ready for the next steps.<\/p>\n\n\n\n<h5 id=\"h-enable-bedrock\" class=\"wp-block-heading\">Enable Bedrock<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">You may need to allow access to models used in this example via <a href=\"https:\/\/console.aws.amazon.com\/bedrock\">Amazon Bedrock<\/a>. Click on get started to open Bedrock console. in the sidebar, there will be option of <code>Bedrock configurations<\/code>. Click on model access inside it. For this tutorial we are using models <code>Titan Text Embedding v2<\/code> and <code>Llama 3 70B Instruct<\/code>. You can change the lambda named chat if you need any other models. Click on modify model access and select models required. Accept terms and conditions and now the AI Model will be ready to use.<\/p>\n\n\n\n<h5 id=\"h-setup-aws-cli\" class=\"wp-block-heading\">Setup AWS CLI<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">The AWS CLI is a unified tool that provides a consistent interface for interacting with all parts of AWS. Please follow this <a href=\"https:\/\/docs.aws.amazon.com\/cli\/latest\/userguide\/getting-started-quickstart.html\">User Guide<\/a> by AWS to set up AWS on your local machine.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Please follow the next steps, once AWS is successfully configured.<\/p>\n\n\n\n<h5 id=\"h-run-aws-cloud-development-kit\" class=\"wp-block-heading\">Run AWS Cloud Development Kit<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">Run the Following Command on the root folder of the project<\/p>\n\n\n\n<pre class=\"wp-block-code language-bash\"><code>cdk deploy\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">You may enter a couple of <code>y<\/code> to approve the deployment. This step will ensure 2 AWS stacks (One for ingesting documents and other for chatting) are deployed on your AWS account. This will generate 2 API gateway endpoints. We will require these two API Gateway endpoints in the next step.<\/p>\n\n\n\n<h5 id=\"h-update-the-environment-file\" class=\"wp-block-heading\">Update the Environment File<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">We will need to update the environment file to include one more variable at the end of <code>.env<\/code> file we created at <a href=\"#setup-environment-config\">Setup Environment Config<\/a>. The variable name is <code>CHAT_URL<\/code><\/p>\n\n\n\n<pre class=\"wp-block-code language-bash\"><code>CHAT_URL=API_Gateway_Endpoint_of_CouchbaseChatStack\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This variable must have the API gateway endpoint of the CouchbaseChatStack which came as part of cdk deploy. The exact endpoint also includes <code>\/chat<\/code> so append it to the back of URL.<\/p>\n\n\n\n<h4 id=\"h-setup-couchbase-eventing\" class=\"wp-block-heading\">Setup Couchbase Eventing<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Once AWS is deployed, we will need to set up couchbase eventing function. This function will add embeddings to Couchbase Database whenever a document is added. Read more about the <a href=\"https:\/\/docs.couchbase.com\/server\/current\/eventing\/eventing-overview.html\">Couchbase Eventing Service<\/a>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">We will use import function feature of couchbase eventing. Go to eventing tab in the Web Console of Cluster. You will get an option to import function. Click on it and use upload from computer if any option is asked. There is file named <code>eventingIngest.json<\/code> present in the root folder of the project. Use this file in import. All the settings will be pre-applied. Click next.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\">We are using _default scope and _default collection for storing eventing temp files, you may use some other collection of your choice.<\/p>\n<\/blockquote>\n\n\n\n<p class=\"wp-block-paragraph\">Now, in the create bindings step, Change the <code>API_URL<\/code> variable to URL of the API gateway endpoint of <code>CouchbaseBedrockStack<\/code>. The URL should be appended with <code>\/send<\/code> to indicate exact endpoint of the function.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Once it&#8217;s updated, click next, and you can see your JS eventing function. You may add any logging or any features you may require here. The default function sends data to API gateway which inside AWS calls SQS and Lambda which will update the file with necessary embeddings.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">After saving, Deploy the created function. Now our setup process is completed with Couchbase Server and AWS Running.<\/p>\n\n\n\n<h4 id=\"h-running-the-application\" class=\"wp-block-heading\">Running the Application<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">After starting Couchbase server, adding vector search index and installing dependencies. Our Application is ready to run.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In the projects root directory, run the following command<\/p>\n\n\n\n<pre class=\"wp-block-code language-sh\"><code>streamlit run src\/ui\/streamlit_ui.py\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The application will run on your local machine at <a href=\"http:\/\/localhost:8501\">http:\/\/localhost:8501<\/a>.<\/p>\n\n\n\n<h4 id=\"h-using-pdf-chat-app\" class=\"wp-block-heading\">Using PDF Chat App<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">The page contains two areas. The top portion is an area to add PDFs. The mid and bottom area is a chat screen.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Now you may upload the PDF you want to chat about. Depending on the size of the PDF, the upload process may take some time.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Once upload is done, you can ask question related to it using bedrock. This demonstrates how the Retrieval Augmented Generation (RAG) model enhances the answers provided by the language model using the PDF content.<\/p>\n\n\n\n<h3 id=\"h-concepts\" class=\"wp-block-heading\">Concepts<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The PDF Chat application leverages two powerful concepts: <a href=\"https:\/\/aws.amazon.com\/what-is\/retrieval-augmented-generation\/\">Retrieval-Augmented Generation (RAG)<\/a> and <a href=\"https:\/\/www.couchbase.com\/products\/vector-search\/\">Vector Search<\/a>. Together, these techniques enable efficient and context-aware interactions with PDF documents.<\/p>\n\n\n\n<h4 id=\"h-retrievalaugmented-generation-rag\" class=\"wp-block-heading\">Retrieval-Augmented Generation (RAG)<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">RAG is like having two helpers:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Retriever<\/strong>: This helper looks through all the PDF documents to find the most relevant information based on your question or prompt.<\/li>\n\n\n<li><strong>Generator<\/strong>: This helper is like a large language model (e.g., GPT-4, Gemini) that can understand natural language and generate human-like responses.<\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Here&#8217;s how RAG works:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>You ask a question or provide a prompt to the app.<\/li>\n\n\n<li>The Retriever helper goes through the PDF documents and finds the most relevant passages or sections related to your question using Vector Search.<\/li>\n\n\n<li>The Generator helper takes those relevant passages and your original question, and uses them to generate a clear and contextual answer.<\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">This enhances the context from PDF and LLM is able to give relevant results from the PDF rather than giving generalized results.<\/p>\n\n\n\n<h4 id=\"h-vector-search-with-couchbase\" class=\"wp-block-heading\">Vector Search with Couchbase<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Couchbase is a NoSQL database that provides a powerful Vector Search capability. It allows you to store and search through high-dimensional vector representations (embeddings) of textual data, such as PDF content.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The PDF Chat app uses LangChain to convert the text from the PDF documents into embeddings. These embeddings are then stored in a Couchbase bucket, along with the corresponding text.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">When a user asks a question or provides a prompt:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The app converts the user&#8217;s query into an embedding using LangChain&#8217;s embedding models (e.g., OpenAI&#8217;s embeddings).<\/li>\n\n\n<li><a href=\"https:\/\/docs.couchbase.com\/python-sdk\/current\/howtos\/full-text-searching-with-sdk.html#vector-search\">Couchbase&#8217;s Vector Search<\/a> capability is utilized, which supports vector search indexes. A dedicated vector search index is created for the PDF embeddings and their corresponding text content, configured with the necessary indexing parameters (bucket, scope, collection, index name).<\/li>\n\n\n<li>The app queries this vector search index using the user&#8217;s query embedding. Couchbase&#8217;s Vector Search calculates the <a href=\"https:\/\/www.couchbase.com\/blog\/vector-similarity-search\/\">similarity<\/a> (e.g., dot product) between the query embedding and the indexed PDF embeddings, enabling fast retrieval of the nearest neighbor embeddings.<\/li>\n\n\n<li>The nearest neighbor embeddings represent the most semantically similar passages or sections from the PDF documents compared to the user&#8217;s query.<\/li>\n\n\n<li>The app retrieves the text content associated with these nearest neighbor embeddings, providing the necessary context for generating a relevant response.<\/li>\n\n\n<li>Couchbase&#8217;s Vector Search supports advanced indexing techniques, such as <a href=\"https:\/\/docs.couchbase.com\/python-sdk\/current\/howtos\/full-text-searching-with-sdk.html#scoped-vs-global-indexes\">scoped indexes<\/a>, <a href=\"https:\/\/docs.couchbase.com\/server\/current\/fts\/fts-creating-index-from-REST-dynamic.html\">dynamic indexing<\/a> and <a href=\"https:\/\/docs.couchbase.com\/python-sdk\/current\/howtos\/full-text-searching-with-sdk.html#combining-fts-and-vector-queries\">hybrid search<\/a>, allowing for efficient management, better scaling of the vector store and multiple types of search supported.<\/li>\n\n\n<li>The vector search index facilitates fast and accurate retrieval, enabling the app to provide context-aware and relevant responses to the user&#8217;s queries, even when the phrasing or terminology differs from the PDF content.<\/li>\n\n\n<li>Couchbase&#8217;s Vector Search integrates seamlessly with LangChain&#8217;s <a href=\"https:\/\/python.langchain.com\/docs\/integrations\/vectorstores\/couchbase\/\">CouchbaseSearchVectorStore<\/a> class, abstracting away the complexities of vector similarity calculations.<\/li>\n\n<\/ul>\n\n\n\n<h4 id=\"h-langchain\" class=\"wp-block-heading\">LangChain<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">LangChain is a powerful library that simplifies the process of building applications with <a href=\"https:\/\/en.wikipedia.org\/wiki\/Large_language_model\">large language models<\/a> (LLMs) and vector stores like Couchbase.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In the PDF Chat app, LangChain is used for several tasks:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Loading and processing PDF documents<\/strong>: LangChain&#8217;s <a href=\"https:\/\/python.langchain.com\/docs\/modules\/data_connection\/document_loaders\/pdf\/\"><em>PDFLoader<\/em><\/a> is used to load the PDF files and convert them into text documents.<\/li>\n\n\n<li><strong>Text splitting<\/strong>: LangChain&#8217;s <a href=\"https:\/\/python.langchain.com\/docs\/modules\/data_connection\/document_transformers\/recursive_text_splitter\/\"><em>RecursiveCharacterTextSplitter<\/em><\/a> is used to split the text from the PDF documents into smaller chunks or passages, which are more suitable for embedding and retrieval.<\/li>\n\n\n<li><strong>Embedding generation<\/strong>: LangChain integrates with <a href=\"https:\/\/python.langchain.com\/docs\/modules\/data_connection\/text_embedding\/\">various embedding models<\/a>, such as OpenAI&#8217;s embeddings, to convert the text chunks into embeddings.<\/li>\n\n\n<li><strong>Vector store integration<\/strong>: LangChain provides a <a href=\"https:\/\/python.langchain.com\/docs\/integrations\/vectorstores\/couchbase\/\"><em>CouchbaseSearchVectorStore<\/em><\/a> class that seamlessly integrates with Couchbase&#8217;s Vector Search, allowing the app to store and search through the embeddings and their corresponding text.<\/li>\n\n\n<li><strong>Chains<\/strong>: LangChain provides various <a href=\"https:\/\/python.langchain.com\/docs\/modules\/chains\/\">chains<\/a> for different requirements. For using RAG concept, we require <em>Retrieval Chain<\/em> for Retrieval and <em>Question Answering Chain<\/em> for Generation part. We also add <em>Prompts<\/em> that guide the language model&#8217;s behavior and output. These all are combined to form a single chain which gives output from user questions.<\/li>\n\n\n<li><strong>Streaming Output<\/strong>: LangChain supports <a href=\"https:\/\/python.langchain.com\/docs\/expression_language\/streaming\/\">streaming<\/a>, allowing the app to stream the generated answer to the client in real-time.<\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">By combining Vector Search with Couchbase, RAG, and LangChain; the PDF Chat app can efficiently ingest PDF documents, convert their content into searchable embeddings, retrieve relevant information based on user queries and conversation context, and generate context-aware and informative responses using large language models. This approach provides users with a powerful and intuitive way to explore and interact with large PDF files.<\/p>\n\n\n\n<h4 id=\"h-langchain-expression-language-lcel\" class=\"wp-block-heading\">LangChain Expression Language (LCEL)<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">We will now utilize the power of LangChain Chains using the <a href=\"https:\/\/python.langchain.com\/docs\/expression_language\/\">LangChain Expression Language<\/a> (LCEL). LCEL makes it easy to build complex chains from basic components, and supports out of the box functionality such as streaming, parallelism, and logging.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">LCEL is a domain-specific language that provides several key advantages when working with LangChain:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Composability: It allows you to easily combine different LangChain components like retrievers, language models, and output parsers into complex workflows.<\/li>\n\n\n<li>Readability: The syntax is concise and expressive, making it easy to understand the flow of operations within a chain or sequence.<\/li>\n\n\n<li>Reusability: You can define reusable sub-chains or components that can be incorporated into larger chains, promoting code reuse and modularity.<\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">In summary, LCEL streamlines the process of building sophisticated natural language processing applications by providing a composable, readable, reusable, extensible, type-safe, and abstracted way to define and orchestrate LangChain components into complex workflows.<\/p>\n\n\n\n<h3 id=\"h-backend-architecture\" class=\"wp-block-heading\">Backend Architecture<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><img decoding=\"async\" src=\"backend_serverless_arch.png\" alt=\"Backend Serverless Architecture\"><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">At its core, this system is designed to optimize resource usage by recognizing that PDF embedding is an intermittent task, not a constant one. By intelligently managing these occasional demands alongside on-demand chat interactions, we&#8217;ve created a solution that maintains high performance while minimizing operational costs. Let&#8217;s understand the flow.<\/p>\n\n\n\n<h4 id=\"h-ingesting-pdf-flow\" class=\"wp-block-heading\">Ingesting PDF Flow<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">This flow is marked with Uppercase English letters. We will go throw each step and what it does.<\/p>\n\n\n\n<h5 id=\"h-a--upload-file\" class=\"wp-block-heading\">A. Upload File<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">PDF File is chunked and uploaded to Couchbase Database. This is the starting step of the backend flow where the main data is added to the database. This data will be used to generate embeddings and do vector similarity search in chat part. Make sure that text is added to <code>text<\/code> field in the document.<\/p>\n\n\n\n<h5 id=\"h-b--eventing-service-in-action\" class=\"wp-block-heading\">B. Eventing Service in Action<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">The Couchbase Eventing Service makes sure that each and every added chunked file is processed. The processing happens by calling the API Gateway if embedding is not present.<\/p>\n\n\n\n<h5 id=\"h-c--send-to-queue\" class=\"wp-block-heading\">C. Send to Queue<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">All the documents are forwarded to Simple Queue Service in AWS so that if a large file is chunked, it is not rate limited by the lambda. This way all files get eventually processed and load gets handled perfectly.<\/p>\n\n\n\n<h5 id=\"h-d--ingest-lambda-is-fired\" class=\"wp-block-heading\">D. Ingest Lambda is Fired<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">Queue sends the files to the lambda. It&#8217;s the duty of the lambda to make sure that embedding for the chunk is created and sent back to couchbase.<\/p>\n\n\n\n<h5 id=\"h-e--get-embeddings-for-text\" class=\"wp-block-heading\">E. Get Embeddings for Text<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">Lambda calls AWS Bedrock service to get embedding of a particular text. Bedrock returns the result to Lambda. Here LangChain is used to generate embedding.<\/p>\n\n\n\n<h5 id=\"h-f--send-embeddings-to-couchbase\" class=\"wp-block-heading\">F. Send Embeddings To Couchbase<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">Lambda uses Couchbase Python SDK to update the corresponding Couchbase Document. Embedding is added to the Document. Here LangChain&#8217;s <code>CouchbaseSearchVectorStore<\/code> is used to abstract multiple methods.<\/p>\n\n\n\n<h4 id=\"h-chat-with-pdf-flow\" class=\"wp-block-heading\">Chat with PDF Flow<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">This flow is marked with Numbers. We will go through to each step to understand how Chat part of the application works.<\/p>\n\n\n\n<h5 id=\"h-1--ask-question\" class=\"wp-block-heading\">1. Ask Question<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">User asks the question. The question is sent to the Chat API gateway endpoint. This proxies the data to Chat Lambda which handles all the other interactions.<\/p>\n\n\n\n<h5 id=\"h-2--get-embeddings-for-question\" class=\"wp-block-heading\">2. Get Embeddings for Question<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">Here again LangChain is used. Bedrock Service is used to fetch embeddings for the question.<\/p>\n\n\n\n<h5 id=\"h-3--similarity-search\" class=\"wp-block-heading\">3. Similarity Search<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">Using Couchbase Vector Store, Similarity search is performed using the embeddings of the question. Similarity search gives the documents which are near to the question asked and may be helpful in answering the underlying question.<\/p>\n\n\n\n<h5 id=\"h-4--ask-question-from-llm\" class=\"wp-block-heading\">4. Ask Question from LLM<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">The Question is asked to the LLM provided by AWS Bedrock (Llama3 here). The context which was received from similarity search is also appended to the question of which helps in returning context rich answer.<\/p>\n\n\n\n<h3 id=\"h-important-components\" class=\"wp-block-heading\">Important Components<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">These are some important components used. We will understand how each of them works.<\/p>\n\n\n\n<h4 id=\"h-couchbase-eventing\" class=\"wp-block-heading\">Couchbase Eventing<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Couchbase Eventing is used here to check for all documents. If any new document is added, Call up the Ingest Lambda so that it can work on ingesting the PDF.<\/p>\n\n\n\n<pre class=\"wp-block-code language-js\"><code>function OnUpdate(doc, meta) {\n    if (doc.hasOwnProperty(&#039;embedding&#039;)) {\n        log(&quot;Embedding exists in the document, skipping API call.&quot;);\n        return;\n    }\n\n    \/\/ Prepare the data to send to API Gateway\n    let payload = {\n        ...doc,\n        id: meta.id,\n    };\n\n    try {\n        \/\/ Make the HTTP POST request to API Gateway\n        let response = curl(&quot;POST&quot;, apiUrl,\n            {\n                body: JSON.stringify(payload),\n                headers: {\n                    &quot;Content-Type&quot;: &quot;application\/json&quot;,\n                }\n            }\n        );\n\n        \/\/ Log the response\n        log(&quot;API Gateway response: &quot;);\n        log(response)\n    } catch (e) {\n        \/\/ Log any errors\n        log(&quot;Error calling API Gateway: &quot;);\n        log(e)\n    }\n}\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The Eventing function checks if embedding already exists. If not, it sends the curl request to the Ingest API Gateway.<\/p>\n\n\n\n<h4 id=\"h-ingest-lambda\" class=\"wp-block-heading\">Ingest Lambda<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">This lambda gets a single document at a time. Uses bedrock to get corresponding embedding vectors and then send the embeddings back to Couchbase.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s understand a bit more on the lambda function code.<\/p>\n\n\n\n<h5 id=\"h-connect-to-couchbase\" class=\"wp-block-heading\">Connect To Couchbase<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">The first step will be connecting to Couchbase. Couchbase Vector Store is required for PDF Upload as well as during chat (For Retrieval). We will use the Couchbase Python SDK to connect to the Couchbase cluster. The connection is established in the <code>connect_to_couchbase<\/code> function.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The connection string and credentials are read from the environment variables. We perform some basic required checks for the environment variable not being set in the <code>.env<\/code>, and then proceed to connect to the Couchbase cluster. We connect to the cluster using <a href=\"https:\/\/docs.couchbase.com\/python-sdk\/current\/hello-world\/start-using-sdk.html#connect\">connect<\/a> method.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>def connect_to_couchbase(connection_string, username, password):\n    try:\n        auth = PasswordAuthenticator(username, password)\n        options = ClusterOptions(auth)\n        options.apply_profile(&quot;wan_development&quot;)\n        cluster = Cluster(connection_string, options)\n        cluster.wait_until_ready(timedelta(seconds=5))\n        logging.info(&quot;Cluster is ready&quot;)\n        return cluster\n    except Exception as e:\n        logging.error(f&#039;Error while connecting: {str(e)}&#039;)\n        raise e\n<\/code><\/pre>\n\n\n\n<h5 id=\"h-get-bedrock-embeddings\" class=\"wp-block-heading\">Get bedrock embeddings<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">This part of code uses AWS SDK to get bedrock. Then initializes the embedding object. For this example we are using <code>amazon.titan-embed-text-v2<\/code> embedding model.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>from langchain_aws.embeddings import BedrockEmbeddings\n\nbedrock = boto3.client(&#039;bedrock-runtime&#039;)\ncluster = connect_to_couchbase(connection_string, username, password)\nembedding = BedrockEmbeddings(client=bedrock, model_id=&quot;amazon.titan-embed-text-v2:0&quot;)\n<\/code><\/pre>\n\n\n\n<h5 id=\"h-use-langchain-to-get-embeddings-and-store-text\" class=\"wp-block-heading\">Use LangChain to get embeddings and store text<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">LangChain has a Couchbase Vector Store support. We use this vector store to abstract out all the internals of getting the embeddings and sending it back to couchbase.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">We will use <code>add_texts<\/code> method of CouchbaseSearchVectorStore object to add text with appropriate embedding.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>from langchain_couchbase.vectorstores import CouchbaseSearchVectorStore\n\ncb_vector_store = get_vector_store(cluster, bucket_name, scope_name, collection_name, embedding, index_name)\n\nsending_text = json.loads(all_messages[0][&#039;body&#039;])[&#039;text&#039;]\nids = json.loads(all_messages[0][&#039;body&#039;])[&#039;id&#039;]\n\ncb_vector_store.add_texts([sending_text], ids=[ids])\n<\/code><\/pre>\n\n\n\n<h4 id=\"h-chat-lambda\" class=\"wp-block-heading\">Chat Lambda<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">This lambda focusses on answering a single question asked by the user. When a question is asked, this lambda uses bedrock to get appropriate embeddings for the question. Then, these embeddings are used by couchbase vector store to perform similarity search and get similar documents (Relevant Pages from the PDF) to help in answering. At the end, the question with the whole context is asked from the Bedrock&#8217;s LLM and the answer is sent back to show to the UI.<\/p>\n\n\n\n<h5 id=\"h-connect-to-couchbase-and-get-bedrock-embeddings\" class=\"wp-block-heading\">Connect to Couchbase and get bedrock embeddings<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">Similar to the last section, here again we will set up Couchbase Cluster using Python SDK and then get bedrock embeddings.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>cluster = connect_to_couchbase(connection_string, username, password)\nbedrock = boto3.client(&#039;bedrock-runtime&#039;)\nembedding = BedrockEmbeddings(client=bedrock, model_id=&quot;amazon.titan-embed-text-v2:0&quot;)\n<\/code><\/pre>\n\n\n\n<h5 id=\"h-create-vector-store-retriever\" class=\"wp-block-heading\">Create Vector Store Retriever<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">Similar to last section, We will create an object for couchbase vector store as part of langchain. However, now as we need to use Couchbase Vector Search feature, the vector store needs to act as a retriever. Therefore, Couchbase Vector Store Retriever as part LangChain Chain Expression Language (LCEL) will be used ahead.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>from langchain_couchbase.vectorstores import CouchbaseSearchVectorStore\n\nvector_store = get_vector_store(cluster, bucket_name, scope_name, collection_name, embedding, index_name)\nretriever = vector_store.as_retriever()\n<\/code><\/pre>\n\n\n\n<h5 id=\"h-langchain-chain-essentials\" class=\"wp-block-heading\">LangChain Chain Essentials<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">After the vector store, we will now set up the question. Whenever we ask questions to LLM, it&#8217;s a good practice to give some prompt to the LLM to answer more precisely.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">We will also set up the LLM itself from AWS Bedrock as part of LangChain. We are using Meta&#8217;s Llama3 70b Model here, but you may change based on your preference from bedrock.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>template = &quot;&quot;&quot;You are a helpful bot. If you cannot answer based on the context provided, respond with a generic answer. Answer the question as truthfully as possible using the context below:\n  {context}\n\n  Question: {question}&quot;&quot;&quot;\n\nprompt = ChatPromptTemplate.from_template(template)\n\naws_model_id = &quot;meta.llama3-70b-instruct-v1:0&quot;\nllm = ChatBedrock(client=bedrock, model_id=aws_model_id)\n<\/code><\/pre>\n\n\n\n<h5 id=\"h-create-and-run-chain\" class=\"wp-block-heading\">Create and run Chain<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">We will now create a single chain from all the components like retriever from Couchbase Vector Store, prompt, LLM from Bedrock and parser to parse the output as string.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">We will run(invoke) the chain and send the output back to UI through API Gateway.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>chain = (\n        {&quot;context&quot;: retriever, &quot;question&quot;: RunnablePassthrough()}\n        | prompt\n        | llm\n        | StrOutputParser()\n)\n\noutput = chain.invoke(input=question)\nprint(output)\nreturn {\n    &#039;statusCode&#039;: 200,\n    &#039;body&#039;: json.dumps(output)\n}\n<\/code><\/pre>\n\n\n\n<h4 id=\"h-streamlit-ui\" class=\"wp-block-heading\">Streamlit UI<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">We are here using UI powered by streamlit which basically tries to use API gateway endpoints to provide PDF ingestion and Chat interface.<\/p>\n\n\n\n<h5 id=\"h-pdf-uploading\" class=\"wp-block-heading\">PDF Uploading<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s start with PDF ingestion part. We use streamlit file uploader to get PDF uploaded from system. We send the PDF to temp file and use LangChain&#8217;s PyPDFLoader to process the PDF so that it becomes consistent with LangChain format.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>from langchain.document_loaders import PyPDFLoader\n\nuploaded_file = st.file_uploader(&quot;Choose a PDF file&quot;, type=&quot;pdf&quot;)\n\nif uploaded_file is not None:\n    # Create a temporary file to save the PDF\n    with tempfile.NamedTemporaryFile(delete=False, suffix=&quot;.pdf&quot;) as tmp_file:\n        tmp_file.write(uploaded_file.getvalue())\n        tmp_file_path = tmp_file.name\n\n    # Use LangChain to load and process the PDF\n    loader = PyPDFLoader(tmp_file_path)\n    documents = loader.load()\n<\/code><\/pre>\n\n\n\n<h5 id=\"h-split-documents\" class=\"wp-block-heading\">Split Documents<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">This LangChain document array will contain huge individual files which defeats the purpose while retrieval as we want to send more relevant context to LLM. So we will split it into smaller chunks or passages using LangChain&#8217;s <a href=\"https:\/\/python.langchain.com\/docs\/modules\/data_connection\/document_transformers\/recursive_text_splitter\/\"><em>RecursiveCharacterTextSplitter<\/em><\/a>:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>chunk_size: 1000: This parameter specifies that each chunk should contain approximately 1000 characters.<\/li>\n\n\n<li>chunk_overlap: 200: This parameter ensures that there is an overlap of 200 characters between consecutive chunks. This overlap helps maintain context and prevent important information from being split across chunk boundaries.<\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">At the end split_documents method splits the large document into smaller LangChain documents based on above defined parameters.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>from langchain.text_splitter import RecursiveCharacterTextSplitter\n\ntext_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)\nchunks = text_splitter.split_documents(documents)\n<\/code><\/pre>\n\n\n\n<h5 id=\"h-send-documents-to-couchbase\" class=\"wp-block-heading\">Send Documents to Couchbase<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">We then send all the documents in batches to couchbase using <code>upsert_multi<\/code> method of couchbase. Here we will need to connect to couchbase earlier. This uses same way as we did in <a href=\"#connect-to-couchbase\">Connect to Couchbase<\/a> Section.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">We use batches, here we are using batch of 100, but this may be adjusted based on requirements.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>batch_size = 100\nbatch = dict()\n# Process each chunk\nfor chunk in chunks:\n    # Call the ingest Lambda function for each chunk\n    key = f&quot;{uuid.uuid4()}&quot;\n\n    batch[key] = {\n        &quot;text&quot;: chunk.page_content\n    }\n    if len(batch) == batch_size:\n        cluster.bucket(DB_BUCKET).scope(DB_SCOPE).collection(DB_COLLECTION).upsert_multi(batch)\n        batch = dict()\n\nelse:\n    if batch:\n        cluster.bucket(DB_BUCKET).scope(DB_SCOPE).collection(DB_COLLECTION).upsert_multi(batch)\n    st.success(&quot;PDF processed and stored successfully!&quot;)\n<\/code><\/pre>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\">Note: Alternatively, <code>CouchbaseSearchVectorStore<\/code> can be used for document ingestion with embeddings, eliminating the need for serverless architecture. The eventing method described in this tutorial is preferable for existing documents or when a dedicated server isn&#8217;t used.<\/p>\n<\/blockquote>\n\n\n\n<h5 id=\"h-ask-question\" class=\"wp-block-heading\">Ask Question<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s move to Chat interface. We create a chat interface using Streamlit components. Whenever user asks a question, The question is sent to the Chat API Gateway. Read more about what the API does <a href=\"#chat-lambda\">here<\/a><\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>st.subheader(&quot;Chat with your PDF&quot;)\nuser_question = st.text_input(&quot;Ask a question about your PDF:&quot;)\n\nif user_question:\n    # Call the chat Lambda function\n    chat_response = requests.post(\n        url=CHAT_URL,\n        json={&quot;question&quot;: user_question}\n    ).json()\n    \n    st.write(&quot;Answer:&quot;, chat_response)\n<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Introduction Welcome to this comprehensive guide on constructing an AI-enhanced Chat Application. We will create a dynamic chat interface capable of going deep into PDF documents to extract and provide summaries, key facts, and answers to your queries. By the end of this tutorial, you\u2019ll have a powerful tool at your disposal, transforming the way [&hellip;]<\/p>\n","protected":false},"author":0,"featured_media":0,"menu_order":0,"template":"","meta":{"_acf_changed":false,"inline_featured_image":false,"_acf":"","footnotes":""},"tutorial-languages":[606],"tutorial-tags":[626,607,608,645,642],"tutorial-technologies":[560,548,613],"tutorial-types":[555],"class_list":["post-10345","tutorials","type-tutorials","status-publish","hentry","tutorial-languages-python","tutorial-tags-amazon-bedrock","tutorial-tags-artificial-intelligence","tutorial-tags-langchain","tutorial-tags-llama3","tutorial-tags-streamlit","tutorial-technologies-eventing","tutorial-technologies-kv","tutorial-technologies-vector-search","tutorial-types-tutorial"],"yoast_head":"<!-- This site is optimized with the Yoast SEO Premium plugin v28.8 (Yoast SEO v28.9) - https:\/\/yoast.com\/product\/yoast-seo-premium-wordpress\/ -->\n<title>Serverless PDF Chat App with Couchbase and AWS Bedrock - Couchbase<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/bedrock-serverless-pdf-chat\/\" \/>\n<meta property=\"og:locale\" content=\"de_DE\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Serverless PDF Chat App with Couchbase and AWS Bedrock\" \/>\n<meta property=\"og:description\" content=\"Introduction Welcome to this comprehensive guide on constructing an AI-enhanced Chat Application. We will create a dynamic chat interface capable of going deep into PDF documents to extract and provide summaries, key facts, and answers to your queries. By the end of this tutorial, you\u2019ll have a powerful tool at your disposal, transforming the way [&hellip;]\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/bedrock-serverless-pdf-chat\/\" \/>\n<meta property=\"og:site_name\" content=\"Couchbase\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/Couchbase\/\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.couchbase.com\/wp-content\/uploads\/2026\/10\/Cloud-2.png\" \/>\n\t<meta property=\"og:image:width\" content=\"2548\" \/>\n\t<meta property=\"og:image:height\" content=\"1171\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:site\" content=\"@couchbase\" \/>\n<meta name=\"twitter:label1\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data1\" content=\"22\u00a0Minuten\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/developers\\\/tutorials\\\/bedrock-serverless-pdf-chat\\\/\",\"url\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/developers\\\/tutorials\\\/bedrock-serverless-pdf-chat\\\/\",\"name\":\"Serverless PDF Chat App with Couchbase and AWS Bedrock - Couchbase\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/#website\"},\"datePublished\":\"2026-02-12T07:55:15+00:00\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/developers\\\/tutorials\\\/bedrock-serverless-pdf-chat\\\/#breadcrumb\"},\"inLanguage\":\"de\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.couchbase.com\\\/de\\\/developers\\\/tutorials\\\/bedrock-serverless-pdf-chat\\\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/developers\\\/tutorials\\\/bedrock-serverless-pdf-chat\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/www.couchbase.com\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Serverless PDF Chat App with Couchbase and AWS Bedrock\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/#website\",\"url\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/\",\"name\":\"Couchbase\",\"description\":\"The Operational Data Platform for AI\u2122\",\"publisher\":{\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/#organization\"},\"alternateName\":\"Couchbase, Inc.\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"de\"},{\"@type\":\"Organization\",\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/#organization\",\"name\":\"Couchbase\",\"alternateName\":\"Couchbase, Inc.\",\"url\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"de\",\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/#\\\/schema\\\/logo\\\/image\\\/\",\"url\":\"https:\\\/\\\/www.couchbase.com\\\/wp-content\\\/uploads\\\/2026\\\/11\\\/Couchbase_Logo_Couchbase_Token_Red-1.png\",\"contentUrl\":\"https:\\\/\\\/www.couchbase.com\\\/wp-content\\\/uploads\\\/2026\\\/11\\\/Couchbase_Logo_Couchbase_Token_Red-1.png\",\"width\":1129,\"height\":1129,\"caption\":\"Couchbase\"},\"image\":{\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/#\\\/schema\\\/logo\\\/image\\\/\"},\"sameAs\":[\"https:\\\/\\\/www.facebook.com\\\/Couchbase\\\/\",\"https:\\\/\\\/x.com\\\/couchbase\",\"https:\\\/\\\/www.youtube.com\\\/c\\\/CouchbaseServer\",\"https:\\\/\\\/www.linkedin.com\\\/company\\\/couchbase\\\/\",\"https:\\\/\\\/github.com\\\/couchbase\\\/\",\"https:\\\/\\\/en.wikipedia.org\\\/wiki\\\/Couchbase,_Inc.\"],\"description\":\"Couchbase is a database software company headquartered in San Jose, California, providing an operational data platform for AI used by hundreds of global enterprises.\",\"legalName\":\"Couchbase, Inc.\",\"foundingDate\":\"2011-01-01\"}]}<\/script>\n<!-- \/ Yoast SEO Premium plugin. -->","yoast_head_json":{"title":"Serverless PDF Chat App with Couchbase and AWS Bedrock - Couchbase","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/bedrock-serverless-pdf-chat\/","og_locale":"de_DE","og_type":"article","og_title":"Serverless PDF Chat App with Couchbase and AWS Bedrock","og_description":"Introduction Welcome to this comprehensive guide on constructing an AI-enhanced Chat Application. We will create a dynamic chat interface capable of going deep into PDF documents to extract and provide summaries, key facts, and answers to your queries. By the end of this tutorial, you\u2019ll have a powerful tool at your disposal, transforming the way [&hellip;]","og_url":"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/bedrock-serverless-pdf-chat\/","og_site_name":"Couchbase","article_publisher":"https:\/\/www.facebook.com\/Couchbase\/","og_image":[{"width":2548,"height":1171,"url":"https:\/\/www.couchbase.com\/wp-content\/uploads\/2026\/10\/Cloud-2.png","type":"image\/png"}],"twitter_card":"summary_large_image","twitter_site":"@couchbase","twitter_misc":{"Est. reading time":"22\u00a0Minuten"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/bedrock-serverless-pdf-chat\/","url":"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/bedrock-serverless-pdf-chat\/","name":"Serverless PDF Chat App with Couchbase and AWS Bedrock - Couchbase","isPartOf":{"@id":"https:\/\/www.couchbase.com\/de\/#website"},"datePublished":"2026-02-12T07:55:15+00:00","breadcrumb":{"@id":"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/bedrock-serverless-pdf-chat\/#breadcrumb"},"inLanguage":"de","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.couchbase.com\/de\/developers\/tutorials\/bedrock-serverless-pdf-chat\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/bedrock-serverless-pdf-chat\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.couchbase.com\/"},{"@type":"ListItem","position":2,"name":"Serverless PDF Chat App with Couchbase and AWS Bedrock"}]},{"@type":"WebSite","@id":"https:\/\/www.couchbase.com\/de\/#website","url":"https:\/\/www.couchbase.com\/de\/","name":"Couchbase","description":"The Operational Data Platform for AI\u2122","publisher":{"@id":"https:\/\/www.couchbase.com\/de\/#organization"},"alternateName":"Couchbase, Inc.","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.couchbase.com\/de\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"de"},{"@type":"Organization","@id":"https:\/\/www.couchbase.com\/de\/#organization","name":"Couchbase","alternateName":"Couchbase, Inc.","url":"https:\/\/www.couchbase.com\/de\/","logo":{"@type":"ImageObject","inLanguage":"de","@id":"https:\/\/www.couchbase.com\/de\/#\/schema\/logo\/image\/","url":"https:\/\/www.couchbase.com\/wp-content\/uploads\/2026\/11\/Couchbase_Logo_Couchbase_Token_Red-1.png","contentUrl":"https:\/\/www.couchbase.com\/wp-content\/uploads\/2026\/11\/Couchbase_Logo_Couchbase_Token_Red-1.png","width":1129,"height":1129,"caption":"Couchbase"},"image":{"@id":"https:\/\/www.couchbase.com\/de\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/Couchbase\/","https:\/\/x.com\/couchbase","https:\/\/www.youtube.com\/c\/CouchbaseServer","https:\/\/www.linkedin.com\/company\/couchbase\/","https:\/\/github.com\/couchbase\/","https:\/\/en.wikipedia.org\/wiki\/Couchbase,_Inc."],"description":"Couchbase ist ein in San Jose, Kalifornien, ans\u00e4ssiges Unternehmen f\u00fcr Datenbanksoftware, das eine operative Datenplattform f\u00fcr KI bereitstellt, die von Hunderten von globalen Unternehmen eingesetzt wird.","legalName":"Couchbase, Inc.","foundingDate":"2011-01-01"}]}},"acf":[],"permalink_manager":null,"_links":{"self":[{"href":"https:\/\/www.couchbase.com\/de\/wp-json\/wp\/v2\/tutorials\/10345","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.couchbase.com\/de\/wp-json\/wp\/v2\/tutorials"}],"about":[{"href":"https:\/\/www.couchbase.com\/de\/wp-json\/wp\/v2\/types\/tutorials"}],"version-history":[{"count":0,"href":"https:\/\/www.couchbase.com\/de\/wp-json\/wp\/v2\/tutorials\/10345\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.couchbase.com\/de\/wp-json\/wp\/v2\/media?parent=10345"}],"wp:term":[{"taxonomy":"tutorial-languages","embeddable":true,"href":"https:\/\/www.couchbase.com\/de\/wp-json\/wp\/v2\/tutorial-languages?post=10345"},{"taxonomy":"tutorial-tags","embeddable":true,"href":"https:\/\/www.couchbase.com\/de\/wp-json\/wp\/v2\/tutorial-tags?post=10345"},{"taxonomy":"tutorial-technologies","embeddable":true,"href":"https:\/\/www.couchbase.com\/de\/wp-json\/wp\/v2\/tutorial-technologies?post=10345"},{"taxonomy":"tutorial-types","embeddable":true,"href":"https:\/\/www.couchbase.com\/de\/wp-json\/wp\/v2\/tutorial-types?post=10345"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}