Module 4 · Query engines

LlamaIndex Workflows: event-driven orchestration

5 min read

Query engines follow a fixed path: retrieve, then answer. But a real application needs logic: check that passages are relevant before answering, rephrase the question and retry otherwise, ask for human validation, parallelize steps. LlamaIndex Workflows let you write this logic as steps that communicate through events. They are the foundation on which LlamaIndex's agents themselves are built.

Events and steps

A workflow is a class whose @step-decorated methods receive an event and emit another:

from llama_index.core.workflow import Context, Event, StartEvent, StopEvent, Workflow, step


class RetrieveEvent(Event):
    query: str


class GradeEvent(Event):
    query: str
    nodes: list[NodeWithScore]
  • StartEvent starts the workflow, with the arguments passed to run();
  • each step declares through its type annotations the event it receives and those it can emit;
  • StopEvent ends the workflow and carries the result.

The engine infers the graph from the annotations: no edges to declare. It also checks consistency before starting: an emitted event that nobody receives, or an unreachable step, raises a validation error.

Lumen's corrective RAG workflow

StartEvent ─► start ─► retrieve ─► grade ─┬─► synthesize ─► StopEvent
                          ▲              │
                          └── (rephrase) ◄─┘  passages too weak, 2 attempts at most
class CorrectiveRAG(Workflow):
    @step
    async def start(self, ctx: Context, ev: StartEvent) -> RetrieveEvent:
        await ctx.store.set("original_query", ev.query)
        await ctx.store.set("rewrites", 0)
        return RetrieveEvent(query=ev.query)

    @step
    async def retrieve(self, ctx: Context, ev: RetrieveEvent) -> GradeEvent:
        ctx.write_event_to_stream(ProgressEvent(message=f"Recherche : {ev.query}"))
        nodes = await self.index.as_retriever(similarity_top_k=config.TOP_K).aretrieve(ev.query)
        return GradeEvent(query=ev.query, nodes=nodes)

    @step
    async def grade(self, ctx: Context, ev: GradeEvent) -> SynthesizeEvent | RetrieveEvent | StopEvent:
        relevant = [n for n in ev.nodes if (n.score or 0) >= self.min_score]
        if relevant:
            return SynthesizeEvent(query=await ctx.store.get("original_query"), nodes=relevant)
        rewrites = await ctx.store.get("rewrites")
        if rewrites >= self.max_rewrites:
            return StopEvent(result={"answer": "Je ne trouve pas cette information dans la base.",
                                     "sources": [], "rewrites": rewrites})
        await ctx.store.set("rewrites", rewrites + 1)
        new_query = (await self.llm.apredict(REWRITE_PROMPT, query=ev.query)).strip()
        return RetrieveEvent(query=new_query)

The grade step illustrates the model's strength: depending on the situation, it emits three different events. The SynthesizeEvent | RetrieveEvent | StopEvent annotation declares these three outputs, and returning to RetrieveEvent creates a loop — bounded by a counter, like any loop involving a model.

The relevance criterion here is the similarity score. A finer version would ask the fast model to judge each passage; the workflow pattern stays the same.

The context: the shared state of a run

The Context is passed to each step. Its store keeps values for the whole run: the original question (to answer the question asked, not its rephrasing), the rephrasing counter. Operations are asynchronous (await ctx.store.get(...)), because the context can be shared between steps running in parallel.

The context serializes (ctx.to_dict()) and restores: a workflow can be paused, saved, and resumed later. That's how human validations work.

Running and following a workflow

workflow = CorrectiveRAG(kb.knowledge, models.main_llm(), timeout=60)
handler = workflow.run(query="Combien coûte la livraison d'un meuble ?")
async for event in handler.stream_events():
    if isinstance(event, ProgressEvent):
        print("·", event.message)
result = await handler

run() immediately returns a handler: you can subscribe to the event stream (stream_events), then await the result. Steps publish what they want into this stream with ctx.write_event_to_stream — progress, intermediate results, tokens — for a responsive interface. The timeout parameter bounds the total duration: a workflow that loops or waits forever is interrupted.

The test_workflow_rewrites_then_gives_up test sets an unreachable threshold and checks that the workflow rephrases exactly twice, then honestly gives up, with no source.

Human in the loop

A step can suspend the workflow while waiting for an external answer:

from llama_index.core.workflow import HumanResponseEvent, InputRequiredEvent

question = InputRequiredEvent(prefix="Valider cette réponse avant envoi au client ?")
response = await ctx.wait_for_event(HumanResponseEvent, waiter_event=question)

The InputRequiredEvent appears in the stream; the application presents it to a human, then sends back the answer with handler.ctx.send_event(HumanResponseEvent(response="oui")). For a long wait, serialize the context and resume later.

Workflows or engines, workflows or LangGraph?

NeedTool
Retrieve then answerA query engine is enough
Conditional logic, loops, parallelism around RAGLlamaIndex Workflow
The model chooses its own tools and stepsAgent (lesson 5.1), itself built on workflows
State graph persisted at every step, crash recovery, time-travelLangGraph (see the dedicated course)

LlamaIndex Workflows and LangGraph solve neighboring problems with two philosophies: typed events and decoupled steps on one side, explicit state graph and checkpoints on the other. Workflows integrate naturally with LlamaIndex components; LangGraph offers more advanced persistence and recovery. The two combine: a LangGraph node can very well call a LlamaIndex engine.

Key takeaways

  • A workflow = @step steps that receive and emit typed events; the graph is inferred from annotations and validated.
  • A step can emit several event types: branches and (bounded) loops are written naturally.
  • The Context shares the run's state; it serializes to pause and resume.
  • run() returns a handler: event stream for the interface, timeout to bound the run.
  • wait_for_event suspends a step while waiting for a human.

Practice

  1. Run examples/04_workflow.py and watch the progress events for both questions.
  2. Replace the score criterion with a judgment from the fast model ("does this passage answer the question? yes/no") in the grade step.
  3. Add a human validation step before StopEvent when the question contains "remboursement".

Resources