AWS Builder Center
Build a Repeatable RAG Pipeline with Amazon OpenSearch, AWS Bedrock, DeepSeek-R1, and S3

Build a Repeatable RAG Pipeline with Amazon OpenSearch, AWS Bedrock, DeepSeek-R1, and S3

Retrieval-augmented generation (RAG) is one of the most practical ways to make a large language model useful with private and domain-specific data.

Senior Technical Architect | AWS Community Builder
Retrieval-augmented generation (RAG) is one of the most practical ways to make a large language model useful with private, domain-specific, or frequently changing information. Instead of relying only on the model’s training data, a RAG application retrieves relevant passages from an external knowledge source and supplies them as context for the model’s answer.
Many RAG tutorials successfully demonstrate the concept but leave several operational questions unanswered: How do you recreate the environment consistently? How do you separate deployment permissions from model-invocation permissions? How do you prove which documents were retrieved? And how do you remove the resources safely after a workshop or proof of concept?
To address those questions, I converted the OpenSearch DeepSeek-R1 RAG tutorial into a repeatable AWS deployment. The project provisions the core infrastructure with AWS CloudFormation, configures OpenSearch programmatically, uploads and indexes sample documents, invokes DeepSeek-R1 through Amazon Bedrock, records the retrieval evidence, and provides a clean-up workflow.

What the solution builds

The end-to-end flow is shown below:

Amazon S3 is the source of truth for the documents. Amazon Titan Text Embeddings V2 converts both the documents and the user’s question into normalised 1,024-dimensional vectors. Amazon OpenSearch Service stores those vectors in a k-NN index and retrieves the most relevant documents using approximate nearest-neighbour search. An OpenSearch search pipeline then supplies the retrieved text to DeepSeek-R1 on Amazon Bedrock and returns the search hits, source locations, and generated answer in one response.

Why make the tutorial repeatable?

A manual tutorial is useful for learning individual steps, but a repeatable deployment is better for demonstrations, workshops, testing, and team handovers.
The  repository  separates the workflow into four clear activities:
./scripts/deploy.sh
python3 scripts/run_lab.py
./scripts/status.sh
./scripts/cleanup.sh

The deployment script creates the AWS resources. The Python lab script configures the OpenSearch ML connector, model registration, vector index, search pipeline, document ingestion, and test query. The status script provides the CloudFormation state and outputs, while the clean-up script empties the S3 bucket and deletes the stack.
This structure makes the demonstration easier to reproduce and reduces the risk of missing a configuration step between environments.

Infrastructure provisioned with CloudFormation

The CloudFormation template creates:
  • An encrypted and versioned Amazon S3 bucket with public access blocked.
  • An Amazon OpenSearch Service domain running OpenSearch 2.19.
  • Encryption at rest, node-to-node encryption, HTTPS enforcement, and TLS 1.2.
  • Fine-grained access control using the deploying IAM principal as the master user.
  • A Bedrock invocation role that OpenSearch can assume.
  • A separate connector-signing role used to register the OpenSearch ML connector.
For cost-conscious labs, the domain uses one t3.small.search node with 10 GiB of gp3 storage. This is intentionally a demonstration topology rather than a production architecture.
The deployment script derives the current AWS account, caller ARN, Region, domain name, stack name, and bucket name. It then deploys the template with named IAM capabilities and prints the resulting CloudFormation outputs.

Separating connector creation from model invocation

One of the most important design choices is the separation of IAM responsibilities. The Bedrock invocation role trusts the OpenSearch service and grants permission to invoke only the DeepSeek-R1 inference profile and foundation model.
The connector-signing role is assumed by the deployment identity. It can pass only the Bedrock invocation role and can send the required HTTP POST request to the specified OpenSearch domain. Inside OpenSearch, the connector-signing role is mapped to the ml_full_access backend role. The automation performs a read-merge-write operation when updating this role mapping, preserving any existing users, hosts, and backend roles rather than overwriting them.
This separation prevents the identity that registers the ML connector from automatically inheriting broad model invocation permissions. It also makes the authorisation path easier to explain and audit.

Configuring DeepSeek-R1 through an OpenSearch connector

The Python automation creates an OpenSearch ML connector that invokes DeepSeek-R1 through the Amazon Bedrock Runtime API.
The current Bedrock contract is important here. The implementation uses the US cross-region inference profile:
us.deepseek.r1-v1:0
It also uses the max_tokens request property and extracts generated text from choices[0].text.
The script first performs a small direct invocation that asks the model to reply with READY. This fail-fast check confirms that the current AWS identity and Region can invoke the model before the script continues with the more involved OpenSearch configuration.
After creating the connector, the script registers a remote model in OpenSearch and waits for the asynchronous model registration and deployment tasks to complete.

