RAG with Haystack and DSPy

Pipeline-based RAG with Haystack and programmatic prompt optimisation with DSPy.

Last Updated: 27, Nov 2026

Search Tutorials

--Ads--

Module 17 · Lesson 3 of 4 · Intermediate

RAG with Haystack and DSPy

Pipeline-based RAG with Haystack and programmatic prompt optimisation with DSPy.

Two more frameworks are worth knowing because they take different approaches. Haystack, by deepset, builds applications as explicit pipelines of typed components, which makes data flow easy to see and test. DSPy, from Stanford, treats prompts as parameters to be optimised rather than written by hand. This lesson shows a RAG pipeline in each.

Haystack: explicit pipelines

pip install haystack-ai anthropic-haystack sentence-transformers

In Haystack, each step is a component with named inputs and outputs, and you connect outputs to inputs explicitly. Indexing and querying are separate pipelines.

haystack_rag.py
from pathlib import Path
from haystack import Document, Pipeline
from haystack.components.builders import ChatPromptBuilder
from haystack.components.embedders import (SentenceTransformersDocumentEmbedder,
                                           SentenceTransformersTextEmbedder)
from haystack.components.retrievers.in_memory import InMemoryEmbeddingRetriever
from haystack.dataclasses import ChatMessage
from haystack.document_stores.in_memory import InMemoryDocumentStore
from haystack_integrations.components.generators.anthropic import AnthropicChatGenerator

MODEL = "BAAI/bge-small-en-v1.5"
store = InMemoryDocumentStore()

# --- Indexing ---
docs = [Document(content=p.read_text(encoding="utf-8"), meta={"file": p.name})
        for p in Path("docs").glob("*.txt")]
doc_embedder = SentenceTransformersDocumentEmbedder(model=MODEL)
doc_embedder.warm_up()
store.write_documents(doc_embedder.run(docs)["documents"])

# --- Querying ---
template = [ChatMessage.from_user("""Sources:
{% for doc in documents %}
<source file="{{ doc.meta['file'] }}">{{ doc.content }}</source>
{% endfor %}

Answer using only the sources and name the file. If they do not contain the answer, say so.
Question: {{ question }}""")]

rag = Pipeline()
rag.add_component("embedder", SentenceTransformersTextEmbedder(model=MODEL))
rag.add_component("retriever", InMemoryEmbeddingRetriever(document_store=store, top_k=3))
rag.add_component("prompt", ChatPromptBuilder(template=template, required_variables=["question", "documents"]))
rag.add_component("llm", AnthropicChatGenerator(model="claude-opus-5-5"))
rag.connect("embedder.embedding", "retriever.query_embedding")
rag.connect("retriever.documents", "prompt.documents")
rag.connect("prompt.prompt", "llm.messages")

question = "What is the hotel limit outside metro cities?"
result = rag.run({"embedder": {"text": question}, "prompt": {"question": question}})
print(result["llm"]["replies"][0].text)

Haystack pipelines can be drawn as diagrams, serialised to YAML and deployed as REST services with Hayhooks. Document stores for Elasticsearch, OpenSearch, Qdrant, Weaviate, pgvector and others replace the in-memory store without changing the rest of the pipeline. (Prompt templates use Jinja syntax, hence the double braces.)

DSPy: programming, not prompting

pip install dspy

In DSPy you declare what each LLM step should do with a signature (inputs and outputs), compose steps into modules, and let an optimiser find the instructions and few-shot examples that score best on your metric. You stop hand-tuning prompt wording.

dspy_rag.py
import json
import dspy
from retriever import DenseRetriever          # our own retriever from the top-k search lesson

records = json.load(open("index/chunks.json", encoding="utf-8"))   # chunks from Module 1
dspy.configure(lm=dspy.LM("anthropic/claude-opus-5-5", max_tokens=2000))

class AnswerFromContext(dspy.Signature):
    """Answer the question using only the context. Reply 'not found' if the context lacks the answer."""
    context: list[str] = dspy.InputField()
    question: str = dspy.InputField()
    answer: str = dspy.OutputField()

class RAG(dspy.Module):
    def __init__(self, retriever: DenseRetriever, k: int = 4):
        super().__init__()
        self.retriever, self.k = retriever, k
        self.respond = dspy.ChainOfThought(AnswerFromContext)

    def forward(self, question: str):
        context = [h.text for h in self.retriever.search(question, k=self.k)]
        return self.respond(context=context, question=question)

rag = RAG(DenseRetriever(records))
print(rag(question="How much is the home internet allowance?").answer)

Optimising the program

Give DSPy training examples and a metric; the optimiser proposes and tests instructions and demonstrations, keeping what scores best.

trainset = [
    dspy.Example(question="How many sick days do employees get?", answer="10 days per year").with_inputs("question"),
    dspy.Example(question="Which day is the default remote day for engineers?", answer="Friday").with_inputs("question"),
    # ... 20 to 200 examples from your golden test set
]

def contains_answer(example, prediction, trace=None) -> bool:
    return example.answer.lower() in prediction.answer.lower()     # replace with an LLM judge for free text

optimizer = dspy.MIPROv2(metric=contains_answer, auto="light")
optimized_rag = optimizer.compile(RAG(DenseRetriever(records)), trainset=trainset)
optimized_rag.save("optimized_rag.json")

Optimisation makes many LLM calls, so start with the "light" setting and a small training set, and keep a separate test set to confirm the improvement. DSPy calls models through LiteLLM; if a request fails because of a sampling parameter such as temperature (which current Claude models reject), check the DSPy documentation for how to stop sending it.

Comparing the frameworks

LangChain / LangGraphLlamaIndexHaystackDSPy
Core ideaComposable components and graphsData indexing and query enginesTyped, explicit pipelinesOptimised LLM programs
StrengthIntegrations and agent workflowsReady-made retrieval strategiesClarity, production deploymentSystematic prompt optimisation
Best whenBuilding varied LLM apps and agentsData-heavy RAG with many techniquesTeams wanting maintainable pipelinesYou have a metric and training data

Key takeaways

  • Haystack connects typed components into explicit indexing and query pipelines.
  • DSPy declares LLM steps as signatures and optimises their prompts against a metric.
  • Each framework suits a different style; all can implement the techniques in this tutorial.