LlamaIndex, Haystack and DSPy

Three tools that start from your data and your measurements rather than from a chat loop.

BeginnerIntermediateExpert · 13 min read · Last updated:

In short

LlamaIndex Workflows connects typed steps through events, which suits branching and parallel work around your data. Haystack connects typed components into pipelines and offers an agent component. DSPy lets you declare what a model step should take in and return, then tunes the prompt against a metric you provide. They can be combined, but each is worth learning on its own first.

What you will learn: the idea behind each project, five runnable examples, pausing and resuming, how to compile a program honestly, how to test retrieval and how to choose.
Prerequisites: The Agent Loop: Observe, Reason, Plan, Act, Reflect and a first understanding of retrieval.

Versions used

Checked in November 2026 and run with llama-index-workflows 2.26.1, haystack-ai 3.5.0 and dspy 3.5.0. Mock or dummy models replace real ones, and the data is a few invented sentences.

Beginner Three different starting points

What each one organizes

AspectLlamaIndex WorkflowsHaystackDSPy
UnitStep that handles an eventComponent with typed inputs and outputsModule built from a signature
WiringEvent typesExplicit connectionsOrdinary Python calls
StrengthBranching, fan-out, human inputInspectable retrieval and agent pipelinesImproving model steps against a metric
You must supplySteps and limitsComponents and storesExamples and a metric
Processwhat happens, in what order, and who approves
Retrievalfind and prepare evidence
Model stepprompt that turns evidence into an answer
Roughly where each tool concentrates: Workflows, Haystack pipelines, DSPy modules.

LlamaIndex Workflows

Workflows grew out of the LlamaIndex project into a separate package, installed as llama-index-workflows and imported as workflows. The core LlamaIndex package also exposes a version under llama_index.core.workflow. A workflow is a class whose @step methods declare, through type hints, which events they accept and emit. It begins with a StartEvent and ends with a StopEvent.

Fan out and join

This workflow looks in three sources at once and combines the findings.

import asyncio

from workflows import Context, Workflow, step
from workflows.events import Event, StartEvent, StopEvent

SOURCES = {
    "policy": "Refunds are allowed within 30 days.",
    "orders": "Order A-17 was delivered 12 days ago.",
    "tickets": "No earlier refund on A-17.",
}


class Lookup(Event):
    source: str


class Found(Event):
    source: str
    text: str


class RefundCheck(Workflow):
    @step
    async def plan(self, ctx: Context, ev: StartEvent) -> Lookup | None:
        for name in SOURCES:
            ctx.send_event(Lookup(source=name))  # fan out

    @step(num_workers=3)
    async def fetch(self, ev: Lookup) -> Found:
        await asyncio.sleep(0.01)  # a real retriever or API call
        return Found(source=ev.source, text=SOURCES[ev.source])

    @step
    async def combine(self, ctx: Context, ev: Found) -> StopEvent | None:
        results = ctx.collect_events(ev, [Found] * len(SOURCES))
        if results is None:
            return None  # still waiting for the others
        lines = sorted(f"[{r.source}] {r.text}" for r in results)
        return StopEvent(result="\n".join(lines))


async def main():
    print(await RefundCheck(timeout=10).run())


asyncio.run(main())

Output:

[orders] Order A-17 was delivered 12 days ago.
[policy] Refunds are allowed within 30 days.
[tickets] No earlier refund on A-17.

send_event starts the lookups, num_workers=3 allows them to run together, and collect_events returns nothing until all three have arrived. The result is sorted so that arrival order does not change it. If one source can fail, decide whether it returns an event that says so; otherwise the join waits until the workflow times out.

Intermediate Pauses and pipelines

Pause, save and resume

A step may emit InputRequiredEvent and a later step may accept HumanResponseEvent. The context can be turned into a dictionary, stored, and rebuilt.

import asyncio
import json

from workflows import Context, Workflow, step
from workflows.events import (HumanResponseEvent, InputRequiredEvent,
                              StartEvent, StopEvent)


class Publish(Workflow):
    @step
    async def ask(self, ctx: Context, ev: StartEvent) -> InputRequiredEvent:
        await ctx.store.set("draft", ev.draft)
        return InputRequiredEvent(prefix=f"Publish '{ev.draft}'?")

    @step
    async def decide(self, ctx: Context,
                     ev: HumanResponseEvent) -> StopEvent:
        draft = await ctx.store.get("draft")
        done = "published" if ev.response == "yes" else "discarded"
        return StopEvent(result=f"{done}: {draft}")


