Executive AI assistant — before / after / after-disrupted#

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

The task. An email arrives. Ignore it, notify the owner, answer it, or schedule the meeting it asks for. A human approves anything that leaves the mailbox. The human may say no.

The original. langchain-ai/executive-ai-assistant (eaia/main/graph.py: 190 lines, 13 nodes) triages with an LLM, has a second LLM pick a tool, sends the choice to a human through Agent Inbox, and routes on the shape of the last message. Three conditional routers each end in raise ValueError; four interrupt handlers (395 lines) each re-implement the accept / edit / ignore / respond branches; a bad_tool_name node strips a stray : from tool names the model sometimes emits.

Hand-wired (before.py)

GOAP (after.py)

Which path

3 routers, 11 if branches, 4 raise ValueError

triage facts as preconditions

Human gate

4 handlers × (accept / edit / ignore / respond)

require_human_approval=True or a Pydantic model

Human says no

an Ignore tool call is synthesised so a router can see it

action failure, blacklist, re-plan

Human fills the form wrong

raise ValueError(f"Unexpected response: ...")

asked again, errors in the payload

Bad model output

bad_tool_name patches the tool name and loops

no tool names to patch

1. The hand-wired version#

before.py keeps the upstream control flow: the same nodes, the same three routers with their ValueError fall-throughs, one Agent Inbox round trip shared by the four handlers, the bad_tool_name patch loop. The LLM is a scripted drafter; Gmail is a pair of flags. run() answers each interrupt from a scripted list of inbox responses.

from examples.screencast.email_assistant import before
from examples.screencast.email_assistant.after import EMAILS

print(before.build_graph().compile().get_graph().draw_mermaid())
---
config:
  flowchart:
    curve: linear
---
graph TD;
	__start__([<p>__start__</p>]):::first
	triage_input(triage_input)
	draft_response(draft_response)
	bad_tool_name(bad_tool_name)
	find_meeting_time(find_meeting_time)
	send_email_draft(send_email_draft)
	send_cal_invite(send_cal_invite)
	notify(notify)
	human_node(human_node)
	send_email_node(send_email_node)
	send_cal_invite_node(send_cal_invite_node)
	mark_as_read_node(mark_as_read_node)
	__end__([<p>__end__</p>]):::last
	__start__ --> triage_input;
	bad_tool_name --> draft_response;
	draft_response -.-> bad_tool_name;
	draft_response -.-> find_meeting_time;
	draft_response -.-> mark_as_read_node;
	draft_response -.-> send_cal_invite;
	draft_response -.-> send_email_draft;
	find_meeting_time --> draft_response;
	human_node -.-> draft_response;
	human_node -.-> mark_as_read_node;
	human_node -.-> send_cal_invite_node;
	human_node -.-> send_email_node;
	notify --> human_node;
	send_cal_invite --> human_node;
	send_cal_invite_node --> draft_response;
	send_email_draft --> human_node;
	send_email_node --> mark_as_read_node;
	triage_input -.-> draft_response;
	triage_input -.-> mark_as_read_node;
	triage_input -.-> notify;
	mark_as_read_node --> __end__;
	classDef default fill:#f2f0ff,line-height:1.2
	classDef first fill-opacity:0
	classDef last fill:#bfb6fc
for label, answers in {
    "newsletter": [],
    "urgent": [{"type": "accept"}],
    "question": [{"type": "accept"}],
    "meeting": [{"type": "accept"}, {"type": "accept"}],
}.items():
    print(f"--- {label}: {EMAILS[label]['subject']} ---")
    final = before.run(EMAILS[label], answers)
    print(f"  sent={final.get('sent', False)} read={final.get('read', False)} notified={final.get('notified', False)}\n")
--- newsletter: Weekly digest: ten tips for faster builds ---
  [triage_input] -> no
  [mark_as_read_node] m-1
  sent=False read=True notified=False

--- urgent: URGENT: board deck numbers ---
  [triage_input] -> notify
  [notify] inbox response: accept
  [mark_as_read_node] m-2
  sent=False read=True notified=True

--- question: Question about the API rate limits ---
  [triage_input] -> email
  [draft_response] tool call ResponseEmailDraft
  [send_email_draft] inbox response: accept
  [send_email_node] -> dana@example.com: 'Hi, the limit is 600 requests per minute.'
  [mark_as_read_node] m-3
  sent=True read=True notified=False

