What this class covered
- The Lang family, and where LangGraph fits
- Why a graph: an agent has many decisions
- Stateful: it remembers
- Four things to remember, and the trip
- A chain, a graph, and how every agent looks
- Installing LangGraph in a virtual environment
- Exercise 1: the hello graph
- Exercise 2: a linear pipeline
- Growing up: a state that gains fields
- Exercise 3: conditional routing
- Exercise 4: a retry loop
- Mini project: find the flaky test by comparing two builds
- Jenkins and the JSON report
- Tasks and announcements: practise the exercises, and Part 2 on Friday evening
- LangGraph is LangChain plus states, branching logic, loops and a human in the loop, as the class put it. Installing it brings
langchain-core, not thelangchainpackage. - The state is one shared dictionary. A node is a plain function: it reads the state and returns only the keys it changed.
- A normal edge always runs. A conditional edge calls a function that returns the name of the next node. A loop is an edge that points back.
compile()turns the builder into an app,invoke()runs it and returns the final state, andstream()withstream_mode="updates"shows what each node changed.- In exercise 3, every status other than
passedandfailedgoes to quarantine, a skipped test included. - In exercise 4,
MAX_ATTEMPTS = 3counts the first run too: a test runs at most three times. - One status is not a verdict: the mini finder compares two builds. A real Playwright run leaves a JSON report only if the
jsonreporter is configured.
The Lang family, and where LangGraph fits
Last class taught LangGraph through four demos and a full Playwright flaky finder. This one is Part 1 of LangGraph Explained: it re-teaches those four ideas in miniature, in the words of its commit, and then applies them. You can follow it without the last one.
Before LangGraph, there is one important thing to understand, the instructor said: there is a Lang family, LangX.
- LangFlow is a low-code visual editor, which can help you create AI agents. This batch has already discussed it.
- LangChain is very popular, and is also used to create LLM-based AI agents.
- LangGraph is the one for today.
- LangSmith and LangFuse are used for traceability and observability. They are not used to create AI agents: they are for when you want to observe how your agents are working, or when you want to trace, which basically means to use it as a debug or something.
A family by name. LangChain, LangGraph and LangSmith come from the LangChain team, langchain-ai on GitHub. LangFlow and LangFuse are separate open-source projects, langflow-ai and langfuse there.
There is no problem with LangChain, the instructor said: its agents are good, they are for the basics, and they work absolutely fine. But when you want some extra functionality, state management, it is a different use case altogether: some people prefer state-management AI agents, and that is where they use LangGraph. State management means it remembers a few things you have done: if one agent has done a particular task, there is a state, and another agent can start from there. You do not have to do everything from scratch.
Question. Does it mean that LangChain is not used?
Show the answer
Answer. LangChain is used, the instructor answered: LangGraph actually uses it internally. The package list shows how: pip show langgraph, run below, requires langchain-core, and the langchain package itself is not installed with it.
LangGraph is a 100% open-source Python framework, the instructor said, and the beauty is that it now supports JavaScript too. The deck calls it an "open-source Python/JS library (from the LangChain team) for building LLM applications as a graph".
Why a graph: an agent has many decisions
LangGraph builds an LLM application as a graph. AI agents are not straight, the instructor said: they are probabilistic in nature. If you create an AI agent, it can have multiple decisions: a test case can fail, a test case can pass, a test case can skip. Whenever there are multiple options, you have to use a graph, and every graph has nodes and edges. These options can open further options.
A real scenario. We are using a LangGraph agent which checks the flaky test case, the instructor said. When a Playwright test case comes, it first checks if the test passed or failed. On a fail, it checks the behaviour: was it passed in the previous to previous build, yes or no? All this is nothing but graph decisions, and if you want to build this agent, you have to use LangGraph. You can create it with normal LangChain, but it will be difficult to maintain in the future.
Because it is a graph, remember this: it can branch, it can loop, it can pause, or it can resume. In LangChain you can have one state, a second, a third, a fourth; in LangGraph the agents can take multiple decisions. That is why it is widely used for AI agents, the instructor said, and it is something that we will also use.
Question. Whenever we say graph, what is the need of the graph?
Worth practising too: what is LangGraph, in one sentence?
Show the answer
Answer. AI agents are not straight, the instructor answered: an agent can have multiple decisions, and whenever there are multiple options you have to use a graph, with its nodes and edges. In one sentence, from the deck: LangGraph is a stateful graph orchestrator for LLM workflows.
Stateful: it remembers
LangGraph is a stateful graph orchestrator. Stateful basically means it remembers the states, the instructor said: whatever you have done with one agent, it remembers, and you can share the same state with another agent, and another. In LangChain that was very difficult, the instructor said, because LangChain does not maintain any kind of state.
Nodes are nothing but functions, edges decide what to run next, and the state is a shared memory that flows through them.
The analogy was our own memory. We also use a graph, the instructor said, as we get mature: you remember the decisions you have taken, and you can go back to see which decision it was, and which branch you took. So our brain is nothing but a graph: it remembers decisions, and it has a state, branches, a loop and a running mechanism. LangGraph uses the same mechanism.
Four things to remember, and the trip
If you get confused at any time, just remember these four important rules, the instructor said:
- The state is the single source of truth. It can be a dictionary, which has all the information about the updates. The deck adds that one Python dict, whose shape you define, travels through the whole graph, and every node reads from it and returns the keys it wants to change.
- Nodes are plain functions. They call the LLM, the DB and other things, and based on that they do the work.
- Edges are the flow, however you want it: normal flow, conditional flow, branches or loops. In the deck, a loop is just an edge pointing backwards.
- It is built for production. You can have a checkpoint, and go back to it. You can have a human in the loop, one of the best features: for a Playwright test case that is flaky in nature, LangGraph will ask you, should I mark this as a flaky test case and report to your manager? You can stream, time travel and debug: it can maintain the states, so you can roll back if you want to.
For the words, the class took the example of a trip:
| In LangGraph | On the trip | In this class's code |
|---|---|---|
| State | a backpack, where you store everything | class State(TypedDict) |
| Node | you, who can work | a function, add_node |
| Edge | an arrow: what is the next one | add_edge |
| Condition | a signpost | add_conditional_edges |
| Start and stop | the doors | START and END |
| Compile | the lock | builder.compile() |
A chain, a graph, and how every agent looks
You build something, you test something, and you report: a plain chain, only next, next, next. This is what you do in LangChain, a step-by-step process, the instructor said. But in real life nothing is simple: you have decisions, branches and loops. You build and you test. If the test passes, you report; if it fails, you retry, and only if the retry passes do you say that yes, this is passed. This is exactly what LangGraph is very good for.
Where it is useful, especially for QA, the instructor said:
- It is great for AI agents, retries and branching workflows. If you want to develop a flaky test case agent, it is the best use case for QA.
- It can store your states for debugging, and it can resume from the checkpoints, which we will see.
- It can work with real production systems, and connect with a database, or anything else you want.
- The same pattern scales from tiny graphs to multi-agent systems.
How every LangGraph agent looks. The figure above is drawn from the class's words. You start something. You read the state, which means your backpack. You run something, a certain task. You update the state, your backpack. Then you take decisions: if a loop is required, you loop, and if it is not, you end.
So LangGraph is nothing but LangChain plus states, plus branching logic, plus loops, plus a human in the loop, the instructor said: a plus-plus variant, where plus-plus basically means increment. It is a big brother of LangChain, with certain extra features that you can use.
For your interview, the class went through a couple of definitions. LangGraph is an open-source Python library, created by the same team as LangChain, for building an LLM application as a graph. Our life is a graph too, the instructor said: it is not straight, we have branches, and we do certain tasks in a loop. The important one, as the deck writes it:
LangGraph is a stateful graph orchestrator for LLM workflows. Nodes are functions, edges decide what runs next, and state is the shared memory that flows through them.
Installing LangGraph in a virtual environment
The class worked in a fresh folder, chapter 18's recap, with nothing in it but an empty test.py. In the terminal, go to that folder, then create and activate a virtual environment, then install:
cd chapter_18_LangGraph/recap
virtualenv venv
source venv/bin/activate
pip install -U langgraph
A virtual environment is a sandbox version of a Python environment, the instructor said: in different folders you can have different versions of Python installed, and the recap folder has Python 3.12. The moment you create it, you find a folder named venv. If the virtualenv command is not installed, pip install virtualenv installs it. The -U is from the deck's version of the install line.
What was installed, and what LangGraph itself requires:
pip show langgraph | grep -E "^(Name|Version|Requires):"
Name: langgraph
Version: 1.2.24
Requires: langchain-core, langgraph-checkpoint, langgraph-prebuilt, langgraph-sdk, pydantic, xxhash
Exercise 1: the hello graph
The empty file was renamed 01_Hello_Graph.py. There are two things to remember, the instructor said: the shared memory, and how to create a flow, the workflow. They are the comments on the first two lines.
# Shared memory
# workflow
from typing import TypedDict
from langgraph.graph import END, START, StateGraph
class State(TypedDict):
tester: str
greeting: str
def greet(state: State) -> dict:
return {"greeting": f"Hello {state['tester']}, your first graph ran."}
builder = StateGraph(State)
builder.add_node("greet", greet)
builder.add_edge(START, "greet")
builder.add_edge("greet", END)
app = builder.compile()
if __name__ == "__main__":
result = app.invoke({"tester": "Pramod"})
print(result["greeting"])
print("\nFinal state:", result)
print("\nThe graph as Mermaid (paste into mermaid.live):")
print(app.get_graph().draw_mermaid())
python 01_Hello_Graph.py
Hello Pramod, your first graph ran.
Final state: {'tester': 'Pramod', 'greeting': 'Hello Pramod, your first graph ran.'}
The graph as Mermaid (paste into mermaid.live):
---
config:
flowchart:
curve: linear
---
graph TD;
__start__([<p>__start__</p>]):::first
greet(greet)
__end__([<p>__end__</p>]):::last
__start__ --> greet;
greet --> __end__;
classDef default fill:#f2f0ff,line-height:1.2
classDef first fill-opacity:0
classDef last fill:#bfb6fc
- Lines 4 and 5, the imports. A typed dictionary,
TypedDict, is key-value pairs: a container, like a bag, where you store everything. Fromlanggraph.graphyou import three things:END,STARTandStateGraph. The editor showed an error on the import, that it could not be found. It is a known issue that sometimes happens, the instructor said, to be ignored for now; when the file ran, it was not an error actually. - Lines 7 to 9, the shared memory. A class named
Stateinherits the typed dictionary and has only two pieces of information, the tester and a greeting. No comma is required, because this is Python. Whatever the flow does is stored here, so both are available at every step: a shared memory between the steps. - Lines 12 and 13, the node.
greettakes the state and returns a dictionary. A node returns only what it has changed. - Lines 15 to 19, the graph. A builder made from
StateGraph(State); one node, because there is only one function; and two edges, start to greet and greet to end. - Lines 21 to 28, run it. You have to compile in the end, and then invoke. The file prints the greeting, the final state, and the graph as Mermaid.
Question. The greeting says hello and a name. How is this name coming?
Worth practising too: what does greet return, and what does invoke() return?
Show the answer
Answer. You invoked, and passed the tester, the instructor answered: this is the state that you have passed. The greet function ran automatically when you invoked, the state came to it, and it got the tester value, which is why the value is printing. greet returns one key, greeting; invoke() returns the whole state, a plain dict, with both keys.
The state after each step, read from the running graph:
| Step | What happens | The state after it |
|---|---|---|
| 1 | invoke() hands in the state |
{'tester': 'Pramod'} |
| 2 | greet returns {'greeting': 'Hello Pramod, your first graph ran.'} |
{'tester': 'Pramod', 'greeting': 'Hello Pramod, your first graph ran.'} |
The last part of the output, from the first ---, is a Mermaid diagram. Copy it, go to mermaid.live, paste it, and you see the picture: the start node, then the greet function, then the end.
Here we have not created any AI agent, the instructor said: it is just a workflow, and the LLM, Playwright and other things will be added to it. But remember this: greet looks like a normal function as of now, and it can be a separate AI agent, which can do a particular task and return. We are entering the territory of multi-agents: in a workflow we can have multiple AI agents. You start with a dictionary, which is nothing but a bag; the bag is shared with the first agent, and when that one is done, the same bag goes to the next, which can see all its key-value pairs, until the end.
Exercise 2: a linear pipeline
The sequential pipeline is a very simple one, which we also use in Playwright, or in automation, the instructor said: set up a Playwright browser, execute, and tear down. What we want is that the state, the backpack, is shared between all three.
from typing import TypedDict
from langgraph.graph import END, START, StateGraph
class State(TypedDict, total=False):
test_name: str
browser: str
status: str
cleaned_up: bool
def setup(state: State) -> dict:
#
return {"browser": "chromium"}
def execute(state: State) -> dict:
return {"status": "passed"}
def teardown(state: State) -> dict:
return {"cleaned_up": True}
builder = StateGraph(State)
builder.add_node("setup", setup)
builder.add_node("execute", execute)
builder.add_node("teardown", teardown)
builder.add_edge(START, "setup")
builder.add_edge("setup", "execute")
builder.add_edge("execute", "teardown")
builder.add_edge("teardown", END)
app = builder.compile()
if __name__ == "__main__":
for step in app.stream({"test_name": "login_works"}, stream_mode="updates"):
for node, update in step.items():
print(f"{node:<9} changed -> {update}")
print("\nFinal state:", app.invoke({"test_name": "login_works"}))
python 02_Linear_Pipeline.py
setup changed -> {'browser': 'chromium'}
execute changed -> {'status': 'passed'}
teardown changed -> {'cleaned_up': True}
Final state: {'test_name': 'login_works', 'browser': 'chromium', 'status': 'passed', 'cleaned_up': True}
- Lines 4 to 8, the state of a test case. The test name is added at the start, then the browser, then the status, and the clean-up happens last.
total=Falseis what lets a key be missing until a node adds it. - Lines 12 to 20, three dummy functions.
setupreturns the browser,executethe status,teardownthe clean-up. We will write real code later, the instructor said. - Lines 22 to 31, the graph. Three nodes are added, then the edges: start, setup, execute, teardown, end.
- Line 37, stream and not invoke. The states keep on changing, so the class used
stream(), with the mode set to updates, to see what happens at each and every node. Line 41 then callsinvoke()for the final state, and that is a second full run: counted here, each of the three functions is called twice.
Question. How many nodes do we have in total in this case?
Worth practising too: how many edges?
Show the answer
Answer. Three, the instructor answered: setup, execute and teardown, each a real function which takes the state and returns a dictionary. Four edges, on lines 28 to 31: START to setup, setup to execute, execute to teardown, and teardown to END.
Growing up: a state that gains fields
A simple analogy, so that you remember it, the instructor said: you grow up. When you are very small, 0 to 1 year, that is the start: you have just been born, and the name is not assigned. By the fifth class the name is assigned, let's suppose Amit, and the class is assigned too, fifth grade. By the 12th, multiple things are assigned in the state, and a few things are updated. By BTech you have a lot of other states.
If you want to go back and check what the state was, what the name was, what the class was, you can go back in LangGraph too, and you can have multiple combinations if you want to. LangChain has a simple sequence, the instructor said, but LangGraph can have multiple versions.
Exercise 2 is the same story on a test case: it starts with a name, and every stage adds one field.
Exercise 3: conditional routing
This is where it is very interesting, the instructor said, because here we can have decisions. If the test case passes, I have to do something; if it fails, something else; if it is flaky, something else.
from typing import Literal, TypedDict
from langgraph.graph import END, START, StateGraph
class State(TypedDict, total=False):
test_name: str
status: str # passed | failed | flaky
action: str
def read_result(state: State) -> dict:
return {} # in real life: parse a Playwright report here
def route_by_status(state: State) -> Literal["log_pass", "file_bug", "quarantine"]:
return {"passed": "log_pass", "failed": "file_bug"}.get(state["status"], "quarantine")
def log_pass(state: State) -> dict:
return {"action": "logged as green"}
def file_bug(state: State) -> dict:
return {"action": f"Jira bug filed for {state['test_name']}"}
def quarantine(state: State) -> dict:
return {"action": f"{state['test_name']} moved to quarantine, rerun nightly"}
builder = StateGraph(State)
builder.add_node("read_result", read_result)
builder.add_node("log_pass", log_pass)
builder.add_node("file_bug", file_bug)
builder.add_node("quarantine", quarantine)
builder.add_edge(START, "read_result")
builder.add_conditional_edges("read_result", route_by_status,
["log_pass", "file_bug", "quarantine"])
for leaf in ("log_pass", "file_bug", "quarantine"):
builder.add_edge(leaf, END)
app = builder.compile()
if __name__ == "__main__":
for name, status in [("cart_total", "passed"),
("checkout_pay", "failed"),
("login_redirect", "flaky")]:
out = app.invoke({"test_name": name, "status": status})
print(f"{name:<15} {status:<7} -> {out['action']}")
# print("\n" + app.get_graph().draw_mermaid())
python 03_Conditional_Edge.py
cart_total passed -> logged as green
checkout_pay failed -> Jira bug filed for checkout_pay
login_redirect flaky -> login_redirect moved to quarantine, rerun nightly
- Lines 10 and 11.
read_resultis empty for now: in real life, you will use Playwright here. - Lines 14 and 15, the router. This function decides which of the three to go with: it looks at the status and returns the name of the next node.
- Lines 18 to 27, three endings. They each just return a dictionary. In
file_bugyou can write Jira code,log_passgives you the log details, andquarantinejust marks that the test is flaky in nature. They are empty functions as of now, and the real ones come in session two, the instructor said. - Lines 38 and 39, the conditional edge. After
read_result, LangGraph callsroute_by_statusand goes where it says. - Lines 42 and 43. The loop adds an edge from each of the three nodes to
END. - Lines 48 to 52. Three test cases are passed in, one passed, one failed, one flaky:
cart_totalis logged as green, a Jira bug is filed forcheckout_pay, andlogin_redirectis moved to quarantine.
In class the run printed the graph too, and the diagram was shown; line 54, which prints it, is commented out in the pushed file. Switched on, these are its edges:
python 03_Conditional_Edge.py | grep -e "-->" -e "-.->"
__start__ --> read_result;
read_result -.-> file_bug;
read_result -.-> log_pass;
read_result -.-> quarantine;
file_bug --> __end__;
log_pass --> __end__;
quarantine --> __end__;
A solid arrow always runs, and a dotted one is the conditional edge, as the key in the repo's graph.html puts it. The class's graph, run on its three statuses and three more:
| Status | The router returns | What happens |
|---|---|---|
passed |
log_pass |
logged as green |
failed |
file_bug |
Jira bug filed for cart_total |
flaky |
quarantine |
cart_total moved to quarantine, rerun nightly |
skipped |
quarantine |
cart_total moved to quarantine, rerun nightly |
timedOut |
quarantine |
cart_total moved to quarantine, rerun nightly |
Passed |
quarantine |
cart_total moved to quarantine, rerun nightly |
Quarantine is the default. Line 15 names two statuses and sends everything else to quarantine, so a skipped test, a timeout and a Passed with a capital P all land there. With no status at all, line 15 stops the run with KeyError: 'status'.
Exercise 4: a retry loop
The retry mechanism is something very useful in your flaky test case finder, the instructor said. You run a test case, and then the should_retry function says: if it is passed, report it; if it fails, I will retry it three times, and then, if it passes, report it.
from typing import Literal, TypedDict
from langgraph.graph import END, START, StateGraph
MAX_ATTEMPTS = 3
class State(TypedDict):
test_name: str
scripted_outcomes: list[str] # what each attempt will return (simulation)
attempts: int
history: list[str]
verdict: str
def run_test(state: State) -> dict:
n = state["attempts"]
outcome = state["scripted_outcomes"][n]
print(f" attempt {n + 1}: {outcome}")
return {"attempts": n + 1, "history": state["history"] + [outcome]}
def should_retry(state: State) -> Literal["run_test", "report"]:
if state["history"][-1] == "passed":
return "report"
if state["attempts"] < MAX_ATTEMPTS:
return "run_test" # <- the loop
return "report"
def report(state: State) -> dict:
h = state["history"]
if h[-1] == "passed" and "failed" in h:
verdict = f"FLAKY: passed on attempt {len(h)} after {h.count('failed')} failure(s)"
elif h[-1] == "passed":
verdict = "STABLE PASS"
else:
verdict = f"REAL FAILURE: failed all {len(h)} attempts"
return {"verdict": verdict}
builder = StateGraph(State)
builder.add_node("run_test", run_test)
builder.add_node("report", report)
builder.add_edge(START, "run_test")
builder.add_conditional_edges("run_test", should_retry, ["run_test", "report"])
builder.add_edge("report", END)
app = builder.compile()
if __name__ == "__main__":
scenarios = {
"login_redirect (flaky)": ["failed", "failed", "passed"],
"checkout_pay (broken)": ["failed", "failed", "failed"],
"cart_total (stable)": ["passed"],
}
for name, outcomes in scenarios.items():
print(name)
out = app.invoke({"test_name": name, "scripted_outcomes": outcomes,
"attempts": 0, "history": [], "verdict": ""})
print(" =>", out["verdict"], "\n")
python 04_Loop_Retry.py
login_redirect (flaky)
attempt 1: failed
attempt 2: failed
attempt 3: passed
=> FLAKY: passed on attempt 3 after 2 failure(s)
checkout_pay (broken)
attempt 1: failed
attempt 2: failed
attempt 3: failed
=> REAL FAILURE: failed all 3 attempts
cart_total (stable)
attempt 1: passed
=> STABLE PASS
- Lines 7 to 12, the state. The test name, the scripted outcomes, the attempts, the history and the verdict: all of this has to be stored at each node.
- Lines 14 to 18, the run.
run_testnotes down the attempt. The outcome comes from a script, so nothing real runs yet. - Lines 21 to 26, the decision. Passed goes to the report. Failed goes back to
run_test, as long as fewer thanMAX_ATTEMPTSattempts are used. - Lines 39 to 45, the graph. Two nodes, and line 44 is the conditional edge.
Question. How many edges do we have?
Worth practising too: what stops the loop?
Show the answer
Answer. Three, the instructor answered: start to the run; then a conditional check, do we have to retry or report; and the last one to the end. The loop stops on a pass, or when MAX_ATTEMPTS is used up.
Three scenarios, the instructor explained: the login redirect is flaky in nature, failing and then passing; the second is always failing, so it is a real failure; the cart total is stable in nature. What should_retry says after every attempt, read from the running graph:
| Test | Attempt | History so far | The edge goes to |
|---|---|---|---|
login_redirect |
1 | failed | run_test |
login_redirect |
2 | failed, failed | run_test |
login_redirect |
3 | failed, failed, passed | report |
checkout_pay |
1 | failed | run_test |
checkout_pay |
2 | failed, failed | run_test |
checkout_pay |
3 | failed, failed, failed | report |
cart_total |
1 | passed | report |
Three attempts, not three retries. In class the rule was to retry three times. MAX_ATTEMPTS counts the first run as well, so a failing test gets one run and two retries. A fourth outcome in the script is never used: failed, failed, failed, passed still ends in REAL FAILURE: failed all 3 attempts.
Mini project: find the flaky test by comparing two builds
The rough idea is very simple, the instructor said: you create a state, you create certain functions, and based on the functions you say that this is the output you are getting. Now a very simple project out of it: a flaky test case finder, a mini version. The instructor gave the scenario to a model, Opus, and explained it while the model was creating the code.
The scenario
You run your Playwright test cases, and that is build number one: out of, let's suppose, 10 cases, 8 pass and 2 fail. Then you run build two: again 8 pass, then one more passes and one fails, so 9 pass and 1 fails. But there is a problem: one test case is actually flaky in nature, and we need to find it by using LangGraph. LangGraph will make the decisions: it will consume this file and automatically give you the result that this is the test case, number three, let's suppose, which is flaky. This information you can share with your QA lead. This is a very simple agent, a very minimum agent, the instructor said.
The two builds
The numbers in the files the model wrote are not the whiteboard's: in the first build one test fails, and in the second, two.
{
"build": 1,
"results": [
{"test": "test_login_valid", "status": "passed"},
{"test": "test_login_invalid_message", "status": "passed"},
{"test": "test_products_count", "status": "passed"},
{"test": "test_sort_price_low_high", "status": "passed"},
{"test": "test_add_to_cart", "status": "passed"},
{"test": "test_cart_badge", "status": "passed"},
{"test": "test_remove_from_cart", "status": "passed"},
{"test": "test_checkout_form_validation","status": "passed"},
{"test": "test_checkout_tax_total", "status": "passed"},
{"test": "test_sso_login_button", "status": "failed"}
]
}
build_2.json lists the same 10 tests in the same order. Apart from the build number, only line 12 differs:
{"test": "test_checkout_tax_total", "status": "failed"},
The code
"""Project (minimal) - find the flaky test by comparing two builds.
Everything from 01-04 in one small graph:
01 state as a backpack, 02 a linear pipeline, 03 a conditional edge,
04 the idea that a verdict needs more than one run.
Input : builds/build_1.json and builds/build_2.json (10 tests each)
Output: which test is FLAKY, which is BROKEN, which are STABLE
venv/bin/python Project_FlakyTestFinder_MIN.py
"""
import json
from pathlib import Path
from typing import Literal, TypedDict
from langgraph.graph import END, START, StateGraph
BUILDS = Path(__file__).parent / "builds"
class State(TypedDict, total=False):
runs: list[dict] # [{test: status}, {test: status}]
stable: list[str]
flaky: list[str]
broken: list[str]
confirmed: str
verdict: str
# ---------------------------------------------------------------- nodes
def load_builds(state: State) -> dict:
"""02 - step one of the pipeline: read both build reports."""
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 {len(runs)} builds, {len(runs[0])} tests each")
return {"runs": runs}
The opening comment, lines 3 to 5, names where each part comes from: the state as a backpack from exercise 1, the pipeline from 2, the conditional edge from 3, and from 4 the idea that a verdict needs more than one run. The state holds the builds' runs, then the stable, the flaky and the broken tests. load_builds reads both JSON files.
def compare(state: State) -> dict:
"""02 - step two: one status per test is not a verdict. Two is."""
b1, b2 = state["runs"]
stable, flaky, broken = [], [], []
for test in b1:
pair = (b1[test], b2[test])
if pair == ("passed", "passed"):
stable.append(test)
elif pair == ("failed", "failed"):
broken.append(test)
else:
flaky.append(test) # passed once, failed once
return {"stable": stable, "flaky": flaky, "broken": broken}
def route(state: State) -> Literal["confirm_flaky", "report"]:
"""03 - the conditional edge: only rerun when there is something to rerun."""
return "confirm_flaky" if state["flaky"] else "report"
compare pairs the two statuses of every test. There is one idea here, the instructor pointed out: a single status is not a verdict. Then route is the conditional edge: if a flaky test case is found, it goes to the confirmation, and if not, to the report.
def confirm_flaky(state: State) -> dict:
"""04 - a third run breaks the tie. Dummy Playwright, no network needed."""
from playwright.sync_api import sync_playwright
test = state["flaky"][0]
with sync_playwright() as pw:
browser = pw.chromium.launch()
page = browser.new_page()
page.set_content("<h1 id='total'>Total: $17.27</h1>") # stands in for the app
passed = page.locator("#total").inner_text() == "Total: $17.27"
browser.close()
print(f"rerun of {test}: {'passed' if passed else 'failed'}")
return {"confirmed": f"{test} passed on rerun 3 -> FLAKY, not broken"}
def report(state: State) -> dict:
"""Every test, both builds, and the label the comparison earned it."""
b1, b2 = state["runs"]
label = {t: "STABLE" for t in state["stable"]}
label.update({t: "FLAKY" for t in state["flaky"]})
label.update({t: "BROKEN" for t in state["broken"]})
rows = [f"{'TEST':<32} {'BUILD 1':<8} {'BUILD 2':<8} VERDICT",
"-" * 64]
for test in b1:
rows.append(f"{test:<32} {b1[test]:<8} {b2[test]:<8} {label[test]}")
rows += ["", f"{len(state['stable'])} stable, "
f"{len(state['flaky'])} flaky, {len(state['broken'])} broken"]
if state.get("confirmed"):
rows.append(state["confirmed"])
return {"verdict": "\n".join(rows)}
confirm_flaky launches Chromium, opens a stub page, which stands in for the app, and checks its total. report builds the table.
# ---------------------------------------------------------------- graph
builder = StateGraph(State)
builder.add_node("load_builds", load_builds)
builder.add_node("compare", compare)
builder.add_node("confirm_flaky", confirm_flaky)
builder.add_node("report", report)
builder.add_edge(START, "load_builds")
builder.add_edge("load_builds", "compare")
builder.add_conditional_edges("compare", route, ["confirm_flaky", "report"])
builder.add_edge("confirm_flaky", "report")
builder.add_edge("report", END)
app = builder.compile()
if __name__ == "__main__":
out = app.invoke({})
print(f"\n{out['verdict']}")
print("\n--- the graph ---")
print(app.get_graph().draw_mermaid())
All the functions are added as nodes: first load_builds, which reads the JSON files, then compare, then the confirmation and the report. The edges join them, and the graph is compiled. The repo's graph.html draws this graph in a browser, with Mermaid loaded from a CDN, so it needs the internet.
The result
The README's way to run it installs Playwright for Python and its Chromium next to LangGraph. It prints this report, and then the graph as Mermaid:
cd chapter_18_LangGraph/recap
venv/bin/pip install -U langgraph playwright && venv/bin/playwright install chromium
venv/bin/python Project_FlakyTestFinder_MIN.py
loaded 2 builds, 10 tests each
rerun of test_checkout_tax_total: passed
TEST BUILD 1 BUILD 2 VERDICT
----------------------------------------------------------------
test_login_valid passed passed STABLE
test_login_invalid_message passed passed STABLE
test_products_count passed passed STABLE
test_sort_price_low_high passed passed STABLE
test_add_to_cart passed passed STABLE
test_cart_badge passed passed STABLE
test_remove_from_cart passed passed STABLE
test_checkout_form_validation passed passed STABLE
test_checkout_tax_total passed failed FLAKY
test_sso_login_button failed failed BROKEN
8 stable, 1 flaky, 1 broken
test_checkout_tax_total passed on rerun 3 -> FLAKY, not broken
This is the final result by this LangGraph agent, the instructor said. One test case is failing in both the builds, which the report labels BROKEN; the other one got flipped, so it is flaky: sometimes it fails, sometimes it passes. The result was stored in a file too, result_min.html, next to the recap folder. It holds the report as plain text, so a browser runs it together and loses the columns; saved as .txt, it would keep them.
This looks like a dummy, the instructor said, and real code can be added to it: the JSON can be real too, and connect with your Playwright automation. The README adds a catch: "Two builds can only ever suspect flakiness", since a test that fails 1 run in 20 will look stable in both.
What the comparison and the rerun check
compare, called with each pair of statuses:
| Build 1 | Build 2 | Label |
|---|---|---|
| passed | passed | STABLE |
| failed | failed | BROKEN |
| passed | failed | FLAKY |
| failed | passed | FLAKY |
| skipped | skipped | FLAKY |
| passed | skipped | FLAKY |
The first three pairs are the ones in the class's builds. The fourth is the instructor's own example, already failed in the previous one and passed now in build two. The last two are extra: the else on line 49 takes every pair that is not two passes or two fails, so a skipped test is labelled flaky too. A test that is missing from build 2 stops compare with a KeyError, and one that is only in build 2 is left out of the report.
The conditional edge works as drawn. With build 2 holding the same results as build 1, nothing flips, and the rerun is skipped:
# build 2 with build 1's results
python Project_FlakyTestFinder_MIN.py | grep -E "rerun|FLAKY|stable,"
9 stable, 0 flaky, 1 broken
With two flaky tests, only the first one is rerun, because line 63 takes state["flaky"][0]:
# build 2 with test_add_to_cart failing as well
python Project_FlakyTestFinder_MIN.py | grep -E "rerun|FLAKY|stable,"
rerun of test_add_to_cart: passed
test_add_to_cart passed failed FLAKY
test_checkout_tax_total passed failed FLAKY
7 stable, 2 flaky, 1 broken
test_add_to_cart passed on rerun 3 -> FLAKY, not broken
And with a wrong total on the stub page, so that the check on line 68 fails, the last line still says passed:
# line 67 with Total: $0.00
python Project_FlakyTestFinder_MIN.py | grep -E "rerun|FLAKY|stable,"
rerun of test_checkout_tax_total: failed
test_checkout_tax_total passed failed FLAKY
8 stable, 1 flaky, 1 broken
test_checkout_tax_total passed on rerun 3 -> FLAKY, not broken
What the third run proves today. It opens the same stub page whatever the test is, so it passes every time, and line 71 writes its verdict without looking at the result. The commit message calls the page a stand-in for the real checkout; the Playwright code comes in Part 2.
Jenkins and the JSON report
Question. How can I connect the Jenkins build data, where Playwright test cases are running?
Show the answer
Answer. A very good question, and it is very simple, the instructor answered: whenever you run a Playwright test case, you get a result.json file, and you will find this file in Jenkins too, automatically. In the next class, the instructor will show that you can pick this up from Jenkins, run it through LangGraph, and get the result automatically.
The JSON report has to be asked for. Playwright Test writes one only when its json reporter is switched on, in the config or on the command line. Two small tests run here without it, on Playwright Test 1.65.1, left test-results/.last-run.json, which holds the status and the failed tests' ids, and no result.json.
A config that asks for it, as Playwright's reporter docs describe:
import { defineConfig } from '@playwright/test';
export default defineConfig({
testDir: './tests',
reporter: [['list'], ['json', { outputFile: 'result.json' }]],
});
With it, the same run wrote result.json. Its top-level keys are config, suites, errors and stats, not the results list of the class's two builds, so the pushed load_builds stops on a real report, on line 33:
python Project_FlakyTestFinder_MIN.py 2>&1 | grep KeyError
KeyError: 'results'
Tasks and announcements
- The code. It is in the batch repository, in chapter 18's recap folder, as this class pushed it. Part 2 added its files to the same folder and changed the two builds to five tests each; this link keeps the 10-test builds this page runs.
- The prompt. The prompt given to the model for the mini finder will be given to you too, the instructor said.
- Part 2, on Friday evening. The deck gives it as Friday, 27 November, 8 PM IST. The instructor will complete this: Playwright code will be added, and Jenkins code too. It will fetch from Jenkins, run it automatically through the LLM, and give you a report like this one. It is going to use a very minimum brain, and the brain is going to make the decisions, the instructor said. Part 2 adds the real code, the real things, for the capstone project.
- What it leads to. RCA, flaky test case, bug triaging: you can create all three in one go by using LangGraph, the instructor said, and they can run 24 by 7, and make decisions too.
Task: give it a try. For the second session, try to do the four exercises and the mini version by yourself.
Show the answer
Answer. Everything you need is on this page: a State, the functions, add_node, the edges, compile() and invoke(). Run each file, and check what it prints against the outputs above.