Concept
"RAG" stands for "Retrieval-Augmented Generation." It's a concept in natural language processing and AI, especially in generative tasks (such as text generation and chatbots).
RAG combines retrieval and generation to improve model performance and output quality. Specifically, RAG first retrieves information relevant to the input query from a large document collection, then feeds that information into a generative model (such as GPT) as context to produce more accurate, richer answers or content.
Example
from langchain_community.vectorstores import DocArrayInMemorySearch
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnableParallel, RunnablePassthrough
from langchain_openai.chat_models import ChatOpenAI
from langchain_openai.embeddings import OpenAIEmbeddings
vectorstore = DocArrayInMemorySearch.from_texts(
["harrison worked at kensho", "bears like to eat honey"],
embedding=OpenAIEmbeddings(),
)
retriever = vectorstore.as_retriever()
template = """Answer the question based only on the following context:
{context}
Question: {question}
"""
prompt = ChatPromptTemplate.from_template(template)
model = ChatOpenAI()
output_parser = StrOutputParser()
setup_and_retrieval = RunnableParallel(
{"context": retriever, "question": RunnablePassthrough()}
)
chain = setup_and_retrieval | prompt | model | output_parser
chain.invoke("where did harrison work?")
Look at the core chain in the example above:
chain = setupandretrieval | prompt | model | output_parser
We have an extra processing step, setup_and_retrieval. As the code above shows, this step also involves several additional concepts: vectorstore, embedding, and retriever. We'll unpack these one by one later.
First, look at retriever. It isn't limited to the method above; you can also invoke it directly:
retriever.invoke("where did harrison work?")
In fact, the complete chain is:
setup_and_retrieval = RunnableParallel(
{"context": retriever, "question": RunnablePassthrough()}
)
chain = setup_and_retrieval | prompt | model | output_parser
Shown as a flowchart, it looks like this:
At this point there are still a few concepts we haven't covered. Let's go through them in reverse order.
Retriever
English explanation:
The word "retriever" first appeared in the 17th century. It derives from the verb "retrieve" and originally referred to dogs specially trained to retrieve downed game birds. Later, it came to refer specifically to this breed of dog.
A retriever is an interface that returns documents based on an unstructured query. It is more general than a vector store. A retriever doesn't need to be able to store documents—it only needs to be able to return (or retrieve) them. A vector store can serve as the backbone for a retriever, but there are other types of retrievers as well.
A retriever takes a string query as input and returns a list of Document objects as output.
A general analogy: think of it like a retriever dog. We give it some signals (a string), and it brings back what we're looking for (documents).
Back to the code above: how is the retriever created?
retriever = vectorstore.as_retriever()
Vector Store
Vector store: A Vector Store, or vector database, is a database designed specifically for storing and retrieving vector data. In AI and machine learning—especially in applications such as natural language processing (NLP) and image recognition—data is often converted into high-dimensional vectors.
One of the most common ways to store and retrieve unstructured data is to embed it, store the resulting vectors, then embed an unstructured query at query time and retrieve the embedded vectors "most similar" to the query embedding. A vector store is responsible for storing the embedded data and performing vector search for you.
A general analogy: we humans have our own understanding of concepts in the world. If I say "a red floral padded jacket," an image and the object pop into our minds. If I say "a dense forest," a picture of a forest appears. To a vector database, "a red floral padded jacket" and "a dense forest" are just vectors ([0.01, 0.12,0.32]). The data retrieved through that vector is what the vector database returns in a query (that is, the image that appears in our minds).
Let's return to the code:
vectorstore = DocArrayInMemorySearch.from_texts(
["harrison worked at kensho", "bears like to eat honey"],
embedding=OpenAIEmbeddings(),
)
This creates an in-memory vector database and stores some string content in it. So what is embedding?
Embedding
The Embedding class is used to interact with text embedding models. There are many embedding model providers (OpenAI, Cohere, Hugging Face, etc.), and this class aims to provide a standard interface for all of them.
Embedding creates a vector representation of text. This is useful because it means we can think about text in vector space and perform operations such as semantic search, finding the most similar text snippets in vector space.
Put simply: There is a model that can turn text input into a set of vectors for easier storage and analysis. After text is input, it can also analyze that text to find related text.