Building the vector index and RAG search pipeline

The OpenSearch index stores three fields:
  • text: the original document text.
  •  source:  the S3 URI used for provenance.
  •  embedding:  a 1,024-dimensional  knn_vector. 
The vector field uses the Lucene engine, HNSW indexing, and cosine similarity.
The automation also creates an OpenSearch search pipeline containing a  retrieval_augmented_generation  response processor. The processor is configured with the deployed model ID and the document text field as context. Its system prompt instructs the model to use only the supplied search results and to state when the answer is not present.
The user instruction requests a concise response and asks the model to show its arithmetic.
These instructions are useful for demonstrations because they make grounding visible and reduce the chance of an unsupported answer.

Uploading, embedding, and indexing documents

The ingestion stage reads each .txt file in the local data directory and uploads it to the encrypted S3 bucket under the documents/ prefix.
For each document, the script:
1.   Reads the object from S3.
2.   Generates an embedding with Amazon Titan Text Embeddings V2.
3.   Creates a stable document ID from the S3 key.
4.    Indexes the text, S3 URI, and vector in OpenSearch.
The same embedding model and vector configuration are then used for the user’s question. OpenSearch retrieves the top three nearest documents and sends them through the RAG search pipeline.

Preserving evidence of retrieval and generation

A useful RAG demonstration should show more than the final answer. It should also show what was retrieved and where it came from.
The project writes the complete result to l ab-output.json . The output includes:
  • The original question.
  • The OpenSearch connector and model IDs.
  • The S3 bucket and OpenSearch endpoint.
  • The retrieved document text.
  • The S3 URI for each retrieved document.
  • The generated RAG answer.
This makes the lab output suitable for presentation evidence, troubleshooting, and discussions about answer grounding.
The sample question compares population changes for New York City and Miami. The expected response requires both retrieval and arithmetic, making it a useful test of whether the model is using the indexed material rather than producing a generic answer.

Running the project

Before starting, ensure that you have:
  • An AWS account and credentials configured for the AWS CLI.
  • Permission to deploy CloudFormation, IAM, S3, OpenSearch, and Bedrock resources.
  • Python 3 with the project dependencies installed.
  • Access to Amazon Titan Text Embeddings V2 and DeepSeek-R1 in the selected region and inference profile.
Install the Python dependencies:
 python3 -m pip install -r requirements.txt 
Deploy the infrastructure:
 ./scripts/deploy.sh 
Run the complete lab:
 python3 scripts/run_lab.py 
You can override the default question:
 python3 scripts/run_lab.py --question "What information can be derived from the indexed documents?" 
Check the stack:
 ./scripts/status.sh 
When the lab is complete, remove the billable resources:  ./scripts/cleanup.sh 

Moving from a lab to production

The repository is intentionally optimised for a short-lived demonstration. A production implementation should extend it in several areas.
First, place the OpenSearch domain in a VPC and use a Multi-AZ topology with multiple data nodes and, where appropriate, dedicated cluster-manager nodes. Add monitoring, alarms, snapshots, capacity planning, and tested recovery procedures.
Second, replace whole-document indexing with a chunking strategy that preserves document, section, page, tenant, and access-control metadata. Use event-driven ingestion for new, updated, and deleted S3 objects, and make the processing idempotent.
Third, enforce user authorisation before retrieval. A RAG system must not return a semantically relevant document that the requesting user is not permitted to access. Apply tenant, role, or document-level filters as part of the retrieval query.
Finally, evaluate retrieval quality separately from answer quality. Measure whether the correct passages were retrieved, whether the answer is supported by those passages, and whether the system refuses questions that are outside the indexed knowledge. Add Bedrock Guardrails, prompt-injection defences, application logging, token and latency monitoring, and cost controls.

Conclusion

This project demonstrates how Amazon S3, Amazon Titan Text Embeddings V2, Amazon OpenSearch Service, and DeepSeek-R1 on Amazon Bedrock can work together in a transparent RAG pipeline.
The main value is not only the generated answer. It is the repeatable operating model around it: infrastructure as code, scoped IAM roles, programmatic OpenSearch configuration, source provenance, saved evidence, and a reliable clean-up path.
That combination makes the repository useful for AWS workshops, technical presentations, proof-of-concept environments, and teams that want to understand the mechanics behind a grounded generative AI application before designing a production-scale platform.

Resources

  • Click  here  to watch related video to this topic
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article