
Day 4 -Understand Text Embeddings and Build Semantic Search with Amazon Bedrock
Explore how AI converts text into numerical vectors and build a semantic search application using Amazon Titan Text Embeddings V2
Series: 30 Days of AI Engineering on AWS (17 articles)
- …
- 5Day 4 -Understand Text Embeddings and Build Semantic Search with Amazon Bedrock This article
Welcome to Day 4 of 30 Days of AI Engineering on AWS!
So far, we've learned how to invoke foundation models, guide their responses with prompt engineering, and generate structured JSON using Amazon Bedrock.
Today, we're moving into an important concept behind modern AI search applications: Text Embeddings.
Imagine searching a knowledge base using this question:
"How can I get my money back after being charged twice?"
But the document you're looking for contains this sentence:
"Our refund policy covers duplicate transactions."
A traditional keyword search might struggle because the wording is different.
A semantic search system can identify that these sentences are related by meaning.
Let's understand how this works and build a small application using Amazon Bedrock.
1. What are text embeddings?
Text embeddings convert text into numerical representations called vectors.
Instead of representing a sentence as ordinary words, an embedding model transforms it into a list of numbers that captures semantic information.
For example:
Text:"I want to reset my password."
Embedding:[0.012, -0.034, 0.087, ...]The actual embedding contains hundreds or thousands of numbers.
Texts with similar meanings tend to have vectors that are closer together in the embedding space.
This makes embeddings useful for:
- Semantic search.
- Document retrieval.
- Recommendation systems.
- Text clustering.
- Retrieval-Augmented Generation (RAG).
An important distinction: an embedding model generates the vectors. It does not independently perform document retrieval or answer questions.
2. Understand Amazon Titan Text Embeddings V2
For this exercise, we'll use Amazon Titan Text Embeddings V2, available through Amazon Bedrock.
It is designed to generate numerical representations of text for retrieval and similarity-related applications.
Important model details:
Configuration | Value |
|---|---|
AWS service | Amazon Bedrock |
Model | Amazon Titan Text Embeddings V2 |
Model ID | amazon.titan-embed-text-v2:0 |
API | InvokeModel |
SDK | Boto3 |
Default dimensions | 1,024 |
Supported dimensions | 256, 512, 1,024 |
Maximum input | 8,192 tokens or 50,000 characters |
The model also supports normalized embeddings, which are useful when comparing vector similarity.
For today's example, we'll use 1,024 dimensions and enable normalization.
3. What are we building?
We'll build a small semantic search application for a fictional customer-support knowledge base.
Our knowledge base will contain four short documents:
- Duplicate payment and refund information.
- Password reset instructions.
- Order tracking information.
- Updating billing details.
A user will enter a natural-language question.
Our application will:
- Generate embeddings for each knowledge-base document.
- Generate an embedding for the user's query.
- Compare the query vector with the document vectors.
- Rank documents by cosine similarity.
- Display the most relevant results.
This is a small version of the retrieval process used in many RAG applications.
4. Prepare your AWS environment
We'll use Python and Boto3.
Install or upgrade Boto3:
pip install --upgrade boto3For this example, we'll use the AWS Mumbai Region:
REGION = "ap-south-1"Titan Text Embeddings V2 supports in-Region inference in Mumbai.
If you're using an Amazon Bedrock short-term API key, generate a new key after selecting
ap-south-1 in the Bedrock console. Bedrock API keys are Region-specific.Windows PowerShell:
$env:AWS_BEARER_TOKEN_BEDROCK="YOUR_API_KEY"Linux/macOS:
export AWS_BEARER_TOKEN_BEDROCK="YOUR_API_KEY"Alternatively, configure standard AWS credentials through an IAM role, AWS CLI profile, or another supported credential provider.
Your IAM identity needs permission to invoke the selected model using
bedrock:InvokeModel .5. Generate your first embedding
Create a file named:
semantic_search.py Start with the imports and AWS configuration:
import jsonimport mathimport boto3
from botocore.exceptions import ClientError, BotoCoreError
REGION = "ap-south-1"
MODEL_ID = "amazon.titan-embed-text-v2:0"
DIMENSIONS = 1024
client = boto3.client( service_name="bedrock-runtime", region_name=REGION)Now create a function to generate embeddings:
def generate_embedding(text):
if not text or not text.strip(): raise ValueError("Input text cannot be empty.")
request_body = { "inputText": text, "dimensions": DIMENSIONS, "normalize": True }
response = client.invoke_model( modelId=MODEL_ID, body=json.dumps(request_body), accept="application/json", contentType="application/json" )
response_body = json.loads( response["body"].read() )
embedding = response_body["embedding"]
if len(embedding) != DIMENSIONS: raise RuntimeError( "Unexpected embedding dimensions." )
token_count = response_body["inputTextTokenCount"]
return embedding, token_countLet's understand the important parameters:
inputText The text we want to convert into an embedding.
dimensions Controls the size of the resulting vector. Titan Text Embeddings V2 supports 256, 512, and 1,024 dimensions.
normalize Requests normalized embedding vectors, which are useful for similarity calculations.
inputTextTokenCount Reports how many input tokens were processed.
Notice that we're using
InvokeModel , not Converse . Titan Text Embeddings V2 is an embedding model, and its model card documents InvokeModel as its supported invocation API.6. Create a small knowledge base
Now let's prepare a few documents.
Add the following code:
knowledge_base = [ { "id": "DOC-001", "title": "Refund and Duplicate Payments", "content": ( "Customers who experience duplicate charges " "can contact the billing department to request " "a refund. Transactions are reviewed before " "a refund is processed." ) }, { "id": "DOC-002", "title": "Password Reset", "content": ( "Customers who cannot access their account " "can reset their password using the Forgot " "Password option on the login page." ) }, { "id": "DOC-003", "title": "Order Tracking", "content": ( "Customers can track their orders using " "the tracking number provided in their " "shipping confirmation email." ) }, { "id": "DOC-004", "title": "Update Billing Information", "content": ( "Customers can update their payment method " "and billing address from the account settings " "page." ) }]These documents are our small knowledge base.
For a real application, each document would usually be split into meaningful sections or chunks before generating embeddings.
7. Calculate cosine similarity
Generating embeddings is only one part of semantic search.
We also need a way to compare them.
A common method is cosine similarity.
It measures the cosine of the angle between two vectors.
The formula is:
[
\text{Similarity}(A,B)=
\frac{A\cdot B}{|A||B|}
]
A higher similarity score indicates that the vectors point in a more similar direction.
Let's implement it:
def cosine_similarity(vector_a, vector_b):
if len(vector_a) != len(vector_b): raise ValueError( "Embedding dimensions must match." )
dot_product = math.fsum( a * b for a, b in zip(vector_a, vector_b) )
norm_a = math.sqrt( math.fsum(a * a for a in vector_a) )
norm_b = math.sqrt( math.fsum(b * b for b in vector_b) )
if norm_a == 0 or norm_b == 0: raise ValueError( "Cannot compare a zero-length vector." )
return dot_product / (norm_a * norm_b)Because our embedding vectors are normalized, cosine similarity can also be calculated using their dot product. The implementation above uses the full formula so the comparison remains understandable and reusable.
8. Build the semantic search function
Now we'll connect everything.
Add the following function:
def semantic_search(query):
if not query or not query.strip(): raise ValueError( "Search query cannot be empty." )
document_vectors = []
total_tokens = 0
print("\nGenerating document embeddings...")
# Generate an embedding for every document for document in knowledge_base:
text = ( document["title"] + "\n" + document["content"] )
vector, tokens = generate_embedding(text)
total_tokens += tokens
document_vectors.append({ "id": document["id"], "title": document["title"], "content": document["content"], "embedding": vector })
# Generate an embedding for the search query query_vector, query_tokens = generate_embedding(query)
total_tokens += query_tokens
# Calculate similarities results = []
for document in document_vectors:
score = cosine_similarity( query_vector, document["embedding"] )
results.append({ "id": document["id"], "title": document["title"], "content": document["content"], "score": score })
# Sort from highest to lowest similarity results.sort( key=lambda item: item["score"], reverse=True )
print("\n===== SEMANTIC SEARCH RESULTS =====")
for result in results:
print("\nDocument:", result["id"]) print("Title:", result["title"])
print( "Similarity:", round(result["score"], 4) )
print("Content:", result["content"])
print("\n===== TOKEN USAGE =====") print("Total input tokens:", total_tokens)Finally, add the entry point:
if __name__ == "__main__":
query = input( "Enter your search question: " )
try: semantic_search(query)
except ClientError as error:
details = error.response.get("Error", {})
print("AWS Error:", details.get("Code")) print("Message:", details.get("Message"))
except (BotoCoreError, ValueError, RuntimeError) as error:
print("Application Error:", error)9. Run your application
Execute:
python semantic_search.pyEnter this query:
I was charged twice for my purchase.How can I get my money back?Your application should rank the duplicate-payment and refund document above the unrelated documents.
Try another query:
I cannot access my account becauseI forgot my login credentials.The password-reset document should be the most relevant result.
The exact similarity scores will depend on the model's generated vectors. Don't expect fixed numerical scores across every execution.
Important: Similarity scores are ranking signals, not probabilities or guarantees that a document contains the correct answer.
10. What did we actually build?
Let's connect the implementation to the underlying AI engineering concepts.
Component | Purpose |
|---|---|
Titan Text Embeddings V2 | Converts text into vectors |
Knowledge base | Stores the original text |
Query embedding | Represents the user's search question |
Cosine similarity | Compares vector representations |
Sorting | Ranks the most relevant documents |
We have now implemented a basic semantic retrieval pipeline.
However, this is not yet a complete RAG application.
A complete RAG pipeline also needs to retrieve relevant context and provide it to a generative model so that it can produce a grounded response.
We'll build toward that in upcoming tasks.
11. Important engineering considerations
Choose meaningful chunks.
AWS recommends splitting longer documents into logical sections or paragraphs for retrieval. A single large document may contain unrelated information that makes retrieval less useful.
Keep embedding dimensions consistent.
If you generate document vectors using 1,024 dimensions, your query vectors must use the same dimensions. Changing the model or dimensions requires an appropriate re-embedding strategy.
Understand model limitations.
Titan Text Embeddings V2 supports 100+ languages in preview and is optimized for English. AWS notes that cross-language retrieval can produce suboptimal results. Test multilingual applications with your actual content.
Don't calculate everything from scratch in production.
Our beginner example regenerates all document embeddings every time it runs. A production application should generate document embeddings during indexing, persist them, and generate only the query embedding during search.
Use an appropriate vector database.
For larger applications, use a vector database or search engine to store embeddings, retrieve nearest neighbors, and support scalable similarity search.
Monitor costs and request quotas.
Embedding models on Amazon Bedrock are throttled by requests per minute (RPM), rather than tokens per minute (TPM). Check the quotas and pricing for your selected Region before scaling the application.
12. Your Day 4 challenge
Try extending the application:
- Add five more documents to the knowledge base.
- Search using questions that don't contain the same keywords as the documents.
- Change the embedding dimensions from 1,024 to 512 and compare retrieval behavior.
- Experiment with Malayalam or Hindi queries against your knowledge base.
- Store generated embeddings in a file instead of regenerating every vector on each run.
Compare the results and observe how semantic similarity changes your search experience.
Day 4 Complete!
Today, we learned how to transform text into vector representations using Amazon Titan Text Embeddings V2.
We also implemented cosine similarity and built a small semantic search application using Python and Amazon Bedrock.
Embeddings are a fundamental building block behind semantic search, document retrieval, recommendation systems, and Retrieval-Augmented Generation.
We're now moving from basic LLM interaction toward building applications that can work with external knowledge.
30 Days. 30 Tasks. Real AI Building.
See you on Day 5!
Official References
Series: 30 Days of AI Engineering on AWS (17 articles)
- …
- 5Day 4 -Understand Text Embeddings and Build Semantic Search with Amazon Bedrock This article
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article