Skip to main content

Overview

One of the most powerful applications enabled by LLMs is sophisticated question-answering (Q&A) chatbots. These are applications that can answer questions about specific source information. These applications use a technique known as Retrieval Augmented Generation, or RAG. This tutorial will show how to build a simple Q&A application over an unstructured text data source. We will demonstrate:
  1. A RAG agent that executes searches with a simple tool. This is a good general-purpose implementation.
  2. A two-step RAG chain that uses just a single LLM call per query. This is a fast and effective method for simple queries.

Concepts

We will cover the following concepts:
  • Indexing: a pipeline for ingesting data from a source and indexing it. This usually happens in a separate process.
  • Retrieval and generation: the actual RAG process, which takes the user query at run time and retrieves the relevant data from the index, then passes that to the model.
Once we’ve indexed our data, we will use an agent as our orchestration framework to implement the retrieval and generation steps.
The indexing portion of this tutorial will largely follow the semantic search tutorial.If your data is already available for search (i.e., you have a function to execute a search), or you’re comfortable with the content from that tutorial, feel free to skip to the section on retrieval and generation

Preview

In this guide we’ll build an app that answers questions about the website’s content. The specific website we will use is the LLM Powered Autonomous Agents blog post by Lilian Weng, which allows us to ask questions about the contents of the post. We can create a simple indexing pipeline and RAG chain to do this in ~40 lines of code. See below for the full code snippet:
Check out the LangSmith trace.

Setup

Installation

This tutorial requires these langchain dependencies:
For more details, see our Installation guide.

LangSmith

Many of the applications you build with LangChain will contain multiple steps with multiple invocations of LLM calls. As these applications get more complex, it becomes crucial to be able to inspect what exactly is going on inside your chain or agent. The best way to do this is with LangSmith. After you sign up at the link above, make sure to set your environment variables to start logging traces:
Or, set them in Python:
We recommend you also set up LangSmith Engine which monitors your traces, detects issues, and proposes fixes.

Components

We will need to select three components from LangChain’s suite of integrations. Select a chat model:
👉 Read the OpenAI chat model integration docs
Select an embeddings model:
Select a vector store:

1. Indexing

This section is an abbreviated version of the content in the semantic search tutorial.If your data is already indexed and available for search (i.e., you have a function to execute a search), or if you’re comfortable with embeddings and vector stores, feel free to skip to the next section on retrieval and generation.
Indexing commonly works as follows:
  1. Load: First we need to load our data into Document objects.
  2. Split: Text splitters break large Documents into smaller chunks. This is useful both for indexing data and passing it into a model, as large chunks are harder to search over and won’t fit in a model’s finite context window.
  3. Store: We need somewhere to store and index our splits, so that they can be searched over later. This is often done using a VectorStore and Embeddings model.
index_diagram

Loading documents

We need to first load the blog post contents into a list of Document objects. We’ll use requests to fetch the page and BeautifulSoup to parse it to text. We can customize the HTML -> text parsing by passing in parameters into the BeautifulSoup parser via bs_kwargs (see BeautifulSoup docs). In this case only HTML tags with class “post-content”, “post-title”, or “post-header” are relevant, so we’ll remove all others.

Splitting documents

Our loaded document is over 42k characters which is too long to fit into the context window of many models. Even for those models that could fit the full post in their context window, models can struggle to find information in very long inputs. To handle this we’ll split the Document into chunks for embedding and vector storage. This should help us retrieve only the most relevant parts of the blog post at run time. As in the semantic search tutorial, we use a RecursiveCharacterTextSplitter, which will recursively split the document using common separators like new lines until each chunk is the appropriate size. This is the recommended text splitter for generic text use cases.
Go deeper TextSplitter: Object that splits a list of Document objects into smaller chunks for storage and retrieval.

Storing documents

Now we need to index our 66 text chunks so that we can search over them at runtime. Following the semantic search tutorial, our approach is to embed the contents of each document split and insert these embeddings into a vector store. Given an input query, we can then use vector search to retrieve relevant documents. We can embed and store all of our document splits in a single command using the vector store and embeddings model selected at the start of the tutorial.
Go deeper Embeddings: Wrapper around a text embedding model, used for converting text to embeddings. VectorStore: Wrapper around a vector database, used for storing and querying embeddings. This completes the Indexing portion of the pipeline. At this point we have a query-able vector store containing the chunked contents of our blog post. Given a user question, we should ideally be able to return the snippets of the blog post that answer the question.

