
Large language Models are designed to understand and generate human language. These models are trained on vast amounts of data to generate a set of response tokens from input tokens. Though they have transformed areas like Content Creation, Customer Support, Translations, Document Processing, and Coding, to name a few, there remain challenges and limitations when it comes to “understanding” the language itself, especially because human language is complex, all our words are made up; there is no actual reason for an apple to be called an apple other than someone long, long ago decided it to be. In this article, we will see some of the limitations of LLMs and how we can overcome them intuitively while implementing an RAG that can search the internet, find information related to the Olympics 2024, and answer questions with exact references.
Limitations of traditional LLMs
- They cannot easily expand or change their memory. Since all the memory it has is in weights and biases, which are outputs of training the model, there is no easier way to expand or modify the existing memory.
- Without having the internal details, they can’t give us a direct way of providing insights into how they have arrived at a specific prediction.
- Another significant issue with traditional LLMs is their tendency to ‘hallucinate’. This can occur for various reasons, often related to inadequate training data, such as insufficient data, inability to verify the ground truth, or overgeneralization.
- Even the largest of language models struggle to memorize knowledge that is rarely mentioned in the training data [1].
Let’s try to solve these problems by ourselves. First, we start with a simple LLM call to which we can give an input, and it responds with appropriate output — using LangChain because it’s faster to setup, and the LLM can be replaced with any model.