async def main():
    workflow = Publish(timeout=30)
    handler = workflow.run(draft="Price list v2")
    async for event in handler.stream_events():
        if isinstance(event, InputRequiredEvent):
            print("asking:", event.prefix)
            saved = json.dumps(handler.ctx.to_dict())  # store this
            await handler.cancel_run()                 # process may stop
            break

    context = Context.from_dict(workflow, json.loads(saved))
    resumed = workflow.run(ctx=context)
    resumed.ctx.send_event(HumanResponseEvent(response="yes"))
    print(await resumed)


asyncio.run(main())

Output:

asking: Publish 'Price list v2'?
published: Price list v2

The first run is canceled after its state is saved, and a second run built from the saved text finishes the job. In a real service the saved state goes into a database, the answer arrives in a separate request, and your code checks who sent it. Test a resume after redeploying, because renamed events or steps can make old state unusable.

Haystack

Haystack, from deepset, builds applications as graphs of components. Each declares typed inputs and outputs, and you connect them by name. Version 3.0, released in July 2026, moved agents to the center of the framework, added hooks that control the agent loop and first-class skills, and made the core package lighter by moving many integrations into separate packages. It includes breaking changes, so follow the migration guide from 2.x.

A small retrieval pipeline

Three documents go into an in-memory store. A keyword retriever selects two, a prompt builder inserts them, and a mock generator replies by quoting the first passage it received.

import os

os.environ["HAYSTACK_TELEMETRY_ENABLED"] = "False"

from haystack import Document, Pipeline  # noqa: E402
from haystack.components.builders import ChatPromptBuilder  # noqa: E402
from haystack.components.generators.chat import (  # noqa: E402
    MockChatGenerator)
from haystack.components.retrievers.in_memory import (  # noqa: E402
    InMemoryBM25Retriever)
from haystack.dataclasses import ChatMessage  # noqa: E402
from haystack.document_stores.in_memory import (  # noqa: E402
    InMemoryDocumentStore)

store = InMemoryDocumentStore()
store.write_documents([
    Document(content="Refunds are allowed within 30 days of delivery.",
             meta={"source": "policy.md"}),
    Document(content="Standard delivery takes five working days.",
             meta={"source": "shipping.md"}),
    Document(content="Gift cards cannot be refunded.",
             meta={"source": "giftcards.md"}),
])

template = [ChatMessage.from_user(
    "Answer from these passages only and cite the source.\n"
    "{% for d in documents %}[{{ d.meta.source }}] {{ d.content }}\n"
    "{% endfor %}Question: {{ question }}")]


def stand_in(messages):
    """Offline reply: quotes the first passage it was given."""
    return messages[-1].text.splitlines()[1]


rag = Pipeline()
rag.add_component("retriever",
                  InMemoryBM25Retriever(document_store=store, top_k=2))
rag.add_component("prompt", ChatPromptBuilder(
    template=template, required_variables=["documents", "question"]))
rag.add_component("llm", MockChatGenerator(response_fn=stand_in))
rag.connect("retriever.documents", "prompt.documents")
rag.connect("prompt.prompt", "llm.messages")

question = "How many days do I have to ask for refunds?"
out = rag.run({"retriever": {"query": question},
               "prompt": {"question": question}},
              include_outputs_from={"retriever"})
for doc in out["retriever"]["documents"]:
    print("retrieved:", doc.meta["source"])
print("reply:", out["llm"]["replies"][0].text)

try:
    rag.connect("retriever.documents", "llm.messages")
except Exception as error:
    print("wiring rejected:", type(error).__name__)

Output:

retrieved: policy.md
retrieved: shipping.md
reply: [policy.md] Refunds are allowed within 30 days of delivery.
wiring rejected: PipelineConnectError

Two behaviors are worth noticing. The second retrieved document is about delivery and is not helpful, which a larger test set would count against retrieval quality. And connecting documents straight to the model's message input is rejected when the pipeline is wired, before anything runs. include_outputs_from exposes an intermediate result so that you can inspect or assert it.

The agent component and hooks