--- meeting: Can we meet next week? ---
  [triage_input] -> email
  [draft_response] tool call MeetingAssistant
  [find_meeting_time] ['2026-11-18T15:00:00', '2026-11-19T10:00:00']
  [draft_response] tool call SendCalendarInvite
  [send_cal_invite] inbox response: accept
  [send_cal_invite_node] {'title': 'Q3 roadmap review', 'start_time': '2026-11-18T15:00:00', 'emails': ['dana@example.com']}
  [draft_response] tool call ResponseEmailDraft
  [send_email_draft] inbox response: accept
  [send_email_node] -> dana@example.com: 'Hi, the invite is on its way.'
  [mark_as_read_node] m-4
  sent=True read=True notified=False

Two upstream failure modes, reproduced. First the model emits ResponseEmailDraft: and the bad_tool_name node patches it and loops back to the drafter. Then the inbox returns a response type the handler does not know and the graph raises.

final = before.run(EMAILS["question"], [{"type": "accept"}], mangle_tool_name=True)
print(f"  bad_tool_names={final['bad_tool_names']} sent={final['sent']}\n")

try:
    before.run(EMAILS["question"], [{"type": "shrug"}])
except ValueError as exc:
    print(f"  ValueError: {exc}")
  [triage_input] -> email
  [draft_response] tool call ResponseEmailDraft:
  [bad_tool_name] Could not find tool with name `ResponseEmailDraft:`. Make sure you are calling one of the allowed tools!
  [draft_response] tool call ResponseEmailDraft
  [send_email_draft] inbox response: accept
  [send_email_node] -> dana@example.com: 'Hi, the limit is 600 requests per minute.'
  [mark_as_read_node] m-3
  bad_tool_names=1 sent=True

  [triage_input] -> email
  [draft_response] tool call ResponseEmailDraft
  [send_email_draft] inbox response: shrug
  ValueError: Unexpected response: {'type': 'shrug'}

2. The GOAP version: triage facts are preconditions#

A FunctionalSensor classifies the email once and writes four facts. Seven actions carry the paths as preconditions; the goal is email_handled. The two human gates are declared on the actions: send_email with require_human_approval=True, send_cal_invite with a Pydantic CalendarInvite form whose validated answer lands in world_state["invite"].

from langgraph.checkpoint.memory import MemorySaver
from langgraph.types import Command

from examples.screencast.email_assistant.after import (
    CalendarInvite, build_actions, build_goal, build_graph, initial_world_state,
)

for a in build_actions():
    gate = a.require_human_approval
    gate_s = "" if not gate else ("  [approve/deny]" if gate is True else f"  [form: {gate.__name__}]")
    print(f"{a.name:18s} cost={a.cost:<4} pre={dict(a.preconditions)}  eff={dict(a.effects)}{gate_s}")
find_meeting_time  cost=1.0  pre={'needs_meeting': True}  eff={'free_slots_known': True}
send_cal_invite    cost=1.0  pre={'free_slots_known': True}  eff={'invite_sent': True, 'reply_context_ready': True}  [form: CalendarInvite]
draft_reply        cost=1.0  pre={'needs_reply': True, 'reply_context_ready': True}  eff={'draft_ready': True}
send_email         cost=1.0  pre={'draft_ready': True}  eff={'reply_sent': True, 'follow_up_done': True}  [approve/deny]
escalate_to_user   cost=5.0  pre={'needs_reply': True}  eff={'escalated': True, 'follow_up_done': True}
notify_user        cost=1.0  pre={'needs_notify': True}  eff={'user_notified': True, 'follow_up_done': True}
mark_as_read       cost=1.0  pre={'follow_up_done': True}  eff={'email_handled': True}

The same four emails. The newsletter is only marked as read; the urgent one pings the owner; the question is drafted, approved and sent; the meeting request finds a slot, asks the operator to fill in the invite form, then drafts a reply that mentions the invite, asks for approval, and sends.

ANSWERS = {
    "send_cal_invite": {
        "title": "Q3 roadmap review",
        "start": "2026-11-18T15:00:00",
        "end": "2026-11-18T15:30:00",
        "attendees": ["dana@example.com"],
    },
    "send_email": {"approved": True},
}


def handle(label: str, answers: dict = ANSWERS) -> dict:
    graph = build_graph()
    compiled = graph.compile(checkpointer=MemorySaver())
    config = {"configurable": {"thread_id": label}}
    print(f"--- {label}: {EMAILS[label]['subject']} ---")
    result = compiled.invoke(
        graph.initial_state(build_goal(), initial_world_state(EMAILS[label])), config=config
    )
    while "__interrupt__" in result:
        ask = result["__interrupt__"][0].value
        print(f"  [human] {ask['type']} for {ask['action']} -> {answers[ask['action']]}")
        result = compiled.invoke(Command(resume=answers[ask["action"]]), config=config)
    print(f"  status: {result['status']}  steps: {[h['action_name'] for h in result['execution_history']]}\n")
    return result


for label in EMAILS:
    handle(label)
--- newsletter: Weekly digest: ten tips for faster builds ---
  [triage] 'Weekly digest: ten tips for faster builds' -> ignore
  [mark_as_read] m-1
  status: goal_achieved  steps: ['mark_as_read']

--- urgent: URGENT: board deck numbers ---
  [triage] 'URGENT: board deck numbers' -> notify
  [notify_user] ping: 'URGENT: board deck numbers'
  [mark_as_read] m-2
  status: goal_achieved  steps: ['notify_user', 'mark_as_read']

--- question: Question about the API rate limits ---
  [triage] 'Question about the API rate limits' -> respond
  [draft_reply] Hi Dana, the public API allows 600 requests per minute per key.
  [human] goap_action_approval for send_email -> {'approved': True}
  [send_email] -> dana@example.com
  [mark_as_read] m-3
  status: goal_achieved  steps: ['draft_reply', 'send_email', 'mark_as_read']

--- meeting: Can we meet next week? ---
  [triage] 'Can we meet next week?' -> meeting
  [find_meeting_time] free slots: ['2026-11-18T15:00:00', '2026-11-19T10:00:00']
  [human] goap_action_form for send_cal_invite -> {'title': 'Q3 roadmap review', 'start': '2026-11-18T15:00:00', 'end': '2026-11-18T15:30:00', 'attendees': ['dana@example.com']}
  [send_cal_invite] 'Q3 roadmap review' 2026-11-18T15:00:00 -> ['dana@example.com']
  [draft_reply] Hi Dana, I have sent an invite for 'Q3 roadmap review' starting 2026-11-18T15:00:00. Looking forward to it.
  [human] goap_action_approval for send_email -> {'approved': True}
  [send_email] -> dana@example.com
  [mark_as_read] m-4
  status: goal_achieved  steps: ['find_meeting_time', 'send_cal_invite', 'draft_reply', 'send_email', 'mark_as_read']

What the operator sees at each gate: the approval payload carries the action, its preconditions, effects and the current world state; the form payload carries the model’s JSON schema.

import json

graph = build_graph()
compiled = graph.compile(checkpointer=MemorySaver())
config = {"configurable": {"thread_id": "peek"}}
paused = compiled.invoke(
    graph.initial_state(build_goal(), initial_world_state(EMAILS["meeting"])), config=config
)
form = paused["__interrupt__"][0].value
print("type      :", form["type"])
print("action    :", form["action"])
print("model     :", form["model_name"])
print("required  :", form["form_schema"]["required"])
print("properties:", list(form["form_schema"]["properties"]))
paused = compiled.invoke(Command(resume=ANSWERS["send_cal_invite"]), config=config)
approval = paused["__interrupt__"][0].value
print()
print("type      :", approval["type"])
print("action    :", approval["action"])
print("effects   :", approval["effects"])
print("draft     :", approval["world_state"]["draft"])
  [triage] 'Can we meet next week?' -> meeting
  [find_meeting_time] free slots: ['2026-11-18T15:00:00', '2026-11-19T10:00:00']
type      : goap_action_form
action    : send_cal_invite
model     : CalendarInvite
required  : ['title', 'start', 'end']
properties: ['title', 'start', 'end', 'attendees']
  [send_cal_invite] 'Q3 roadmap review' 2026-11-18T15:00:00 -> ['dana@example.com']
  [draft_reply] Hi Dana, I have sent an invite for 'Q3 roadmap review' starting 2026-11-18T15:00:00. Looking forward to it.

type      : goap_action_approval
action    : send_email
effects   : {'reply_sent': True, 'follow_up_done': True}
draft     : Hi Dana, I have sent an invite for 'Q3 roadmap review' starting 2026-11-18T15:00:00. Looking forward to it.

3. Disruption: the human says no, fills the form wrong, or the process dies#

Upstream, an unexpected inbox response is a ValueError. Here a denial is an action failure with the operator’s reason attached. The observer blacklists send_email, the planner re-plans from the current world state, and escalate_to_user (cost 5, dearer than the whole reply path) is now the cheapest way to follow_up_done.

An invite form that fails Pydantic validation is a different thing: an input error, not a decision. The operator is asked again, and the new interrupt payload carries the attempt number, the rejected payload and the validation errors. Declining the form ({"approved": False, "reason": ...}) is a decision and takes the same path as the denied send.

import logging, sys

logging.basicConfig(stream=sys.stdout, format="  log  %(message)s", level=logging.WARNING, force=True)

from examples.screencast.email_assistant import after_disrupted

denied = after_disrupted.denied_send()
bad_form = after_disrupted.invalid_form()
============================================================
  DISRUPTION 1 — the operator denies the send
============================================================
  [triage] 'Question about the API rate limits' -> respond
  [draft_reply] Hi Dana, the public API allows 600 requests per minute per key.
  [human] approval for send_email -> DENY ('tone is off')
  log  Action 'send_email' failed: human_approval_denied: tone is off
  [escalate_to_user] draft left in Drafts; owner pinged to handle the thread by hand
  [mark_as_read] m-3
  status: goal_achieved  replans: 1  blacklisted: ['send_email']
    ok   draft_reply
    FAIL send_email — human_approval_denied: tone is off
    ok   escalate_to_user
    ok   mark_as_read

============================================================
  DISRUPTION 2 — the invite form fails validation, then is declined
============================================================
  [triage] 'Can we meet next week?' -> meeting
  [find_meeting_time] free slots: ['2026-11-18T15:00:00', '2026-11-19T10:00:00']
  [human] form for send_cal_invite -> {'title': 'no times'}  (start/end missing)
  asked again: attempt 2, rejected {'title': 'no times'}
    start: Field required
    end: Field required
  [human] form for send_cal_invite -> DECLINE ('not this week')
  log  Action 'send_cal_invite' failed: human_approval_denied: not this week
  [escalate_to_user] no draft yet; owner pinged to handle the thread by hand
  [mark_as_read] m-4
  status: goal_achieved  replans: 1  blacklisted: ['send_cal_invite']
    ok   find_meeting_time
    FAIL send_cal_invite — human_approval_denied: not this week
    ok   escalate_to_user
    ok   mark_as_read

The run is paused at interrupt() with the state in the checkpointer. A new process builds a new GoapGraph, compiles it against the same checkpointer, and resumes the same thread.

resumed = after_disrupted.crash_and_resume()
============================================================
  DISRUPTION 3 — the process dies while the human is deciding
============================================================
  [triage] 'Question about the API rate limits' -> respond
  [draft_reply] Hi Dana, the public API allows 600 requests per minute per key.
  paused at: send_email  -- process exits here
  new process, new graph object, same checkpointer and thread
  [send_email] -> dana@example.com
  [mark_as_read] m-3
  status: goal_achieved  replans: 0  blacklisted: []
    ok   draft_reply
    ok   send_email
    ok   mark_as_read

4. What replaced what#

Hand-wired piece

GOAP replacement

route_after_triage (4 branches + ValueError)

the sensor’s facts are preconditions on notify_user, draft_reply, find_meeting_time

take_action (5 branches + bad_tool_name)

no tool names: the planner picks actions by effects

enter_after_human (5 branches + 2 ValueError)

the gate either lets the action run or fails it

4 Agent Inbox handlers (accept / edit / ignore / respond)

require_human_approval=True and a Pydantic model

Ignore tool call synthesised on denial

blacklist + re-plan to escalate_to_user

raise ValueError on an unexpected inbox response

a bad form is asked again with the errors; a declined one is blacklisted

The integration test tests/integration/test_screencast_email_assistant.py pins the four paths, both gate payloads, the denial re-plan, the invalid-form re-ask, the declined form, the crash-resume and the async path, and keeps the hand-wired version faithful to upstream (ValueError included).