# Import the AzureChatOpenAI class from the langchain_openai module
from langchain_openai import AzureChatOpenAI
# Import the load_dotenv and find_dotenv functions from the dotenv module
# These functions are used to load environment variables from a .env file
from dotenv import load_dotenv, find_dotenv
# Load the environment variables from the .env file, if it exists
load_dotenv(find_dotenv())
# Create an instance of the AzureChatOpenAI class,
# which represents a Large Language Model (LLM) from Azure OpenAI service.
# The model used is "gpt-4o" and it's using the
# preview version of the API from March 2023.
# The 'verbose' parameter enables detailed logging for debugging.
# The 'temperature' parameter is set to 1, which controls the
# randomness of the model's outputs (higher values mean more randomness).
llm = AzureChatOpenAI(
model="gpt-4o",
api_version="2023-03-15-preview",
verbose=True,
temperature=1,
)
# Invoke the LLM with a prompt of "Hi" to generate a response.
llm.invoke("Hi")To which GPT-4o responds with a pleasant greeting.
AIMessage(
content='Hello! How can I assist you today?',
additional_kwargs={},
response_metadata={
'token_usage': {
'completion_tokens': 9,
'prompt_tokens': 8,
'total_tokens': 17,
'completion_tokens_details': None,
},
'model_name': 'gpt-4o-2024-05-13',
'system_fingerprint': 'fp_67802d9a6d',
'finish_reason': 'stop',
'logprobs': None,
'content_filter_results': {},
},
id='run-160f3379-db8c-4035-af27-3678eb7edfeb-0',
usage_metadata={'input_tokens': 8, 'output_tokens': 9, 'total_tokens': 17},
)Now, let’s ask it a few questions and observe its behavior; our primary goal is to see if the limitations we outlined above are reproducible.
llm.invoke("How many medals did USA win in 2024 Olympics?")
"""
As of my knowledge cutoff in October 2023, the 2024 Summer Olympics have
not yet occurred, so I am unable to provide the number of medals the USA won.
For the most current and accurate information,
please refer to up-to-date sources such as official Olympic websites
or reputable news outlets.
"""
llm.invoke("How many medals did USA win in the most recent Olympics?")
"""
AIMessage(content='The most recent Olympics as of 2023 were the
2020 Summer Olympics held in Tokyo, which actually took place in 2021
due to the COVID-19 pandemic. The United States won a total of 113 medals
at these games: 39 gold, 41 silver, and 33 bronze.
"""
llm.invoke("Who is Shanmukha Ranganath?")
"""
As of my last update in October 2023, there is no widely known public figure
or notable individual by the name of Shanmukha Ranganath.
It's possible that this person could be a private individual or
someone who has gained recognition in a specific field or community
that is not widely covered in mainstream media or public databases.
If you have more context or specific details about Shanmukha Ranganath,
such as their profession, achievements, or the context in which you came
across the name, I might be able to provide more targeted information.
"""From the above example of inputs and outputs, we can see that the LLM’s training data is October 2023 and doesn’t know any events that occurred after that. And even though it gave correct results for our 2nd question, it doesn’t provide an easier way to check for the source where it got its facts (it could be possible if OpenAI exposes internal layer weights). Finally, when asked for my name, it couldn’t tell who I was since there wasn’t enough data for LLM to form weights.
One way to solve this problem is to provide the data necessary for LLM to extract the answers, using only the generative part of LLM by providing more inputs. Using the first part of United States at the 2024 Summer Olympics article as input along with our question:
llm.invoke("""
The United States of America (USA), represented by the United States Olympic & Paralympic Committee (USOPC),
competed at the 2024 Summer Olympics in Paris from July 26 to August 11, 2024. U.S. athletes have appeared in every
Summer Olympic Games of the modern era, except for the 1980 edition in Moscow, when America led a sixty-six-nation
boycott in protest of the Soviet invasion of Afghanistan. As Los Angeles is hosting the 2028 Summer Olympics,
the United States marched penultimately before the homebound French team entered Place du Trocadéro during the
parade of nations segment of the opening ceremony. Additionally, an American segment featuring H.E.R. and Tom Cruise from Paris,
and the Red Hot Chili Peppers, Billie Eilish, Snoop Dogg, and Dr. Dre from Long Beach, was performed during the closing ceremony.
The opening ceremony flag-bearers for the United States were LeBron James and Coco Gauff.
James, a two-time Olympic gold medalist, is the first male basketball player to be chosen.[1][2]
At 20 years of age, Gauff is the youngest American athlete and the first tennis player to be so honored.[3][4]
The closing ceremony flag-bearers were Nick Mead and Katie Ledecky.
Mead was part of the U.S. men's four rowing team that won their first gold medal since 1960, while Ledecky,
a nine-time Olympic gold medalist, became the most decorated female Olympian to be chosen.[5]
The United States competed in all sports except handball and was represented by more female than male athletes for the
fourth consecutive time in the Summer Olympics (278 men and 314 women).[6]
The team topped the medal rankings for the fourth consecutive and 19th overall time, with a total of 40 gold, 44 silver,
and 42 bronze medals.[7] Tied with China on golds (40), the U.S. placed first in the overall medal tally via a
tiebreaker (44–27 in silver). The occasion marked the first time in Summer Olympic history that two countries
finished with an equal number of gold medals at the top.[8] Additionally, the Americans won 126 medals overall
compared to China's 91.[9][10]
How many medals did USA win in the most recent Olympics?
""")
"""
The United States won a total of 126 medals at the 2024 Summer Olympics
in Paris. This included 40 gold, 44 silver, and 42 bronze medals.
"""Hurray! We just extended the memory of GPT-4o! We just learned that when we provide more context along with our question, we can put the generative capabilities of the LLM to use better, and the chances of hallucinations can also be minimized with correct prompting to trust the data source that is given. As the next step, instead of copying the paragraph from Wikipedia every time, let’s call Tavily’s search API, take the top 3 articles, and send them as input to our LLM.