Haystack's Agent takes a chat generator and tools and loops until an exit condition is met.

import os

os.environ["HAYSTACK_TELEMETRY_ENABLED"] = "False"

from haystack.components.agents import Agent  # noqa: E402
from haystack.components.generators.chat import (  # noqa: E402
    MockChatGenerator)
from haystack.dataclasses import ChatMessage, ToolCall  # noqa: E402
from haystack.tools import tool  # noqa: E402


@tool
def stock_level(sku: str) -> str:
    """Return the units in stock for one product code."""
    return {"KT-2": "4"}.get(sku, "unknown product")


model = MockChatGenerator(responses=[
    ChatMessage.from_assistant(tool_calls=[
        ToolCall(tool_name="stock_level", arguments={"sku": "KT-2"})]),
    "There are 4 units of KT-2.",
])
agent = Agent(chat_generator=model, tools=[stock_level],
              max_agent_steps=4)
result = agent.run(messages=[ChatMessage.from_user("Stock of KT-2?")])

for message in result["messages"]:
    if message.tool_calls:
        print("call:", message.tool_calls[0].tool_name)
    elif message.tool_call_results:
        print("result:", message.tool_call_results[0].result)
    else:
        print(f"{message.role.value}: {message.text}")
print("steps:", result["step_count"], "| exit:", result.get("exit_reason"))

Output:

user: Stock of KT-2?
call: stock_level
result: 4
assistant: There are 4 units of KT-2.
steps: 2 | exit: text

The result reports the messages, the number of steps and why the loop ended, which is worth logging for every run. The default step limit in this version is 100, so set max_agent_steps far lower for most tasks. Hooks run at defined points in the loop; the package includes ones for human confirmation and for budgets. Pipelines can be serialized, which helps review and deployment; load serialized definitions only from sources you trust.

Choose a pipelineChoose an agent
Steps are the same for every requestThe number of searches depends on what is found
Cost must be predictableSome extra calls are acceptable
Each stage is evaluated separatelySuccess is judged on the end result
Expert Optimizing and operating

DSPy

DSPy treats a prompt as something to be built from a description and tuned with data. A signature names inputs and outputs. A module such as Predict, ChainOfThought or ReAct decides how the model is asked. An optimizer changes the instructions or examples so that a metric scores better.

import dspy
from dspy.utils import DummyLM


class Route(dspy.Signature):
    """Choose the support queue for a customer message."""

    message: str = dspy.InputField()
    queue: str = dspy.OutputField(desc="billing, shipping or other")


def exact(example, prediction, trace=None):
    return example.queue == prediction.queue


def example(message, queue):
    return dspy.Example(message=message, queue=queue).with_inputs("message")


train = [example("I was charged twice", "billing"),
         example("My parcel has not arrived", "shipping")]
dev = [example("Refund has not reached my card", "billing"),
       example("Tracking page shows nothing", "shipping"),
       example("Do you have a shop in Leeds?", "other")]

# Offline stand-in: it replays these answers whatever the prompt says,
# so the score shows the mechanics, not the quality of a model.
lm = DummyLM({
    "Refund has not reached my card": {"queue": "billing"},
    "Tracking page shows nothing": {"queue": "shipping"},
    "Do you have a shop in Leeds?": {"queue": "shipping"},
})
dspy.configure(lm=lm)

program = dspy.Predict(Route)
evaluate = dspy.Evaluate(devset=dev, metric=exact, num_threads=1,
                         display_progress=False)
print("score:", evaluate(program).score)

compiled = dspy.LabeledFewShot(k=2).compile(program, trainset=train,
                                            sample=False)
print("examples added to the prompt:", len(compiled.demos))
compiled(message="Tracking page shows nothing")
for message in lm.history[-1]["messages"]:
    first = str(message["content"]).replace("\n", " ")[:60]
    print(f"{message['role']:9} {first}")
print("saved state holds:", sorted(compiled.dump_state()))

Output:

score: 66.67
examples added to the prompt: 2
system    Your input fields are: 1. `message` (str): Your output field
user      <message> I was charged twice </message>
assistant <queue> billing </queue>
user      <message> My parcel has not arrived </message>
assistant <queue> shipping </queue>
user      <message> Tracking page shows nothing </message>  Output for
saved state holds: ['demos', 'lm', 'signature', 'traces', 'train']

