Overview

9 Creating an agentic RAG-based chatbot

This chapter brings together several of DSPy’s most practical building blocks to show how they combine into realistic assistant systems. It moves from simple question answering toward more capable chatbots that can retrieve outside information, take actions with tools, remember past exchanges, and improve their own outputs. Using the WixQA dataset as a running example, the chapter illustrates how DSPy can be used to build customer-support style applications that are grounded in a company knowledge base rather than the model’s training data alone.

The first major focus is retrieval-augmented generation. The chapter shows how to embed knowledge-base article titles, store them in a vector retriever, and pass the most relevant articles to an LM so it can answer domain-specific questions. It then extends this baseline with evaluation using a judge model, followed by more advanced retrieval strategies such as multihop search and HYDE, which generate better search terms or hypothetical documents to improve recall. These methods are presented as practical ways to reduce retrieval failures and improve answer quality when a single retrieval pass is not enough.

The second half of the chapter shifts to agents, memory, and system integration. It explains ReAct as a reasoning-and-action loop where the LM chooses tools, observes results, and iterates until it can answer or act successfully. Examples include a calculator agent, an agentic RAG workflow that retrieves and reads knowledge-base articles as needed, and a memory-enabled chatbot that uses conversation history to handle follow-up questions naturally. The chapter closes by showing how DSPy agents can connect to external services through MCP, and how DSPy’s Refine module can repeatedly improve answers by scoring and retrying them, making the overall chatbot stack more robust and flexible.

The two main stages of RAG: retrieval and generation. During the retrieval stage, we're searching for documents that are most similar to the query. Once we have these, we can prepare the prompt by injecting the top-k results along with the user query as input for the generation stage. The LM is then able to generate a grounded answer based on these documents. If requested, it may also quote the source documents.
Transforming article titles to vectors through an embedder model. The input for the embedder is text, and the output is an n-dimensional vector.
Creating a vector store from the article titles. We vectorize each article title with an embedder and save its vector into a database-like structure.
In the ReAct cycle, we split the solution of complex problems into iterations. Each iteration starts with a thought step (similar to the thoughts in Chain of Thought), which leads to the LM choosing an action. The action is then executed, and its outcome is added to the chat history. This is used in the next cycle of ReAct, where the LM determines the next action to take. This continues until either the LLM decides it can finish the task, or it reaches a maximum number of iterations. In this figure, the LM is responsible for the Reason and Act steps, while the other steps are initiated by the user or the ReAct module.
During the agent’s initialization, it connects to the set of MCP servers that may be used by the host, creating a pool of MCP clients to communicate with these. Whenever the agent chooses to execute an MCP-based tool, the appropriate MCP client communicates with its server, passing the necessary arguments and collecting the tool’s output.

Summary

  • DSPy provides support for creating RAG-based applications, including providing infrastructure for working with vector stores and performing embedding-based search.
  • DSPy RAG modules can be evaluated and optimized similarly to other DSPy modules.
  • DSPy also provides a built-in ReAct module, which allows us to create agents that can reason and act.
  • Using ReAct, users provide a set of tools wrapped in Python functions. The LM will choose which of these tools to use to complete the query.
  • Where the LMs choose to use a tool, DSPy will also have them specify the parameters to be used.
  • When using ReAct, DSPy tracks trajectories: histories of the reasoning, the tools selected, and outputs from the tool executions.
  • Each iteration, ReAct uses the trajectories created so far to help it determine which tool to call next.
  • When put in a long-running loop, this framework allows us to create an always-available agent.
  • Chatbots can be implemented with a ReAct pattern as well as a RAG pattern. We often combine these.
  • DSPy supports memory, which allows us to create applications that can maintain conversations over any number of queries.
  • The MCP protocol allows agents to retrieve tool definitions from remote MCP servers. The execution of the tool will happen in a remote machine.
  • MCP protocol defines hosts, clients and servers.
  • DSPy supports creating MCP hosts (applications that use MCP tools) and MCP Servers (applications that provide and execute the MCP tools).

FAQ

What is the main goal of chapter 9, “Creating an agentic RAG-based chatbot”?The chapter shows how to build more realistic DSPy applications by combining retrieval-augmented generation (RAG), agents using ReAct, long-running conversation memory, and supporting tools. The result is a full-featured chatbot that can answer questions from a knowledge base, act with tools, and remember past interactions.
What problem does RAG solve in a chatbot?RAG helps a language model answer questions that depend on information it did not learn during training. It does this by retrieving relevant documents from a knowledge base and supplying them as context so the model can generate a grounded answer.
What is the WixQA dataset used for in this chapter?WixQA provides customer questions, expert-written answers, and knowledge-base articles from Wix. The chapter uses it to build and evaluate RAG systems by comparing retrieved documents and generated responses against the provided gold answers.
How does the baseline DSPy RAG module work?The baseline RAG module first retrieves the most relevant knowledge-base articles for a question, then passes those articles and the question to a language model. The model uses that context to generate the final response.
Why does the chapter use embeddings and a vector store for retrieval?Embeddings convert text into vectors so similar questions and article titles are close in vector space. A vector store lets DSPy search for the most similar titles quickly and return the top-k matches for use in generation.
What is the purpose of the factuality judge in the RAG evaluation?The factuality judge compares the AI response with the expert ground-truth answer and scores how well the important information is preserved. This provides an LLM-as-a-Judge metric for evaluating how factually aligned the RAG output is.
What are the two common sources of error in a RAG application?First, the retriever may fail to find the documents needed to answer the question. Second, even if relevant documents are retrieved, the language model may still generate an incorrect or misleading answer because of prompt or generation issues.
What is agentic RAG, and how is it different from basic RAG?Agentic RAG uses an agentic loop, such as ReAct, to retrieve information iteratively instead of only once. The agent can reason about what to search next, call tools multiple times, inspect results, and continue until it has enough evidence to answer well.
How does DSPy use memory for long-running conversations?DSPy can pass conversation history into the model so later responses can depend on earlier exchanges. This helps resolve references like “that” or “the previous one,” and it can also preserve user-specific context across turns or sessions.
How does the chapter connect DSPy agents to MCP?The chapter shows how to expose Wix knowledge-base actions through an MCP server and then connect a DSPy ReAct agent to those tools as an MCP client. DSPy discovers the server’s tools at runtime, converts them to DSPy tools, and uses them inside the agent loop.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Building LLM Applications with DSPy ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Building LLM Applications with DSPy ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Building LLM Applications with DSPy ebook for free