2. Retrieval and generation

RAG applications commonly work as follows:
  1. Retrieve: Given a user input, relevant splits are retrieved from storage using a Retriever.
  2. Generate: A model produces an answer using a prompt that includes both the question with the retrieved data
retrieval_diagram Now let’s write the actual application logic. We want to create a simple application that takes a user question, searches for documents relevant to that question, passes the retrieved documents and initial question to a model, and returns an answer. We will demonstrate:
  1. A RAG agent that executes searches with a simple tool. This is a good general-purpose implementation.
  2. A two-step RAG chain that uses just a single LLM call per query. This is a fast and effective method for simple queries.

RAG agents

One formulation of a RAG application is as a simple agent with a tool that retrieves information. We can assemble a minimal RAG agent by implementing a tool that wraps our vector store:
Here we use the tool decorator to configure the tool to attach raw documents as artifacts to each ToolMessage. This will let us access document metadata in our application, separate from the stringified representation that is sent to the model.
Retrieval tools are not limited to a single string query argument, as in the above example. You can force the LLM to specify additional search parameters by adding arguments—for example, a category:
Given our tool, we can construct the agent:
Let’s test this out. We construct a question that would typically require an iterative sequence of retrieval steps to answer:
Note that the agent:
  1. Generates a query to search for a standard method for task decomposition;
  2. Receiving the answer, generates a second query to search for common extensions of it;
  3. Having received all necessary context, answers the question.
We can see the full sequence of steps, along with latency and other metadata, in the LangSmith trace.
You can add a deeper level of control and customization using the LangGraph framework directly—for example, you can add steps to grade document relevance and rewrite search queries. Check out LangGraph’s Agentic RAG tutorial for more advanced formulations.

RAG chains

In the above agentic RAG formulation we allow the LLM to use its discretion in generating a tool call to help answer user queries. This is a good general-purpose solution, but comes with some trade-offs: Another common approach is a two-step chain, in which we always run a search (potentially using the raw user query) and incorporate the result as context for a single LLM query. This results in a single inference call per query, buying reduced latency at the expense of flexibility. In this approach we no longer call the model in a loop, but instead make a single pass. We can implement this chain by removing tools from the agent and instead incorporating the retrieval step into a custom prompt:
Let’s try this out:
In the LangSmith trace we can see the retrieved context incorporated into the model prompt. This is a fast and effective method for simple queries in constrained settings, when we typically do want to run user queries through semantic search to pull additional context.
The above RAG chain incorporates retrieved context into a single system message for that run.As in the agentic RAG formulation, we sometimes want to include raw source documents in the application state to have access to document metadata. We can do this for the two-step chain case by:
  1. Adding a key to the state to store the retrieved documents
  2. Adding a new node via a middleware hook such as before_model to populate that key (as well as inject the context).

Security: indirect prompt injection

RAG applications are susceptible to indirect prompt injection. Retrieved documents may contain text that resembles instructions (e.g., “respond in JSON format” or “ignore previous instructions”). Because the retrieved context shares the same context window as your system prompt, the model may inadvertently follow instructions embedded in the data rather than your intended prompt.For example, the blog post indexed in this tutorial contains text describing an Auto-GPT JSON response format. If a user query retrieves that chunk, the model may output JSON instead of a natural-language answer.
To mitigate this:
  1. Use defensive prompts: Explicitly instruct the model to treat retrieved context as data only and to ignore any instructions within it. The prompts in this tutorial include such instructions.
  2. Wrap context with delimiters: Use clear structural markers (e.g., XML tags like <context>...</context>) to separate retrieved data from instructions, making it easier for the model to distinguish between them.
  3. Validate responses: Check that the model’s output matches the expected format (e.g., plain text) and handle unexpected formats gracefully.
No mitigation is foolproof — this is an inherent limitation of current LLM architectures where instructions and data share the same context window. For more on this topic, see research on prompt injection.

Next steps

Now that we’ve implemented a simple RAG application via create_agent, we can easily incorporate new features and go deeper: