LLMCompiler — before / after / after-disrupted#

Notebook version of the three-script screencast in examples/screencast/llm_compiler/.

The task. Answer “what is the combined population of Springfield and Shelbyville?”: two independent lookups, one sum, one sentence. Run the lookups in parallel; recover when one fails.

The original. LangGraph’s LLMCompiler tutorial (462 code lines, 2 nodes, 1 conditional edge) streams a DAG of tool tasks with $N dependency references, schedules them by hand as dependencies resolve, and asks a joiner LLM to choose between a final answer and Replan. Routing is encoded in message types: the graph ends when the last message is an AIMessage. Four issues report the replan branch as broken or untested (#274, #1459, #1513, #1565).

Hand-wired (before.py)

GOAP (after.py)

Dependencies

$N strings, a resolver, a thread pool

preconditions and effects

Ordering

planner prompt + scheduler

A*

Parallelism

ThreadPoolExecutor over “ready” tasks

executor="parallel" waves

Recovery

joiner emits Replan as a SystemMessage the planner must parse

observer blacklists the failed action and re-plans

Termination

recursion_limit

goal reached, or no_plan with an explanation

1. The hand-wired version#

before.py is a condensed, hermetic version of the tutorial’s control flow. The planner is a fixed task list (an LLM writes it in the original), the scheduler resolves $N references and runs ready tasks in a thread pool, and should_continue routes on isinstance(messages[-1], AIMessage).

from examples.screencast.llm_compiler import before

print(before.build_graph().compile().get_graph().draw_mermaid())
before.run()
before.run(index_down_for=["Springfield"])
---
config:
  flowchart:
    curve: linear
---
graph TD;
	__start__([<p>__start__</p>]):::first
	plan_and_schedule(plan_and_schedule)
	join(join)
	__end__([<p>__end__</p>]):::last
	__start__ --> plan_and_schedule;
	join -.-> __end__;
	join -.-> plan_and_schedule;
	plan_and_schedule --> join;
	classDef default fill:#f2f0ff,line-height:1.2
	classDef first fill-opacity:0
	classDef last fill:#bfb6fc


============================================================
  BEFORE (hand-wired LangGraph) — HAPPY PATH
============================================================
  [plan_and_schedule] attempt 1: ['lookup', 'lookup', 'add']
  [join] FinalResponse — 54,838

  Result: The combined population is 54,838.  (attempts: 1)

============================================================
  BEFORE (hand-wired LangGraph) — INDEX DOWN FOR ['Springfield']
============================================================
  [plan_and_schedule] attempt 1: ['lookup', 'lookup', 'add']
  [join] Replan — ERROR: population index unavailable for Springfield
  [plan_and_schedule] attempt 2: ['archive_lookup', 'archive_lookup', 'add']
  [join] FinalResponse — 54,838

  Result: The combined population is 54,838.  (attempts: 2)

Two things to notice in the disrupted run: the replan re-ran both lookups through the archive although only Springfield’s index was down, and the planner had to recognise the word “unavailable” in a feedback string to switch tools. Neither is a bug in this condensed version; both are what the architecture asks you to hand-write.

2. The GOAP version: dependencies are preconditions#

Each tool task is an ActionSpec. The sum’s preconditions are the two *_known facts the lookups produce, so A* orders the plan and the parallel executor runs the two lookups in one wave.

from examples.screencast.llm_compiler.after import build_actions, build_goal, initial_world_state
from langgoap import GoapGraph

for a in build_actions():
    print(f"{a.name:28s} cost={a.cost:<4} pre={dict(a.preconditions)}  eff={dict(a.effects)}")

graph = GoapGraph(build_actions(), executor="parallel")
result = graph.invoke(goal=build_goal(), world_state=initial_world_state())
print()
print("status :", result["status"])
print("answer :", result["world_state"]["answer"])
print("history:", [h.action_name for h in result["execution_history"]])
lookup_springfield           cost=1.0  pre={'question_parsed': True}  eff={'population_springfield_known': True}
lookup_springfield_archive   cost=3.0  pre={'question_parsed': True}  eff={'population_springfield_known': True}
lookup_shelbyville           cost=1.0  pre={'question_parsed': True}  eff={'population_shelbyville_known': True}
lookup_shelbyville_archive   cost=3.0  pre={'question_parsed': True}  eff={'population_shelbyville_known': True}
sum_populations              cost=1.0  pre={'population_springfield_known': True, 'population_shelbyville_known': True}  eff={'total_known': True}
compose_answer               cost=1.0  pre={'total_known': True}  eff={'answer_ready': True}
  [lookup_springfield] index -> 30,720
  [lookup_shelbyville] index -> 24,118
  [sum_populations] 30720 + 24118 = 54,838
  [compose_answer] The combined population of Springfield and Shelbyville is 54,838.

status : goal_achieved
answer : The combined population of Springfield and Shelbyville is 54,838.
history: ['lookup_springfield', 'lookup_shelbyville', 'sum_populations', 'compose_answer']

How many times did the executor node run? Streaming the graph’s node updates shows the two lookups as a single executor invocation (one wave), then the sum, then the answer.

def executor_steps(g: GoapGraph) -> int:
    compiled = g.compile()
    state = g.initial_state(build_goal(), initial_world_state())
    return sum(1 for update in compiled.stream(state, stream_mode="updates") if "executor" in update)

print("parallel executor  :", executor_steps(GoapGraph(build_actions(), executor="parallel")), "executor invocations")
print("sequential executor:", executor_steps(GoapGraph(build_actions())), "executor invocations")
  [lookup_springfield] index -> 30,720
  [lookup_shelbyville] index -> 24,118
  [sum_populations] 30720 + 24118 = 54,838
  [compose_answer] The combined population of Springfield and Shelbyville is 54,838.
parallel executor  : 3 executor invocations
  [lookup_springfield] index -> 30,720
  [lookup_shelbyville] index -> 24,118
  [sum_populations] 30720 + 24118 = 54,838
  [compose_answer] The combined population of Springfield and Shelbyville is 54,838.
sequential executor: 4 executor invocations

3. Disruption: the index is down#

The fast lookup raises. max_retries is 0, so the observer blacklists it and the planner swaps in the archive lookup (cost 3). A sibling result already obtained is kept, so only the failed city is looked up again.

import logging, sys

# The observer and planner log through ``logging``; send those lines to stdout so
# they appear in order with the prints below instead of in a separate stderr block.
logging.basicConfig(stream=sys.stdout, format="  log  %(message)s", level=logging.WARNING, force=True)


def show(label: str, **flags):
    ws = {**initial_world_state(), **flags}
    actions = build_actions()
    if flags.get("archive_down"):
        actions = [a for a in actions if not a.name.endswith("_archive")]
    result = GoapGraph(actions, executor="parallel").invoke(goal=build_goal(), world_state=ws)
    print(f"--- {label} ---")
    print("status     :", result["status"], "| replans:", result["replan_count"], "| blacklisted:", result["blacklisted_actions"])
    for h in result["execution_history"]:
        print(f"  {'ok  ' if h.success else 'FAIL'} {h.action_name}" + ("" if h.success else f" — {h.error}"))
    if result["status"] == "no_plan":
        print("  explanation:", result["no_plan_explanation"]["suggestion"])
    print()

show("index down for Springfield only", index_down_for=["Springfield"])
show("index down for every city", primary_index_down=True)
show("index and archive both down", primary_index_down=True, archive_down=True)
  log  Action 'lookup_springfield' failed: population index unavailable for Springfield
  [lookup_shelbyville] index -> 24,118
  [lookup_springfield_archive] archive -> 30,720
  [sum_populations] 30720 + 24118 = 54,838
  [compose_answer] The combined population of Springfield and Shelbyville is 54,838.
--- index down for Springfield only ---
status     : goal_achieved | replans: 1 | blacklisted: ['lookup_springfield']
  FAIL lookup_springfield — population index unavailable for Springfield
  ok   lookup_shelbyville
  ok   lookup_springfield_archive
  ok   sum_populations
  ok   compose_answer

  log  Action 'lookup_springfield' failed: population index unavailable for Springfield
  log  Action 'lookup_shelbyville' failed: population index unavailable for Shelbyville
  [lookup_springfield_archive] archive -> 30,720
  [lookup_shelbyville_archive] archive -> 24,118
  [sum_populations] 30720 + 24118 = 54,838
  [compose_answer] The combined population of Springfield and Shelbyville is 54,838.
--- index down for every city ---
status     : goal_achieved | replans: 2 | blacklisted: ['lookup_springfield', 'lookup_shelbyville']
  FAIL lookup_springfield — population index unavailable for Springfield
  FAIL lookup_shelbyville — population index unavailable for Shelbyville
  ok   lookup_springfield_archive
  ok   lookup_shelbyville_archive
  ok   sum_populations
  ok   compose_answer

  log  Action 'lookup_springfield' failed: population index unavailable for Springfield
  log  No plan for goal {'answer_ready': True}: Every remaining path to the goal needs a blacklisted action (lookup_springfield). Raise ActionSpec.max_retries or attach an ActionQos for transient failures, add an alternative action, or set GoalPolicy(blacklist_fallback=True) to re-admit blacklisted actions.
--- index and archive both down ---
status     : no_plan | replans: 1 | blacklisted: ['lookup_springfield']
  FAIL lookup_springfield — population index unavailable for Springfield
  explanation: Every remaining path to the goal needs a blacklisted action (lookup_springfield). Raise ActionSpec.max_retries or attach an ActionQos for transient failures, add an alternative action, or set GoalPolicy(blacklist_fallback=True) to re-admit blacklisted actions.

4. What replaced what#

Hand-wired piece

Lines in before.py

GOAP replacement

$N reference parser and dependency walker

~35

preconditions on each ActionSpec

Ready-task scheduler with a thread pool

~25

GoapGraph(..., executor="parallel")

Joiner deciding FinalResponse vs Replan

~10

the observer: a failed action is blacklisted and the planner runs again

Feedback as a SystemMessage the planner must parse

~5

nothing: the archive action is simply the next cheapest way to the same effect

should_continue routing on message type

~5

nothing: the goal is a world-state fact

recursion_limit as the safety net

1

no_plan with an explanation; TerminationPolicy if you want a budget

The integration test tests/integration/test_screencast_llm_compiler.py pins the wave count, the answer, the replan behaviour and the async path.