The score is two out of three because the dummy model was told to get the third case wrong. LabeledFewShot then added two training examples to the prompt, which you can see as earlier user and assistant messages. No quality gain is shown or claimed here: a dummy model cannot improve. With a real model you would measure the compiled program on examples it never saw.

Choosing an optimizer

OptimizerWhat it changesNeeds
LabeledFewShotAdds labeled examplesA few good examples
BootstrapFewShotCollects examples from runs that pass the metricA metric and a model to run
MIPROv2Searches instructions and examplesMore data and many calls
GEPARevises instructions using written feedbackA metric that can explain failures

Optimization spends model calls, sometimes a great many. Set a budget, keep separate training, validation and final test sets, and stop reusing the final set once it has influenced a decision.

A metric gets exactly what it rewards

If the metric checks only that an answer contains a keyword, optimization will find prompts that produce the keyword. Review failures and successes by hand, include cases where the right behavior is to refuse, and watch cost and length as well as score.

Upgrading to 3.5

The 3.5 release notes say it changes prompts, defaults and APIs, and ask users to re-evaluate optimized programs. dspy.ReAct now provides what was previewed as the newer ReAct version, and RLM, Flex and GEPA are no longer marked experimental. Treat a saved, compiled program as tied to the library version, model and data that produced it, and record all three.

Measuring retrieval

Whichever tool you use, a model cannot cite a passage it never received. Build a list of questions, mark which documents answer each, and measure retrieval before judging generated text.

MeasureQuestion it answersIllustration with two results returned
Recall at kDid we get the documents that were needed?One needed document, found: 1 of 1
Precision at kHow much of what we got was useful?One useful of two returned: 0.5
Rank of first useful resultHow near the top is it?Found first: rank 1

The illustration matches the pipeline above: the refund policy was needed and came first, and the delivery passage was extra. Three documents make this trivial, so a real test needs near-duplicates, outdated versions, questions with no answer in the store and users with different permissions. Change one setting at a time, such as chunk size, retriever or number of results, and rerun the same list.

Include unanswerable questions

A system that always returns something invites the model to answer from weak evidence. Decide what should happen when nothing relevant is found, and test that the application says so.

Combining them

A reasonable division is a workflow for the process, a pipeline or retriever for evidence and an optimized module for the one step whose quality you can measure. Each boundary should pass plain data, so that any part can be replaced.

  • One component owns the state of a run
  • Retry rules exist in one place, to avoid multiplied retries
  • Traces from all parts share a run identifier
  • Dependencies are locked together and upgraded one at a time

Testing and operating

LevelWhat to check
Component or stepExact behavior with fixed input
RetrievalWhether needed passages are in the results, per question
GenerationWhether claims are supported by the passages
Whole processEnd state, approvals, cost and time

Filter by the user's permissions inside retrieval, not in the prompt: a model should never receive a passage the user may not read. Retrieved text may also contain instructions planted by someone else, so treat it as data and restrict what the following step can do. Haystack collects anonymous usage telemetry unless it is disabled; the example turns it off through an environment variable.

Common mistakes

MistakeBetter practice
Tuning prompts before measuring retrievalFix missing evidence first
Joins with no failure eventReport failures as events and set timeouts
Optimizing and testing on the same dataHold out a final set
Default agent step limitsSet a small limit that suits the task
Copying 2.x Haystack code into 3.xFollow the migration guide
Adopting all three at onceAdd each when a need appears

Checklist

  • The tool chosen matches the problem: process, pipeline or prompt quality
  • Saved workflow state is stored securely and tested across releases
  • Retrieval is evaluated on its own
  • Permissions are applied before text reaches the model
  • Optimized programs record version, model, data and score
  • Telemetry settings are deliberate

Frequently asked questions

Is Workflows the same as LlamaIndex?

No. LlamaIndex is a wider set of data tools. Workflows is its event-driven orchestration library and can be installed alone.

Does DSPy replace prompt writing?

It changes the work. You still state the task clearly, choose examples and define the metric. The optimizer searches within what you give it.

Can Haystack use a vector database?

Yes, through document store integrations. The in-memory store here is for learning and small tests.

Which should I learn for document question answering?

Any pipeline tool will teach the stages. Learn to measure retrieval and answer support first, then pick the tool your team can operate.

References and further reading

Next steps