> ## Documentation Index
> Fetch the complete documentation index at: https://docs.swarms.world/llms.txt
> Use this file to discover all available pages before exploring further.

# GraphWorkflow Guide

> Build a dependency graph of agents: fan out to parallel specialists, fan back in to one writer, check the graph, follow each node with callbacks, and refine over several loops

A `GraphWorkflow` runs agents as the nodes of a directed graph. An edge from A to B means B waits for A and receives A's output. The workflow sorts the graph into layers: every node in a layer runs at the same time, and a layer starts only when the one before it has finished. `run()` returns a dict with every node's output, keyed by node id.

Reference: [GraphWorkflow](https://docs.swarms.world/api/graph-workflow.md).

## 1. Fan out and fan back in

Add each agent with `add_node()`; its `agent_name` becomes its node id. `add_edges_from_source()` sends one node's output to several nodes (fan-out), and `add_edges_to_target()` collects several nodes' outputs into one (fan-in).

```python theme={null}
from swarms import Agent, GraphWorkflow


def make_agent(name: str, system_prompt: str) -> Agent:
    """Build a one-loop agent on a small model."""
    return Agent(
        agent_name=name,
        system_prompt=system_prompt,
        model_name="gpt-5.4-mini",
        max_loops=1,
    )


collector = make_agent("Collector", "List the five most important facts about the topic, one line each.")
tech = make_agent("Tech-Analyst", "Assess the technical side of the facts in under 80 words.")
market = make_agent("Market-Analyst", "Assess the market side of the facts in under 80 words.")
writer = make_agent("Writer", "Combine the analyses into a three-sentence summary.")

workflow = GraphWorkflow(name="Market-Brief")
for agent in [collector, tech, market, writer]:
    workflow.add_node(agent)

workflow.add_edges_from_source("Collector", ["Tech-Analyst", "Market-Analyst"])
workflow.add_edges_to_target(["Tech-Analyst", "Market-Analyst"], "Writer")

results = workflow.run("Assess the outlook for home battery storage in 2027.")

print(sorted(results))
print(results["Writer"])
```

```text theme={null}
['Collector', 'Market-Analyst', 'Tech-Analyst', 'Writer']
I agree with both prior analyses: by 2027, home battery storage should have ...
```

The graph runs in three layers: Collector, then both analysts at once, then Writer. `add_edge("A", "B")` adds a single edge, and `add_parallel_chain(sources, targets)` connects every source to every target.

> [!NOTE]
>
> Pass the agent itself to `add_node()`, not a `Node`. To give a node an id other than its `agent_name`, build `Node` objects and pass them in the `nodes` constructor argument.

## 2. What each node receives

Nodes in the first layer get the task, with a short line asking for their best response. Every later node gets the task, then one message per predecessor in the form `Predecessor-Name: output`, and a fixed instruction to review that work and build on it. That instruction is why the Writer above opens with "I agree with both prior analyses". The node's own system prompt still decides what it produces, so put the format you want there.

Each result is the agent's final answer, whatever that agent's own `output_type` is. Every output is also added to `workflow.conversation`, which keeps growing across runs.

## 3. Build from a spec and set entry and end points

`GraphWorkflow.from_spec()` builds the whole graph in one call. An edge is a tuple: `(source, target)`, `(source, [targets])` for a fan-out, `([sources], target)` for a fan-in, or `([sources], [targets])` for a full mesh. Other keyword arguments, such as `name` and `max_loops`, go to the constructor.

Entry points are the nodes where work starts and end points are the nodes whose output is the result. When you don't set them, nodes with no incoming edges become entry points and nodes with no outgoing edges become end points. `validate()` uses them to find nodes that are unreachable or lead nowhere. This block reuses the agents from section 1 and adds a fact checker whose output goes nowhere:

```python theme={null}
checker = make_agent("Fact-Checker", "Flag any fact in the list that looks wrong or outdated.")

spec_workflow = GraphWorkflow.from_spec(
    agents=[collector, tech, market, writer, checker],
    edges=[
        ("Collector", ["Tech-Analyst", "Market-Analyst", "Fact-Checker"]),
        (["Tech-Analyst", "Market-Analyst"], "Writer"),
    ],
    entry_points=["Collector"],
    end_points=["Writer"],
    name="Market-Brief-Spec",
)

report = spec_workflow.validate()
print(report["is_valid"], report["warnings"])

spec_workflow.set_end_points(["Writer", "Fact-Checker"])
print(spec_workflow.validate()["warnings"])

spec_workflow.compile()
print(spec_workflow.get_compilation_status()["layers"])
```

```text theme={null}
True ["Found 1 nodes that cannot reach any exit point: {'Fact-Checker'}"]
[]
[['Collector'], ['Tech-Analyst', 'Market-Analyst', 'Fact-Checker'], ['Writer']]
```

`validate()` reports problems without raising. Pass `raise_on_error=True` to raise `ValueError` on an invalid graph, or `auto_fix=True` to add the missing entry and end points for you.

> [!NOTE]
>
> Entry and end points do not decide which nodes run. Every node in the graph runs, in layer order. The end points matter for validation and for `max_loops`, below.

## 4. Follow each node with callbacks

`run()` takes two callbacks. `on_node_complete(node_id, output)` fires as soon as each node finishes, before the rest of its layer. `streaming_callback(node_id, token)` fires for every token any node generates, so filter by `node_id` to follow one node. This block reuses the workflow from section 1:

```python theme={null}
def on_node_complete(node_id: str, output: str) -> None:
    """Report each node as soon as it finishes."""
    print(f"\n[done] {node_id}: {len(output)} characters")


def on_token(node_id: str, token: str) -> None:
    """Print the Writer's tokens as they arrive."""
    if node_id == "Writer":
        print(token, end="", flush=True)


results = workflow.run(
    "Assess the outlook for heat pumps in UK homes in 2027.",
    on_node_complete=on_node_complete,
    streaming_callback=on_token,
)
```

You can also set `on_node_complete` once in the constructor; a callback passed to `run()` takes its place for that run. An exception raised inside a callback is logged and does not stop the workflow.

## 5. Refine over several loops

With `max_loops` above 1, the whole graph runs again. In each later loop, the nodes in the first layer receive the end points' outputs from the loop before, with an instruction to refine them. The result then holds every node's output per loop as `{node_id}_loop_{n}`, plus the last loop's outputs under the plain node ids.

```python theme={null}
refining = GraphWorkflow.from_spec(
    agents=[collector, tech, market, writer],
    edges=[
        ("Collector", ["Tech-Analyst", "Market-Analyst"]),
        (["Tech-Analyst", "Market-Analyst"], "Writer"),
    ],
    name="Refining-Brief",
    max_loops=2,
)

results = refining.run("Assess the outlook for home battery storage in 2027.")

print(sorted(results))
print(results["Writer"])
```

```text theme={null}
['Collector', 'Collector_loop_1', 'Collector_loop_2', 'Market-Analyst', 'Market-Analyst_loop_1', 'Market-Analyst_loop_2', 'Tech-Analyst', 'Tech-Analyst_loop_1', 'Tech-Analyst_loop_2', 'Writer', 'Writer_loop_1', 'Writer_loop_2']
```

`results["Writer"]` is the same text as `results["Writer_loop_2"]`.

## Tips

* **Read the end points.** `run()` returns every node's output, not only the end points'. Look up the node you want by id.
* **Choose what a failure does.** By default a failed node's output becomes an `[ERROR] Agent <name> failed: ...` string and its descendants still run. Set `on_error="skip_descendants"` to skip the nodes that depend on it, or `on_error="raise"` to stop and raise.
* **Cap parallel nodes.** `max_parallel_nodes` limits how many nodes in a layer run at once. By default the whole widest layer runs together.
* **Resume long runs.** With `checkpoint_dir` set, each finished layer is saved, and running the same task again skips the saved layers.
* **Nest graphs.** Pass another `GraphWorkflow` to `add_node()` to run it as one node.
* **Avoid cycles.** The workflow is meant to be a DAG; `validate()` reports any cycle it finds.

## Next steps

* [GraphWorkflow reference](https://docs.swarms.world/api/graph-workflow.md)
* [AgentRearrange guide](https://docs.swarms.world/examples/multi-agent/agent-rearrange-example.md), for flows you can write as one string
* [Runnable scripts](https://github.com/kyegomez/swarms/tree/master/examples/multi_agent/graphworkflow_examples)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.