Skip to content

Human-in-the-Loop Workflows

Learn how to build human-in-the-loop workflows

LlamaIndex workflows support human-in-the-loop patterns where a workflow can pause, wait for human input, and then resume after the human input is received. This is useful for scenarios like:

  • Getting user approval for actions
  • Collecting additional information from users

For this to work, you need to use the withState middleware, which allows you to save the state of the workflow using the snapshot function and to resume the workflow from a saved snapshot using the resume function.

Here’s how to implement a workflow that pauses for human input:

import { createWorkflow, workflowEvent } from "@llamaindex/workflow-core";
import { createStatefulMiddleware } from "@llamaindex/workflow-core/middleware/state";
// Define events
const startEvent = workflowEvent<string>();
const humanRequestEvent = workflowEvent<void>();
const humanResponseEvent = workflowEvent<string>();
const stopEvent = workflowEvent<string>();
const { withState } = createStatefulMiddleware(() => ({}));
const workflow = withState(createWorkflow());
// Workflow that needs human input
workflow.handle([startEvent], () => {
return humanRequestEvent.with();
});
workflow.handle([humanResponseEvent], (context, event) => {
return stopEvent.with(`Human said: ${event.data}`);
});
// Usage with snapshot/resume
const { sendEvent, snapshot, stream } = workflow.createContext();
sendEvent(startEvent.with("begin"));
// Wait for a human request and take a snapshot
await stream.until(humanRequestEvent).toArray();
const snapshotData = await snapshot();
// Later (in another request): resume and provide human input
const resumedContext = workflow.resume(snapshotData);
resumedContext.sendEvent(humanResponseEvent.with("hello world"));
const events = await resumedContext.stream.until(stopEvent).toArray();
console.log(events[events.length - 1].data); // "Human said: hello world"
Note for AI agents: this documentation is built for programmatic access. - Overview of all docs: https://developers.llamaindex.ai/llms.txt - Any page is available as raw Markdown by appending index.md to its URL — e.g. https://developers.llamaindex.ai/llamaparse/parse/getting_started/index.md - Agent-friendly REST search APIs live under https://developers.llamaindex.ai/api/ — search (BM25 full-text), grep (regex), read (fetch a page), and list (browse the doc tree). See https://developers.llamaindex.ai/llms.txt for parameters. - A hosted documentation MCP server is available at https://developers.llamaindex.ai/mcp. If you support MCP, you can ask the user to install it for browsing these docs directly (an alternative to the REST API). Setup: https://developers.llamaindex.ai/for-agents/mcp/ - Other LlamaIndex tooling for agents — the LlamaParse Platform MCP server, agent skills and plugins, and the n8n node — is mapped at https://developers.llamaindex.ai/for-agents/