The Testing Academy · Class Notes Friday, 27 November (IST)
Live class · study guide

LangGraph Part 2: memory, interrupt, LLM node, final finder

The last LangGraph class: a short recap, then memory with a checkpointer and a thread id, a human in the loop with interrupt and Command, and an LLM node that sorts a failure into fixed categories while Python keeps the routing. Then the final flaky test finder: two builds in, a cause from the LLM, a quarantine, and a human who can be asked first, in Python and in TypeScript.

By Pramod Dutta, The Testing Academy. Study notes from the AI Tester Blueprint 3x class, built from the session recording, the batch repository (commit "feat: add the final flaky finder in Python and TypeScript", pushed as the class ended; the two commits after it changed only the README's diagrams and added a cheat-sheet brief) and the Eraser notes deck (its LangGraph Part 2 section). Every Python file of the commit was run on the versions the class's own virtual environment had installed (Python 3.12.4, LangGraph 1.2.24, langchain-groq 1.2.1), and the TypeScript twin on its own lockfile (LangGraph JS 1.7.5), with the network blocked and no key. Where the class's code calls Groq, a copy of llm.py or llm.ts with one line changed points it at a small local model, gemma3:270m, through Ollama, so the LLM answers shown are that model's, not the class's. The Playwright tests and run_build.py sign in to TTACart, so they were not run: the finder reads the build files that the class's own run left in the repo.

Hides every output until you tap Reveal, so you can predict it first.
01

What this class covered

  • Recap: Part 1, and what this class adds
  • Memory: a checkpointer and a thread id
  • Human in the loop: interrupt and Command
  • An LLM node: the model decides, Python routes
  • The final flaky test finder
  • The TypeScript twin
  • Jenkins: a post-build action
  • Tasks and announcements: rewatch, build three agents, and more sessions to come
  • Compile with a checkpointer and pass a thread_id, and each thread keeps its own state between invoke() calls. InMemorySaver keeps it in memory; the file's docstring names a SQLite or Postgres saver to survive a restart.
  • Annotated[list[str], operator.add] tells LangGraph to add each new item to the saved list. Without it, or without the checkpointer, every invoke starts again at run #1.
  • interrupt() pauses the graph and hands a question to the caller, and Command(resume=answer) on the same thread_id carries on. Without a checkpointer, the resume fails.
  • In an LLM node, the model returns one of a fixed set of categories (structured output), and a plain Python function routes on it: the model decides, the graph stays in control.
  • The final finder calls the LLM only when a test flipped between the two builds, and it triages and quarantines only the first flaky test.
  • Answering no keeps the test FLAKY in the report and quarantines nothing. The line about LANGGRAPH_STRICT_MSGPACK is a LangGraph warning about reading saved state, not a switch that blocks a test.
  • The TypeScript twin runs on LangGraph JS, where a node may not share a name with a state channel: its triage node is triage_flaky.
02

Recap: Part 1, and what this class adds

SEVEN LESSONS, ONE GRAPH the finder's docstring Part 1, last class 01 STATE A backpack a TypedDict; nodes return what changed 02 PIPELINE Load, then compare load_builds, compare, then the rest 03 BRANCH Skip the LLM entirely when nothing is flaky 04 LOOP IDEA A pair is a verdict one status is an observation Part 2, this class 05 MEMORY A checkpointer which interrupt() requires 06 HUMAN interrupt() pauses before quarantining 07 LLM NODE The LLM says why it flaked; Python still routes today's two topics, then the finder all seven in one graph THE FINAL FINDER Project_FlakyTestFinderFinal.py two builds in, a triaged verdict out
Lines 3 to 10 of Project_FlakyTestFinderFinal.py map each lesson to the part of the final graph that uses it.

Last class wrote four small graphs and a mini flaky finder. This is Part 2 of the series, and the last LangGraph class. It opened with a quick recap from the notes.

LangGraph helps you build AI agents with states and branching logic, the instructor said. It is an open-source Python library, which now supports JavaScript too, for building an LLM application in the form of a graph: it can have branches, loops and decisions, and of course it uses an LLM too.

The important points, as the class went over them again:

  • The state is where you store everything, as key-value pairs. It is like your backpack: when you go on a trip, everything is stored in your backpack.
  • Nodes are plain functions. Each one takes a state and returns a dictionary.
  • Edges are the flow control you want to use.
  • When you combine them, it becomes a LangGraph flow. You install it with pip install langgraph, make a typed dictionary your state, add the nodes and the edges, then compile and invoke.

The best use case, the instructor said, is a flaky test case finder. A normal LangChain flow is linear, but LangGraph can have multiple branches, loops, retries and decisions, so the LLM can take decisions too. That is why people prefer LangGraph to LangChain when they want to build a production-ready system. Last time's project, the instructor recalled, took two build files from a Playwright run, loaded them, compared them, routed them and confirmed the flakiness.

Like n8n, in code. In n8n, the class used to have nodes which are connected, the instructor said: these are the same nodes, every one of them is a function, and the edges connect them into a proper workflow. In n8n and in LangFlow you have seen the UI part; here you do it with functions and edges, and that is the only difference. The rest you do by hand: you write the functions yourself, or with AI, and you can build a linear pipeline, a conditional one, a looped one and more.

Today. The ultimate goal was the full and final flaky test finder, built with help from Claude. Before it, two topics that are very important: how to add checkpoints and memory, and how to add an LLM, because the moment you add an LLM, it can take decisions by itself rather than through the code, the instructor said. Then the finder, which takes a real Playwright framework, runs it two times and finds the flaky test automatically. The deck's section for this class lists the same three: checkpoints and memory, adding an LLM, and the flaky test finder project.

03

Memory: a checkpointer and a thread id

ONE CHECKPOINTER, TWO THREADS 05_Memeory_Checkpoint.py DOOR IN START NODE record_run adds one label, run #N DOOR OUT END COMPILED WITH InMemorySaver() saves the state per thread thread_id nightly-regression invoke 1 ['run #1'] invoke 2 ['run #1', 'run #2'] invoke 3 ['run #1', 'run #2', 'run #3'] runs, after each invoke: the saved list grows, because line 15 adds each new label (operator.add) and the checkpointer keeps the list 9 checkpoints saved thread_id smoke invoke 1 ['run #1'] its own state: it starts again at run #1
The values are the file's real output. Each thread_id keeps its own saved state between invoke() calls.

The first topic was memory, or checkpoints. This is a very interesting feature of LangGraph, the instructor said: you compile a state graph with a checkpointer, and if a run goes through step 1, step 2 and so on up to step 5, you can roll back to the checkpoints too. Whenever you compile with a checkpointer, you pass a thread ID and a configuration, and you can go back to a checkpoint if required.

The changes are very small, the instructor said. You build the graph as it is; the state keeps a list of runs, so you can see how many times you have run it, and a node named record_run records each one. operator.add merges a new item in, and Annotated tells LangGraph how to combine the value. InMemorySaver is already available in LangGraph. In the recap folder, the file is named as the repo spells it:

05_Memeory_Checkpoint.pyPython
"""005 - Memory with a checkpointer.

Compile with a checkpointer and pass a thread_id. 
Each thread keeps its own state between invoke() calls, like separate test sessions. 
Swap InMemorySaver for a SQLite or Postgres saver and it survives restarts.
"""

import operator
from typing import Annotated, TypedDict

from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import END, START, StateGraph

class State(TypedDict):
    runs: Annotated[list[str], operator.add]


def record_run(state: State) -> dict:
    return {"runs": [f"run #{len(state.get('runs', [])) + 1}"]}

builder = StateGraph(State)
builder.add_node("record_run", record_run)
builder.add_edge(START, "record_run")
builder.add_edge("record_run", END)

app = builder.compile(checkpointer=InMemorySaver())

if __name__ == "__main__":
    nightly = {"configurable": {"thread_id": "nightly-regression"}}
    smoke = {"configurable": {"thread_id": "smoke"}}

    app.invoke({"runs": []}, nightly)
    app.invoke({"runs": []}, nightly)
    out = app.invoke({"runs": []}, nightly)
    print("nightly-regression remembers:", out["runs"])

    out = app.invoke({"runs": []}, smoke)
    print("smoke is separate:           ", out["runs"])

    snap = app.get_state(nightly)
    print("\nget_state(nightly).values:", snap.values)
    print("checkpoints saved for nightly:", len(list(app.get_state_history(nightly))))
Terminal
python 05_Memeory_Checkpoint.py
Output
nightly-regression remembers: ['run #1', 'run #2', 'run #3']
smoke is separate:            ['run #1']

get_state(nightly).values: {'runs': ['run #1', 'run #2', 'run #3']}
checkpoints saved for nightly: 9
  • Lines 1 to 6, the docstring. Compile with a checkpointer and pass a thread_id, and each thread keeps its own state between invoke() calls, like separate test sessions. Swap InMemorySaver for a SQLite or Postgres saver and it survives restarts. In class: it will survive even if you restart your machine.
  • Lines 14 and 15, the state. One key, runs, a list of strings with operator.add as its reducer.
  • Lines 18 and 19, the node. record_run returns one new label, run # and the next number.
  • Lines 21 to 26, the graph. Start, record_run, end, compiled with checkpointer=InMemorySaver(). A very simple workflow, by the way, the instructor said: it does nothing. It starts, it records something, and it ends. But everything is kept in memory, so if you invoke it two times, or a third time, everything is remembered.
  • Lines 29 to 38, two threads. nightly-regression is invoked three times and smoke once, each with its own config.
  • Lines 40 to 42. get_state() reads a thread's saved values, and get_state_history() lists its checkpoints.

When you run it the first time on the nightly regression, the run is 1, the instructor explained; then you run it again, and it is 2; then 3. So it remembers that the run happened 1, 2 and 3 times for the nightly. Smoke is a separate one: it was invoked only one time, so its run is 1. And if you get the value of nightly again, you know that it ran 3 times.

What makes it remember, run here on four versions of the file, each with one line switched off:

Line 15, the state Line 26, the compile Nightly, after three invokes Smoke
Annotated[..., operator.add] InMemorySaver() ['run #1', 'run #2', 'run #3'] ['run #1']
list[str] InMemorySaver() ['run #1'] ['run #1']
Annotated[..., operator.add] none ['run #1'] ['run #1']
list[str] none ['run #1'] ['run #1']

Both are needed. The checkpointer keeps each thread's state between invoke() calls, and the reducer adds the new label to the saved list. Each invoke hands in {"runs": []}: without operator.add, that empty list replaces the saved one, and the count starts again.

The 9 checkpoints the file counts for nightly-regression are three per invoke: one for the input, one before record_run, one after it. Read from the class's own graph:

Invoke Step Next node Runs saved at that point
1 -1 __start__ []
1 0 record_run []
1 1 none: done ['run #1']
2 2 __start__ ['run #1']
2 3 record_run ['run #1']
2 4 none: done ['run #1', 'run #2']
3 5 __start__ ['run #1', 'run #2']
3 6 record_run ['run #1', 'run #2']
3 7 none: done ['run #1', 'run #2', 'run #3']
Two panels on cream paper, each with a drawing board on a desk. Left, titled n8n, with the sublabel Drag and drop: a dotted canvas with three blocks joined by connectors, and a fourth blush block with a small database symbol dropping onto the middle one from above, shown by a curved terracotta arrow. Right, titled LangGraph, with the sublabel Written in code: a sheet of grey squiggles standing for code, with three brackets joined in the same shape, and the same database symbol in a terracotta box at the bottom, linked to them.
The class's comparison: n8n's memory is a block you drag and drop; LangGraph's in-memory saver does the same job, written in code.

Like n8n's memory. In n8n workflows, you had a memory that remembers your conversations, the instructor reminded the class. Similarly, here the in-memory saver remembers how many times you have run your workflow, your AI agent. In n8n you just drag and drop the memory; here you have to do it by hand, in code. And this is a great feature for the flaky one, the instructor said. The final finder compiles with a checkpointer too, on its line 132, because the pause of the next section needs one.

Question. Last time, how did we run it? Do you remember?

Worth practising too: why does smoke show only run #1 when nightly-regression shows three?

Show the answer

Answer. The instructor thinks you first activate the virtual environment, then run the file with uv, or directly with Python, such as python 05_Memeory_Checkpoint.py. As for smoke: each thread_id keeps its own saved state, and smoke was invoked once.

04

Human in the loop: interrupt and Command

A PAUSE THE CHECKPOINTER KEEPS 06_Human_In_Loop.py DOOR IN START NODE detect two flaky tests NODE, PAUSES ask_approval interrupt() asks IF YES OR Y quarantine quarantined 2 tests ANYTHING ELSE skip left as is, nothing changed route DOOR OUT END The pause, and the resume 1 interrupt() freezes the graph inside ask_approval 2 invoke() returns: __interrupt__ holds the question 3 the checkpointer keeps the paused thread, flaky-review-1 4 Command(resume=answer) on the same thread_id carries on
The answers and endings are the file's real runs. The resume needs the checkpointer: without one it fails.

LangGraph also allows you to have a human in the loop, the instructor said: you can pause the graph, the agent, and ask for a human's input. This file uses the in-memory saver, start and end, and Command and interrupt. The state notes down the flaky tests and whether they are approved; detect is just a dummy, which names the flaky tests, a login one among them. Then comes the human approval, and this is where interrupt comes in: it asks whether to quarantine these tests.

06_Human_In_Loop.pyPython
"""007 - Human in the loop: pause the graph and ask before doing something risky.

interrupt(payload) freezes the graph and hands `payload` to the caller.
You resume it later with Command(resume=answer) on the SAME thread_id.
A checkpointer is required: the pause has to be saved somewhere.

    python 007_Human_In_The_Loop.py        # asks you
    python 007_Human_In_The_Loop.py yes    # answers for you (CI / demos)
"""
import sys
from typing import Literal, TypedDict

from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import END, START, StateGraph
from langgraph.types import Command, interrupt


class State(TypedDict, total=False):
    flaky_tests: list[str]
    approved: bool
    outcome: str

def detect(state: State) -> dict:
    return {"flaky_tests": ["login_redirect", "search_autocomplete"]}

def ask_approval(state: State) -> dict:
    answer = interrupt({
        "question": "Quarantine these tests? (yes/no)",
        "tests": state["flaky_tests"],
    })
    return {"approved": str(answer).strip().lower() in ("y", "yes")}

def route(state: State) -> Literal["quarantine", "skip"]:
    return "quarantine" if state["approved"] else "skip"


def quarantine(state: State) -> dict:
    return {"outcome": f"quarantined {len(state['flaky_tests'])} tests"}


def skip(state: State) -> dict:
    return {"outcome": "left as is, nothing changed"}


builder = StateGraph(State)
builder.add_node("detect", detect)
builder.add_node("ask_approval", ask_approval)
builder.add_node("quarantine", quarantine)
builder.add_node("skip", skip)


builder.add_edge(START, "detect")
builder.add_edge("detect", "ask_approval")
builder.add_conditional_edges("ask_approval", route, ["quarantine", "skip"])
builder.add_edge("quarantine", END)
builder.add_edge("skip", END)

app = builder.compile(checkpointer=InMemorySaver())

if __name__ == "__main__":
    cfg = {"configurable": {"thread_id": "flaky-review-1"}}

    first = app.invoke({}, cfg)
    pause = first["__interrupt__"][0].value
    print("Graph paused. It is asking:")
    print(" ", pause["question"])
    for t in pause["tests"]:
        print("   -", t)
    print("Paused before node:", app.get_state(cfg).next)

    answer = sys.argv[1] if len(sys.argv) > 1 else input("\nYour answer: ")
    final = app.invoke(Command(resume=answer), cfg)
    print("\nResumed with", repr(answer), "->", final["outcome"])
  • Lines 3 to 5. interrupt(payload) freezes the graph and hands payload to the caller, and you resume it later with Command(resume=answer) on the same thread_id. A checkpointer is required: the pause has to be saved somewhere.
  • Lines 26 to 31, the pause. ask_approval calls interrupt() with the question and the two tests. Its answer is approved when it is y or yes, in any case and with spaces trimmed.
  • Lines 33 and 34, the router. Approved goes to quarantine, anything else to skip.
  • Lines 52 to 56, the flow. Start, detect, ask for approval, then quarantine or skip depending on the human review, and both end.
  • Lines 60 to 73, the caller. The first invoke() comes back paused, with the question in __interrupt__; line 71 takes the answer from the command line or asks for it, and line 72 resumes with it.

The file's own name. The usage lines of the docstring, 7 and 8, name the file 007_Human_In_The_Loop.py. In the repo it is 06_Human_In_Loop.py, so that is the name to run.

When you run it, you see something like magic, the instructor said: it asks you for an answer, because it has found two tests which are flaky in nature. If you say y, it will quarantine them; if you say no, it will resume as it is, or skip them. Run here on a terminal, typing yes at the prompt:

Terminal
python 06_Human_In_Loop.py
Output
Graph paused. It is asking:
  Quarantine these tests? (yes/no)
   - login_redirect
   - search_autocomplete
Paused before node: ('ask_approval',)

Your answer: yes

Resumed with 'yes' -> quarantined 2 tests

And typing no, the same run takes the other branch:

Terminal
python 06_Human_In_Loop.py
Output
Graph paused. It is asking:
  Quarantine these tests? (yes/no)
   - login_redirect
   - search_autocomplete
Paused before node: ('ask_approval',)

Your answer: no

Resumed with 'no' -> left as is, nothing changed

python 06_Human_In_Loop.py yes answers for you, as the docstring says, for CI or a demo. Most of this code was written by AI, the instructor pointed out: the point is that how you ask the user depends on your own use. Two things to take from all of it, the instructor said: your nodes are functions, and edges connect them, as in your n8n workflows, where a human in the loop is an option too.

What each typed answer leads to, through the real pause and resume, here and in the final finder of the last section (its ask_human node, line 94, has a rule of its own):

Typed answer The 06 file The final finder
"yes" quarantine quarantined: test_products_load
"y" quarantine quarantined: test_products_load
"Y" quarantine quarantined: test_products_load
"yeah" skip quarantined: test_products_load
" yes" quarantine quarantined: nothing
"no" skip quarantined: nothing
"n" skip quarantined: nothing
"", just Enter skip quarantined: nothing

The checkpointer is not optional. Line 58 compiled without it, the first invoke() still comes back paused, but nothing was saved to come back to:

Terminal
# line 58 as app = builder.compile()
python 06_Human_In_Loop.py yes 2>&1 | grep -E "^(Graph paused|ValueError)"
Output
Graph paused. It is asking:
ValueError: No checkpointer set

And skipping that get_state() call does not help: the resume itself stops with RuntimeError: Cannot use Command(resume=...) without checkpointer.

05

An LLM node: the model decides, Python routes

THE MODEL DECIDES, THE GRAPH STAYS IN CONTROL 07_LLM_Node.py DOOR IN START NODE, CALLS THE LLM classify structured output: one of four categories route(): Python ACTION NODE product_bug file a Jira bug for the dev team ACTION NODE test_bug fix the test code (locator / assertion) ACTION NODE environment ping DevOps, rerun when the env is healthy ACTION NODE flaky quarantine and rerun nightly Who decides what The LLM picks the category: a Triage with category and reason. route() is plain Python: it returns triage.category, the next node. The action is the node's, from ACTIONS, not the model's words.
Each action node ends the run. The four actions are the ACTIONS dictionary on lines 38 to 43.

Till here, the class had not used an LLM. If you want to add one, you have to first say which LLM you are working on, the instructor said. The idea, in the words of the file's docstring: the LLM classifies a failure log into a fixed category, with structured output, so it's a real enum, not prose; a normal Python router then reads that category and picks the next node. The model decides, the graph stays in control. In n8n too, the instructor said, an LLM could decide the category, and the rest of the flow remains absolutely the same.

llm.py, and the key

The LLM comes from a file named llm.py, which has the configuration of Groq, the instructor said. It reads the .env file and gets the Groq key from it:

llm.pyPython
"""Shared LLM factory for scripts 008-010. Reads chapter_18_LangGraph/.env."""
import os
from pathlib import Path

from dotenv import load_dotenv

CHAPTER_ROOT = Path(__file__).resolve().parents[1]   # recap/ -> chapter_18_LangGraph/
load_dotenv(CHAPTER_ROOT / ".env")
load_dotenv()


def has_llm() -> bool:
    return bool(os.getenv("GROQ_API_KEY"))


def get_llm(**settings):
    if not has_llm():
        raise SystemExit(
            "GROQ_API_KEY is not set. Copy chapter_18_LangGraph/.env.sample to .env "
            "and add a free key from https://console.groq.com/keys"
        )
    from langchain_groq import ChatGroq
    return ChatGroq(model=os.getenv("LLM_MODEL", "openai/gpt-oss-120b"), temperature=0, **settings)
  • Lines 7 to 9. It loads chapter_18_LangGraph/.env first, then any .env that load_dotenv() finds.
  • Lines 16 to 21. No GROQ_API_KEY, no LLM: the script stops with a message.
  • Line 23. The model is LLM_MODEL if you set it, otherwise openai/gpt-oss-120b, at temperature 0. In class, the model was named as a GPT 120 billion one.

In class, the first run stopped because langchain_groq was not installed. The deck's notes for this class have the install line for it, with python-dotenv too:

Terminal
pip install -q langchain-groq python-dotenv

The key goes in a .env file, which the class created by hand, with a key made on Groq's site. Pydantic, which the next file needs, was already installed.

No .env.sample in chapter 18. The message on lines 18 to 21 says to copy chapter_18_LangGraph/.env.sample, but the repo has no such file in chapter 18. Create the .env yourself, as the class did; the repo's .gitignore already keeps .env files out of Git.

The triage graph

07_LLM_Node.pyPython
"""008 - An LLM inside a node, and its answer driving the fork.

The LLM classifies a failure log into a fixed category (structured output, so
it's a real enum, not prose). 

A normal Python router then reads that category
and picks the next node. The model decides, the graph stays in control.
"""
from typing import Literal, TypedDict

from langgraph.graph import END, START, StateGraph
from pydantic import BaseModel, Field

from llm import get_llm

class Triage(BaseModel):
    category: Literal["product_bug", "test_bug", "environment", "flaky"]
    reason: str = Field(description="one sentence")

class State(TypedDict, total=False):
    test_name: str
    log: str
    triage: Triage
    action: str

classifier = get_llm().with_structured_output(Triage)

def classify(state: State) -> dict:
    t = classifier.invoke(
        "You triage failed UI tests. Classify this failure.\n"
        f"Test: {state['test_name']}\nLog:\n{state['log']}"
    )
    return {"triage": t}

def route(state: State) -> str:
    return state["triage"].category

ACTIONS = {
    "product_bug": "file a Jira bug for the dev team",
    "test_bug": "fix the test code (locator / assertion)",
    "environment": "ping DevOps, rerun when the env is healthy",
    "flaky": "quarantine and rerun nightly",
}

def make_action(category):
    return lambda state: {"action": ACTIONS[category]}

builder = StateGraph(State)
builder.add_node("classify", classify)


for cat in ACTIONS:
    builder.add_node(cat, make_action(cat))
    builder.add_edge(cat, END)
builder.add_edge(START, "classify")
builder.add_conditional_edges("classify", route, list(ACTIONS))
app = builder.compile()

FAILURES = [
    ("checkout_pay",
     "AssertionError: expected order total '$120.00' but got '$0.00'. API /cart returned 200 with total=0."),
    ("login_button",
     "TimeoutError: locator('#login-btn') not found. Page has button[data-test=login] instead."),
    ("search_results",
     "net::ERR_CONNECTION_REFUSED at https://staging.example.com - staging DB container restarting."),
]

if __name__ == "__main__":
    for name, log in FAILURES:
        out = app.invoke({"test_name": name, "log": log})
        t = out["triage"]
        print(f"{name:<15} -> {t.category:<12} | {out['action']}")
        print(f"{'':<15}    why: {t.reason}")
  • Lines 16 to 18, the categories. Product bug, test bug, environment and flaky, plus a reason of one sentence: a Literal inside a Pydantic BaseModel.
  • Lines 20 to 24, the state. The test name and the log go in; the triage and the action come out. This agent takes your logs and your test name, and adds the category by using the LLM, the instructor said.
  • Line 26. with_structured_output(Triage) makes the model answer in that shape.
  • Lines 28 to 33, the LLM node. It tells the model that it is triaging failed UI tests, with the test name and the log it received.
  • Lines 35 and 36, the router. Plain Python: it returns state["triage"].category, which is the name of the next node.
  • Lines 38 to 46, the actions. One node per category, each returning its action. Flaky: quarantine it and rerun nightly.
  • Lines 59 to 66, the failures. Suppose the failure has come from the checkout page, the instructor said: these stand for the real failures that come from Playwright, here a checkout total, a login button and the search results.

Without a key, it stops on line 26, before any test is classified:

Terminal
python 07_LLM_Node.py
Output
GROQ_API_KEY is not set. Copy chapter_18_LangGraph/.env.sample to .env and add a free key from https://console.groq.com/keys

The LLM in these notes. The class's LLM was Groq, with the instructor's key. These notes use no key and send nothing off the machine: in a copy of llm.py, line 22 builds a small local model through Ollama instead, gemma3:270m, and every other line runs as pushed. GROQ_API_KEY holds a placeholder word, only so that has_llm() lets the copy start; the local model never reads it.

Python
    from langchain_ollama import ChatOllama as ChatGroq
Terminal
LLM_MODEL=gemma3:270m python 07_LLM_Node.py
Output
checkout_pay    -> test_bug     | fix the test code (locator / assertion)
                   why: The test failed because the expected order total was not met.
login_button    -> test_bug     | fix the test code (locator / assertion)
                   why: Locator (#login-btn) is not found in the page, which is a common UI issue.
search_results  -> test_bug     | fix the test code (locator / assertion)
                   why: The test failed because the database connection was refused.

The local model put all three under one category. In class, Groq's answers were different, and the instructor read them out:

Test In class, on Groq Here, on the local model The action that ran here
checkout_pay a product bug test_bug fix the test code (locator / assertion)
login_button a test bug test_bug fix the test code (locator / assertion)
search_results an environment problem test_bug fix the test code (locator / assertion)

Whatever the model says, the graph routes it the same way: route() returns the category, and the action comes from that node, not from the model's words. The categories are fixed, too: each request carried product_bug, test_bug, environment and flaky as the only values allowed, and Triage(category="Flaky"), with a capital F, fails with a ValidationError.

For each failure, the instructor narrated the model's choice: does it fall to a product bug, a test bug, an environment, or is it a flaky test case? In class, the LLM's answer was a product bug for the checkout one, so the action was to file a bug; a test bug for the login one; and an environment problem for the search results. There was no flaky one. The router can be one line because the answer is a Triage with a fixed category: there is exactly one node for each of the four values, and nothing else validates.

06

The final flaky test finder

TWO BUILDS IN, A TRIAGED VERDICT OUT Project_FlakyTestFinderFinal.py READS 2 FILES load_builds PAIRS STATUSES compare THE LLM SAYS WHY triage WITH --HUMAN ask_human interrupt() asks first OTHERWISE, AUTO quarantine THEN END report flaky found nothing flaky solid arrow: always runs dashed arrow: a conditional edge compiled with InMemorySaver(): the pause in ask_human needs it The class's two builds, five tests each PASSED passed, passed 4 tests FLAKY passed, failed test_products_load BROKEN failed, failed no test
The edges are the ones LangGraph reports for the pushed file. The counts are its real run on the class's builds.

Whatever the class had learned, all seven concepts, comes together here. The instructor asked Claude for it: the requirement gave it the TTACart login page, and asked for the minimum code, using what the exercises from 01 to 07 had covered. The commit that brought it describes it as a real 5-test TTACart login suite run twice: it compares the pair of reports to find the flaky test, asks Groq why it flaked, then quarantines it automatically or after an interrupt() asks a human.

The scenario

Two panels on cream paper, each with a wooden noticeboard on short legs. Left, titled Two builds, with the sublabel Pass, then fail: two rows of five blank index cards; every card in the top row has a grey tick, and in the bottom row four have a tick and the last one a terracotta cross, the two last cards outlined together as a pair. Right, titled The culprit, with the sublabel Flaky in nature: only that pair is pinned on the board, a tick above a cross, behind a large magnifying glass with a terracotta rim; the other cards lie stacked on the floor.
The whiteboard's story: across two builds most tests pass both times, and the real culprit is the one that passed once and failed once.

This is a lightweight framework of Playwright, the instructor said, and it can be Selenium too. It has five test cases, run as build number one and build number two. On the whiteboard, tests that pass in both builds are fine. One that passes, but fails the second time, is the real flaky test. One that fails and fails is a failure. So the real culprit is the one that is flaky in nature, and that is the one to find with the LangGraph agent. Its verdict is the final one, which you share with your QA lead.

The build files that the class's run left in the repo are simpler than the whiteboard: all five tests passed in build 1, and in build 2 only test_products_load failed. No test failed in both. The two files differ in the build number and in this entry:

builds/build_2.jsonJSON
    {
      "test": "test_products_load",
      "status": "failed"
    }

The Playwright suite

It's a very simple framework, the instructor said: no page object model, nothing at all, just a username and a password. In the file, the five tests are a valid login, an invalid password, an empty username, a locked-out user and the products loading. Its docstring says which one is flaky, and why:

pw_tests/test_login.pyPython
"""5 real Playwright login tests against TTACart.

Test 5 is the planted flaky one. Its flakiness is SIMULATED, not random: with
FLAKY_BUILD=2 it waits only 50ms for the product grid, which it never makes.
Simulated on purpose, so the lesson is reproducible in a classroom; a genuinely
random test would make the demo a coin toss.
"""
pw_tests/test_login.pyPython
def test_products_load(page: Page) -> None:
    """The planted flaky test: a timeout too tight to meet in build 2."""
    login(page, USER, PASSWORD)
    expect(page.locator("article")).to_have_count(6, timeout=50 if FLAKY else 10_000)

In build 2, FLAKY_BUILD is 2, so test_products_load gives the six products only 50 milliseconds to appear. run_build.py runs the suite once and writes one build file:

run_build.pyPython
def main(build: str) -> None:
    BUILDS.mkdir(exist_ok=True)
    xml = HERE / f".build_{build}.xml"
    env = {**os.environ, "FLAKY_BUILD": build}
    subprocess.run([str(PYTHON), "-m", "pytest", "pw_tests", "-q", f"--junitxml={xml}"],
                   cwd=HERE, env=env, capture_output=True, text=True)

    results = [
        {"test": tc.get("name").split("[")[0],
         "status": "failed" if any(c.tag in ("failure", "error") for c in tc) else "passed"}
        for tc in ET.parse(xml).getroot().iter("testcase")
    ]
    out = BUILDS / f"build_{build}.json"
    out.write_text(json.dumps({"build": int(build), "results": results}, indent=2))
    xml.unlink()

    passed = sum(r["status"] == "passed" for r in results)
    print(f"build {build}: {passed}/{len(results)} passed -> {out.name}")
    for r in results:
        print(f"   {r['status']:<7} {r['test']}")

Its docstring calls JUnit XML pytest's built-in report, so there is no plugin to install. The tests sign in to TTACart, the Testing Academy's practice shop, so they were not run for these notes; the login details are in the task post. The finder below reads the two build files that the class's own run wrote: their layout is exactly the one line 34 writes.

The code

Project_FlakyTestFinderFinal.pyPython
"""Project (final) - two Playwright builds in, a triaged verdict out.

Everything from 01-07 in one graph:
  01 state     a TypedDict backpack, nodes return only what they changed
  02 pipeline  load -> compare -> ...
  03 branch    skip the LLM entirely when nothing is flaky
  04 loop idea one status is an observation, a pair is a verdict
  05 memory    a checkpointer, which interrupt() requires
  06 human     interrupt() pauses before quarantining
  07 LLM node  Groq classifies WHY it flaked; Python still routes

    venv/bin/python run_build.py 1 && venv/bin/python run_build.py 2
    venv/bin/python Project_FlakyTestFinderFinal.py              # auto-quarantine
    venv/bin/python Project_FlakyTestFinderFinal.py --human      # ask me first
"""

The docstring maps each lesson to its part of the graph, as the diagram at the top of this page shows, and gives the three commands: two builds, then the finder, with or without --human.

Project_FlakyTestFinderFinal.pyPython
BUILDS = Path(__file__).parent / "builds"


class Triage(BaseModel):
    """07 - structured output, so the answer is an enum and not prose."""
    cause: Literal["timing", "test_bug", "product_bug", "environment"]
    reason: str = Field(description="one sentence")


class State(TypedDict, total=False):
    runs: list[dict]
    passed: list[str]
    flaky: list[str]
    broken: list[str]
    triage: Triage
    quarantined: str
    verdict: str


# ---------------------------------------------------------------- nodes
def load_builds(state: State) -> dict:
    runs = [{r["test"]: r["status"] for r in json.loads(p.read_text())["results"]}
            for p in (BUILDS / "build_1.json", BUILDS / "build_2.json")]
    print(f"loaded 2 builds, {len(runs[0])} tests each")
    return {"runs": runs}


def compare(state: State) -> dict:
    """The whole rule: compare the PAIR, never a single status."""
    b1, b2 = state["runs"]
    passed, flaky, broken = [], [], []
    for test in b1:
        pair = (b1[test], b2[test])
        target = (passed if pair == ("passed", "passed")
                  else broken if pair == ("failed", "failed") else flaky)
        target.append(test)
    return {"passed": passed, "flaky": flaky, "broken": broken}


def route_after_compare(state: State) -> Literal["triage", "report"]:
    """03 - no flaky test means no LLM call, and no spend."""
    return "triage" if state["flaky"] else "report"

First the triage, the instructor said: the cause is timing, a test bug, a product bug or the environment. The state captures the runs, the passed, flaky and broken tests, the triage and the quarantine. load_builds reads build one and build two, compare labels every test by its pair of statuses, and route_after_compare goes to the LLM only when a flaky test was found.

Project_FlakyTestFinderFinal.pyPython
def triage(state: State) -> dict:
    """07 - Groq says WHY. Python still decides what happens next."""
    b1, b2 = state["runs"]
    test = state["flaky"][0]
    t = get_llm().with_structured_output(Triage).invoke(
        "You triage flaky UI tests. One sentence.\n"
        f"Test: {test}\nBuild 1: {b1[test]}   Build 2: {b2[test]}\n"
        "It asserts the product grid has 6 items after login."
    )
    print(f"groq: {t.cause} - {t.reason}")
    return {"triage": t}


def route_quarantine(state: State) -> Literal["ask_human", "quarantine"]:
    """03 again - the --human flag picks the lane."""
    return "ask_human" if "--human" in sys.argv else "quarantine"


def ask_human(state: State) -> dict:
    """06 - interrupt() freezes the graph until someone answers."""
    answer = interrupt({"question": f"Quarantine {state['flaky'][0]}?",
                        "cause": state["triage"].cause})
    return {"quarantined": state["flaky"][0] if str(answer).lower().startswith("y")
            else ""}


def quarantine(state: State) -> dict:
    return {"quarantined": state["flaky"][0]}

triage asks the LLM why the test flaked, route_quarantine reads --human from the command line, ask_human pauses with interrupt(), and quarantine quarantines without asking.

Project_FlakyTestFinderFinal.pyPython
def report(state: State) -> dict:
    b1, b2 = state["runs"]
    rows = [f"{'TEST':<24}{'BUILD 1':<9}{'BUILD 2':<9}VERDICT", "-" * 56]
    label = {t: "PASSED" for t in state["passed"]}
    label.update({t: "FLAKY" for t in state["flaky"]})
    label.update({t: "BROKEN" for t in state["broken"]})
    rows += [f"{t:<24}{b1[t]:<9}{b2[t]:<9}{label[t]}" for t in b1]
    rows += ["", f"{len(state['passed'])} passed, {len(state['flaky'])} flaky, "
                 f"{len(state['broken'])} broken"]
    if state.get("triage"):
        rows.append(f"cause: {state['triage'].cause} - {state['triage'].reason}")
    q = state.get("quarantined")
    rows.append(f"quarantined: {q}" if q else "quarantined: nothing")
    return {"verdict": "\n".join(rows)}


# ---------------------------------------------------------------- graph
builder = StateGraph(State)
for name, fn in [("load_builds", load_builds), ("compare", compare), ("triage", triage),
                 ("ask_human", ask_human), ("quarantine", quarantine), ("report", report)]:
    builder.add_node(name, fn)

builder.add_edge(START, "load_builds")
builder.add_edge("load_builds", "compare")
builder.add_conditional_edges("compare", route_after_compare, ["triage", "report"])
builder.add_conditional_edges("triage", route_quarantine, ["ask_human", "quarantine"])
builder.add_edge("ask_human", "report")
builder.add_edge("quarantine", "report")
builder.add_edge("report", END)

app = builder.compile(checkpointer=InMemorySaver())      # 05 - interrupt needs it

if __name__ == "__main__":
    cfg = {"configurable": {"thread_id": "flaky-final"}}
    out = app.invoke({}, cfg)

    if "__interrupt__" in out:                            # 06 - paused, ask and resume
        q = out["__interrupt__"][0].value
        answer = input(f"\n{q['question']} (cause: {q['cause']}) [y/N]: ")
        out = app.invoke(Command(resume=answer), cfg)

    print(f"\n{out['verdict']}")

report builds the table. Everything has been added as a node, and all the edges are added properly, the instructor said: we have an agent which is 24x7. The checkpointer on line 132 is there because interrupt() needs it.

Running it

Without a key, the run gets as far as the LLM:

Terminal
python Project_FlakyTestFinderFinal.py
Output
loaded 2 builds, 5 tests each
GROQ_API_KEY is not set. Copy chapter_18_LangGraph/.env.sample to .env and add a free key from https://console.groq.com/keys

With the local stand-in of the last section, run with no argument, it quarantines on its own:

Terminal
LLM_MODEL=gemma3:270m python Project_FlakyTestFinderFinal.py
Output
loaded 2 builds, 5 tests each
groq: product_bug - The product grid is not fully loaded, and the load time is too long.

TEST                    BUILD 1  BUILD 2  VERDICT
--------------------------------------------------------
test_valid_login        passed   passed   PASSED
test_invalid_password   passed   passed   PASSED
test_empty_username     passed   passed   PASSED
test_locked_out_user    passed   passed   PASSED
test_products_load      passed   failed   FLAKY

4 passed, 1 flaky, 0 broken
cause: product_bug - The product grid is not fully loaded, and the load time is too long.
quarantined: test_products_load

The groq: label on the second line is the code's own text; the answer came from gemma3:270m. In class, the run loaded the five tests and marked the verdict as flaky, and this report you can share with your manager, the instructor said. The README's copy of a Groq run ends with cause: timing - the test checks the product grid before the async load completes and quarantined: test_products_load.

With --human, it asks first. In class, the question came with the LLM's reason, about the test checking the product grid before the session had loaded. If you say no, it skips, the instructor said; with a yes, the test is quarantined, as the runs here show. Answered n on a terminal here:

Terminal
LLM_MODEL=gemma3:270m python Project_FlakyTestFinderFinal.py --human
Output
loaded 2 builds, 5 tests each
groq: product_bug - The product grid is not fully loaded, and the load time is too long.

Quarantine test_products_load? (cause: product_bug) [y/N]: n
Deserializing unregistered type __main__.Triage from checkpoint. This will be blocked in a future version. Set LANGGRAPH_STRICT_MSGPACK=true to block now, or add to allowed_msgpack_modules to allow explicitly: [('__main__', 'Triage')]

TEST                    BUILD 1  BUILD 2  VERDICT
--------------------------------------------------------
test_valid_login        passed   passed   PASSED
test_invalid_password   passed   passed   PASSED
test_empty_username     passed   passed   PASSED
test_locked_out_user    passed   passed   PASSED
test_products_load      passed   failed   FLAKY

4 passed, 1 flaky, 0 broken
cause: product_bug - The product grid is not fully loaded, and the load time is too long.
quarantined: nothing

The test is still marked flaky even when you say no, as the class pointed out: the table is the same, and the last line reads quarantined: nothing. Answered y, the same run ends with quarantined: test_products_load instead.

The strict line is a warning, not an option. In class, the line in the middle was read as a way to block the test or the flow: set strict to true. It is LangGraph's own warning, printed when the graph resumes and reads the Triage answer back from the checkpoint. LANGGRAPH_STRICT_MSGPACK=true limits which Python types LangGraph rebuilds from saved state; it blocks no test and no build. Run again with it set and answered n, the finder prints the same lines without the warning, because the strict list already includes the types the state declares, Triage among them. The pushed finder has no option that blocks a build.

What the branches do

The same finder, on the class's builds and on three changed copies of them:

Build files LLM requests Summary line Quarantined
the class's two builds 1 4 passed, 1 flaky, 0 broken test_products_load
build 2 with build 1's results 0 5 passed, 0 flaky, 0 broken nothing
test_products_load failed in both 0 4 passed, 0 flaky, 1 broken nothing
test_valid_login failing in build 2 as well 1 3 passed, 2 flaky, 0 broken test_valid_login

With nothing flaky, the finder goes straight to the report, as line 68 promises: no flaky test means no LLM call, and no spend. That run needs no key at all:

Terminal
# build 2 with build 1's results
python Project_FlakyTestFinderFinal.py
Output
loaded 2 builds, 5 tests each

TEST                    BUILD 1  BUILD 2  VERDICT
--------------------------------------------------------
test_valid_login        passed   passed   PASSED
test_invalid_password   passed   passed   PASSED
test_empty_username     passed   passed   PASSED
test_locked_out_user    passed   passed   PASSED
test_products_load      passed   passed   PASSED

5 passed, 0 flaky, 0 broken
quarantined: nothing

With two flaky tests, only the first one in build order is triaged and quarantined, because lines 75 and 99 take state["flaky"][0]:

Terminal
# build 2 with test_valid_login failing as well
LLM_MODEL=gemma3:270m python Project_FlakyTestFinderFinal.py
Output
loaded 2 builds, 5 tests each
groq: product_bug - The product grid is not valid, and it's not responding to the user's input.

TEST                    BUILD 1  BUILD 2  VERDICT
--------------------------------------------------------
test_valid_login        passed   failed   FLAKY
test_invalid_password   passed   passed   PASSED
test_empty_username     passed   passed   PASSED
test_locked_out_user    passed   passed   PASSED
test_products_load      passed   failed   FLAKY

3 passed, 2 flaky, 0 broken
cause: product_bug - The product grid is not valid, and it's not responding to the user's input.
quarantined: test_valid_login

And the prompt is the same whatever test flipped: the last line of the prompt on lines 77 to 79 describes the product grid. The request for test_valid_login carried exactly this:

Text
You triage flaky UI tests. One sentence.
Test: test_valid_login
Build 1: passed   Build 2: failed
It asserts the product grid has 6 items after login.

The README adds its own caveat: two builds can only suspect flakiness, since a test that fails 1 run in 20 looks perfectly stable in both.

07

The TypeScript twin

Question. Sir, we can have the TS script as well for this, right?

Show the answer

Answer. Yes, the instructor answered: you can have the same AI agent created in TypeScript too, if you want to. The repo has it, in the ts folder: the same graph on LangGraph JS, in the words of the commit message, written in TypeScript and run with tsx.

JavaScript or TypeScript. In class, the answer went on: the instructor thought LangGraph supports JS, not TS, and was pretty much sure the generated version would be in JS. The version in the repo is a TypeScript file, flakyTestFinderFinal.ts, which imports @langchain/langgraph, LangGraph's JavaScript library, and npm run finder runs it as it is. It ran here.

Here we have TypeScript too, the instructor said: its test cases are in a login spec, and you see the same process; the instructor thought it had run with Playwright too. It had: the two reports in ts/builds are Playwright's own JSON reports, written by Playwright Test 1.65.1 at 20:41 IST, near the end of the class. The scripts that make them, and the finder's:

ts/package.jsonJSON
  "scripts": {
    "build:1": "playwright test --reporter=json > builds/build_1.json",
    "build:2": "FLAKY_BUILD=2 playwright test --reporter=json > builds/build_2.json",
    "finder": "tsx flakyTestFinderFinal.ts"
  },
ts/playwright.config.tsTypeScript
import { defineConfig } from "@playwright/test";

export default defineConfig({
  testDir: "./tests",
  retries: 0,                       // the AGENT decides about retries, not the runner
  use: { browserName: "chromium" },
});

The LLM factory is the same as llm.py, and reads the same .env:

ts/llm.tsTypeScript
/** Shared LLM factory. Reads chapter_18_LangGraph/.env, same as the Python llm.py. */
import { ChatGroq } from "@langchain/groq";
import dotenv from "dotenv";
import path from "node:path";
import { fileURLToPath } from "node:url";

const HERE = path.dirname(fileURLToPath(import.meta.url));
dotenv.config({ path: path.resolve(HERE, "../../.env") });   // ts/ -> recap/ -> chapter_18

export function getLlm() {
  if (!process.env.GROQ_API_KEY) {
    throw new Error("GROQ_API_KEY is not set. Add it to chapter_18_LangGraph/.env");
  }
  return new ChatGroq({
    model: process.env.LLM_MODEL ?? "openai/gpt-oss-120b",
    temperature: 0,
  });
}
ts/flakyTestFinderFinal.tsTypeScript
/**
 * Project (final, TypeScript) - two Playwright builds in, a triaged verdict out.
 *
 * The same graph as Project_FlakyTestFinderFinal.py. Differences are all
 * LangGraph-JS API, not design:
 *   - state is an Annotation.Root({...}) instead of a TypedDict
 *   - addConditionalEdges takes the mapping as the third argument
 *   - interrupt() throws a GraphInterrupt, so the caller checks __interrupt__
 *   - a node may NOT share a name with a state channel, so the node that
 *     fills the `triage` channel has to be called something else
 *
 *   npm run build:1 && npm run build:2
 *   npm run finder              # auto-quarantine
 *   npm run finder -- --human   # ask me first
 */
ts/flakyTestFinderFinal.tsTypeScript
/** 07 - structured output, so the answer is a union type and not prose. */
const Triage = z.object({
  cause: z.enum(["timing", "test_bug", "product_bug", "environment"]),
  reason: z.string().describe("one sentence"),
});
type Triage = z.infer<typeof Triage>;

/** 01 - state. Each channel replaces its old value when a node returns it. */
const State = Annotation.Root({
  runs: Annotation<Record<string, string>[]>,
  passed: Annotation<string[]>,
  flaky: Annotation<string[]>,
  broken: Annotation<string[]>,
  triage: Annotation<Triage | undefined>,
  quarantined: Annotation<string>,
  verdict: Annotation<string>,
});
type S = typeof State.State;

/** Playwright's JSON reporter nests specs one level deeper than you expect. */
function readBuild(n: number): Record<string, string> {
  const r = JSON.parse(fs.readFileSync(path.join(BUILDS, `build_${n}.json`), "utf8"));
  const specs = r.suites[0].suites?.[0]?.specs ?? r.suites[0].specs;
  return Object.fromEntries(specs.map((s: any) => [s.title, s.ok ? "passed" : "failed"]));
}

The state is an Annotation.Root, the triage shape is a zod schema, and readBuild takes each spec's ok from Playwright's report, where the Python version reads status.

ts/flakyTestFinderFinal.tsTypeScript
// ---------------------------------------------------------------- graph
const app = new StateGraph(State)
  .addNode("load_builds", loadBuilds)
  .addNode("compare", compare)
  .addNode("triage_flaky", triage)
  .addNode("ask_human", askHuman)
  .addNode("quarantine", quarantine)
  .addNode("report", report)
  .addEdge(START, "load_builds")
  .addEdge("load_builds", "compare")
  .addConditionalEdges("compare", routeAfterCompare, ["triage_flaky", "report"])
  .addConditionalEdges("triage_flaky", routeQuarantine, ["ask_human", "quarantine"])
  .addEdge("ask_human", "report")
  .addEdge("quarantine", "report")
  .addEdge("report", END)
  .compile({ checkpointer: new MemorySaver() });   // 05 - interrupt needs it

const cfg = { configurable: { thread_id: "flaky-final-ts" } };
let out = await app.invoke({}, cfg);

if ((out as any).__interrupt__) {                   // 06 - paused, ask and resume
  const q = (out as any).__interrupt__[0].value;
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
  const answer = await rl.question(`\n${q.question} (cause: ${q.cause}) [y/N]: `);
  rl.close();
  out = await app.invoke(new Command({ resume: answer }), cfg);
}

console.log(`\n${out.verdict}`);

The README sets the two side by side:

Difference Python TypeScript
State TypedDict Annotation.Root({...})
Builder mutate a builder object chained .addNode().addEdge()
Node vs channel names may be the same must differ, or it throws
Test report --junitxml + xml.etree --reporter=json, built in

Without a key, the twin stops in the same place, in getLlm(), called from triage:

Terminal
cd ts
npm run finder 2>&1 | head -n 13
Output
> finder
> tsx flakyTestFinderFinal.ts

loaded 2 builds, 5 tests each
llm.ts:12
    throw new Error("GROQ_API_KEY is not set. Add it to chapter_18_LangGraph/.env");
          ^

Error: GROQ_API_KEY is not set. Add it to chapter_18_LangGraph/.env
    at getLlm (llm.ts:12:11)
    at RunnableCallable.triage (flakyTestFinderFinal.ts:80:19)

With the same one-line stand-in in a copy of llm.ts, line 2 importing ChatOllama from @langchain/ollama as ChatGroq, it reads the class's two Playwright reports:

Terminal
LLM_MODEL=gemma3:270m npm run finder
Output
> finder
> tsx flakyTestFinderFinal.ts

loaded 2 builds, 5 tests each
groq: product_bug - The product grid is not fully loaded, and the user's login attempt failed.

TEST                  BUILD 1  BUILD 2  VERDICT
------------------------------------------------------
valid_login           passed   passed   PASSED
invalid_password      passed   passed   PASSED
empty_username        passed   passed   PASSED
locked_out_user       passed   passed   PASSED
products_load         passed   failed   FLAKY

4 passed, 1 flaky, 0 broken
cause: product_bug - The product grid is not fully loaded, and the user's login attempt failed.
quarantined: products_load

The test names are the spec's titles. With -- --human, answered n, it ends with quarantined: nothing, and answered y, with quarantined: products_load.

The port surprise. The commit message calls it worth the file it cost: a node may not share a name with a state channel in LangGraph JS. The Python finder has a node named triage that fills the triage key, and LangGraph in Python allows it. Line 122 of the twin, with the node named triage the same way:

Terminal
# line 122 as .addNode("triage", triage)
npm run finder 2>&1 | head -n 12
Output
> finder
> tsx flakyTestFinderFinal.ts

node_modules/@langchain/langgraph/src/graph/state.ts:1126
        throw new Error(
              ^

Error: triage is already being used as a state attribute (a.k.a. a channel), cannot also be used as a node name.
    at StateGraph.addNode (node_modules/@langchain/langgraph/src/graph/state.ts:1126:15)
    at <anonymous> (flakyTestFinderFinal.ts:122:4)
08

Jenkins: a post-build action

Where do you run it? This will be your Jenkins post-build action, the instructor said, together with the run build file: in Jenkins, you will only use this file, run_build.py, and it will automatically run your test cases and mark them as flaky. In the repo, the two jobs are split. run_build.py runs the suite and saves one build's results; the finder is the part that compares two builds and marks the flaky test, and its docstring, lines 12 to 14, runs them in that order: run_build.py 1, run_build.py 2, then the finder.

Question. How to connect this from Jenkins?

Show the answer

Answer. Very simple, the instructor answered: in Jenkins, in the post-build action, you can add this as a Python file. Whenever you run your Selenium or Playwright tests, add this file in the post-build action, and it will run automatically.

09

Tasks and announcements

  • The code. It is in the batch repository, in chapter 18's recap folder.
  • Build your own agents. Start with the very basic ones, the instructor said: the hello graph, then linear, conditional and loop. When you reach the advanced level, find the AI agents you want to create on app.thetestingacademy.com, take the idea, create it with LangGraph, deploy it and use it; a test documentation creator, for example. On the site, the AI hub's AI agents tab lists the agents built in this course.
  • The easy way first. You can create any kind of LangGraph agent, the instructor said: the easiest way is by creating it in n8n, the second easiest is LangFlow, and if you want more control, LangGraph.
  • Use AI. Use AI as much as you can now, the instructor said: you have the power now, because you understand the code too, some part of it.
  • What comes next. This marks the end of LangGraph, but learning is not going to stop, the instructor said: a lot of upcoming sessions are being planned.

Task: rewatch and build it. Rewatch the video one or two times, and try to create it by yourself. Try to understand the concepts too: how you can change it, and which part you can change.

Show the answer

Answer. LangGraph has only these concepts, the instructor said: memory, checkpoints, linear or conditional loops, and just running directly. Each has a file on this page: run 05, 06 and 07, then the finder, and compare what they print with the outputs above.

Task: three agents. Create a root cause analysis agent, a bug triaging agent and a flaky test agent with LangGraph, and deploy them. If you create these three, you will start understanding all of it, the instructor said.

Show the answer

Answer. The final finder is the third one, and 07 is the shape of a triage agent: an LLM node that answers with one of a fixed set of categories, and a Python router that picks the next node from it.