import requests
import json
import os
url = "https://api.tavily.com/search"
payload = json.dumps({
"query": "How many medals did USA win in 2024 Olympics",
"api_key": os.getenv("TAVILY_API_KEY"),
"search_depth": "basic",
"topic": "general",
"include_answer": False,
"include_raw_content": False,
"include_images": False,
"include_image_descriptions": False,
"include_domains": [],
"max_results": 3,
})
response = requests.request("POST", url, data=payload)
top_results = response.json()["results"]
context = str.join("\n\n", [result['content'] for result in top_results])
llm.invoke(f"""
{context}
How many medals did USA win in the most recent Olympics?
""")
"""
At the 2024 Paris Olympics, the United States won a total of 126 medals.
This included 40 gold, 44 silver, and 42 bronze medals.
The USA led the overall medal count, followed by China with 91 medals
and Great Britain with 65 medals.
"""That is it!! We just extended our LLM’s memory, modified it according to our needs, reduced hallucinations, and finally pinpointed the sources from which it got its information. This is the idea behind RAG — Retrieval Augmented Generation. Before RAG, there existed ways to address these problems, like Memory Networks, Stack Augmented Networks, and Memory Layers, to name a few. Still, the data layer is often inside the model’s weights, requiring retraining. RAG introduces, and most importantly, a more straightforward way to enhance the memory of LLM without needing to retrain the model.
What is RAG
RAG or Retrieval Augmented Generation is a technique to enhance LLM responses by integrating relevant information from external sources, thus augmenting the model’s pre-trained, parametric memory without having the need to retrain the model itself
In simple words, RAG allows us to use external knowledge with existing models like GPT-4o without having to retrain the entire model, thus having the power of LLMs combined with the advantage of external data. It can be thought of in 3 general steps — Indexing, Retrieval, and Generation.
In fact, our above implementation is a variation of RAG known as SearchRAG. Search-RAG is an extension of RAG in which the retriever part queries using a typical search engine and passes the results to a generator. Since the retriever is a search engine, it is not limited to the knowledge base provided to traditional RAG. It can get real-time data using the internet and thus has more extensive information, including the latest updates and developments of any topic. Companies like Alphabet and Microsoft admitted that LLMs like Gemini and GPT, respectively, have long powered their search engines, Google and Bing [2].
But how do we make this work for our data, the data that is personal or company-specific and cannot be put on the internet for public use? Simple, we build our own robust internal search engine!! And I am not even kidding; the recent ideas and approaches for retrieval enhancement steps in RAG have been how search engines have evolved. From basic indexing to embeddings to semantic search to graph search, all of which are becoming a part of RAG. Let’s start with baseline RAG and see what each step is about, and finally, we’ll see what a production-ready RAG looks like.

Indexing
It can be thought of as forming a database from which documents or chunks of documents can be retrieved based on some sort of heuristic. You can think of this step as preprocessing all the data to keep it ready for the next step so that when the user query comes, we can retrieve relevant documents as soon as possible. Similar to search engines like Google or Bing, when we search for something, we get the results almost instantaneously since all the sites are preprocessed and ranked beforehand. This sort of preprocessing and ranking comes under indexing. But how does one determine whether two sentences are syntactically and semantically similar?
Numerical Representation
Like humans understand language and form complex sentences from basic words, machines must also understand those words and sentences. We teach machines this using numerical representation. This is not a new concept; these have existed long before LLMs and have been playing a significant role in NLP tasks. From statistical representations like — One-hot encoding, Bag of Words, and Word2Vec to machine-learned representations like Vector Embeddings are some of the different ways numerical representations have evolved, most of which have been powering our search engine queries for a long, long time. We shall use the OpenAI text-embedding-ada-002 model to convert our data to vectors and keep it ready to be retrieved. These vectors capture the essence of the sentences: word similarity, including semantic meaning.
from langchain_openai import AzureOpenAIEmbeddings
# A list of articles
articles = [{
'title': 'USA Olympic medal count 2024 - Sporting News',
'url': 'https://www.sportingnews.com/us/olympics/news/usa-best-olympic-medal-count-2024-paris-games-final-most-medals-all-time/0809c8a9c89cd4133bb0b281',
'content': 'The nation has ....',
}]
# Initialize an empty list to store the embeddings for each article
article_embeddings = []
# Create an instance of AzureOpenAIEmbeddings with a specific model and API version
embedding_model = AzureOpenAIEmbeddings(
model="text-embedding-ada-002-01",
api_version="2023-05-15",
)
for article in articles:
# Generate embeddings for the content of each article using the embed_query method.
# This method converts the article's content into a vector representation.
embeddings = embedding_model.embed_query(article['content'])
article_embeddings.append(embeddings)This converts the data to embeddings. These embeddings are stored in a Vector database so that when user queries, we convert the query also to vector representation and somehow find the most relevant documents.

Before we move on to how exactly we retrieve our documents, we need to talk about chunking. Though LLMs can take large inputs, there are still limits to how much input it can take and how much output it can produce, known as Context Window. So, as our documents become larger, we need to split them into smaller chunks and send only relevant chunks to our LLM. This is known as chunking. I have written an in-depth article on how to think about chunking and some implementation from scratch to help you develop the intuition behind different methods.
RAG 101: Chunking StrategiesWhy, When, and How to chunk for enhanced RAG. Build intuition to develop chunking strategies.memsranga.com
Retrieval
We’ve converted all our data to vectors, but what do these vectors mean? Graphically, each vector can be plotted in an n-dimensional space, and all the vectors that are semantically similar exist nearby in the space, i.e., at almost the same distance and direction from the origin. So, when the user queries, we convert the query to a vector and get nearby vectors using certain functions to calculate the closeness. These functions are known as similarity functions.

Similarity functions
Similarity function is a real-valued function that quantifies the similarity between two objects. Although no single definition of a similarity exists, usually such measures are in some sense the inverse of distance metrics. Cosine similarity is a commonly used similarity measure for real-valued vectors, used in (among other fields) information retrieval to score the similarity of documents in the vector space model. In machine learning, common kernel functions such as the RBF kernel can be viewed as similarity functions. [3]
Any function that computes how similar two different vectors are can be called a Similarity function. There are many strategies for performing these functions. Some common strategies are — Cosine Similarity, Euclidean Distance, KNN, and Dot Product. Though most Vector databases provide out-of-the-box implementations to use different functions when retrieving the documents, it is good to understand how each function is implemented since each function behaves differently with different types of data. The top k documents (or chunks of documents) are chosen to be inputted to the next step, which is generation.
import numpy as np
# Define a function to calculate cosine similarity between two vectors
def cosine_similarity(vec1, vec2):
# Ensure both vectors are numpy arrays
vec1 = np.array(vec1)
vec2 = np.array(vec2)
# Compute cosine similarity
cos_sim = np.dot(vec1, vec2) / (np.linalg.norm(vec1) * np.linalg.norm(vec2))
return cos_sim
query = "Olympic medal count for USA in 2024"
similarities = []
for article, article_embedding in zip(articles, article_embeddings):
similarity = cosine_similarity(query_embedding, article_embedding)
similarities.append({
'title': article['title'],
'url': article['url'],
'similarity': similarity,
})
for result in similarities:
print(f"Title: {result['title']}, Similarity: {result['similarity']:.4f}, URL: {result['url']}")
"""
Title: USA Olympic medal count 2024 - Sporting News, Similarity: 0.8754, URL: https://www.sportingnews.com/us/olympics/news/usa-best-olympic-medal-count-2024-paris-games-final-most-medals-all-time/0809c8a9c89cd4133bb0b281
Title: Olympic Games Paris 2024: All U.S. medal winners - full list, Similarity: 0.8779, URL: https://olympics.com/en/news/olympic-games-paris-2024-all-u-s-medal-winners-full-list
Title: Medal Count - Paris 2024 Olympic Medal Table, Similarity: 0.8894, URL: https://olympics.com/en/paris-2024/medals
"""Though there are multiple enhancements we could’ve done here to enhance how the documents are queried and how to rank them again after fetching, those strategies are for another article. So, the 3rd article performed better in similarity and might generate more relevant results for our query, so we chose top k (=1 in this case) to send to LLM.
Generation
This step receives the context documents from retrieval step, it combines the query, context and the prompt to send to LLMs and generate appropriate response

Beyond RAG
Though the RAG paper introduces us to a novel approach to using external knowledge in pre-trained models in 2 steps, much more is needed in real-world scenarios. The image below summarizes all the steps involved in a typical RAG flow:

Conclusion
We’ve seen how LLMs have limitations when it comes to data that it hasn’t seen and how RAG overcomes these issues, significantly reducing hallucinations and enhancing the model’s reliability without retraining. We’ve seen the steps involved in naive RAG, developed an understanding of each step, and finally saw what a production-ready RAG pipeline might look like.
🚀 Explore the code on GitHub and show your support with a ⭐ if you find it helpful! 🙌✨
References
[1] Large Language Models Struggle to Learn Long-Tail Knowledge
[2] Confirmed: the new Bing runs on OpenAI’s GPT-4
[3] Similarity Measure