What this class covered
- A recap of chapter 17 so far, then structured output with a Pydantic BaseModel, and what happens without it
- A Playwright agent, level 1: plain English in, Playwright tools out
- The full end-to-end purchase: the task changes, the code does not
- The task from a Jira ticket
- Many tickets, one by one: the Jira test executor, and a mistake on a negative case
- The QA pipeline: fetch, retrieve, plan, execute, report
- Many stories in one page, and the RAG library
- Tasks and announcements: build the multi-story executor; LLM evaluation next weekend, then LangGraph
- A Pydantic
BaseModelgiven asresponse_formatbecomes a JSON schema in the request, and the reply is checked against it: a priority outsideLiteral["High", "Medium", "Low"]stops the run with a validation error. create_agenttakes a Pydantic model, a dataclass, a TypedDict or a JSON schema dict; a plain class stops it before any request reaches a model.- An agent's tools are plain functions whose docstrings the model reads:
playwright_tools.pyoffers 32, and its first rule is to return a string, never raise, so the model can read an error and try again. - Two tool calls in one turn run at the same time, and Playwright's
filltypes into whichever field has the focus: both texts can land in one field while both tools report success. Verify after you act. - A lookup by label survives renamed ids and classes but not a renamed label; a CSS id, the other way round.
snapshot_pageshows the page as it is now. - A Jira ticket can be the task:
jira_client.pyreads it over REST v3, and a bad token can come back as 404, not 401. - The pipeline grounds its plan on the five most similar of 5,000 earlier test cases, stops at two gates for a human, and decides the overall verdict in code, not in the model.
Recap and structured output
Last class began chapter 17 with LangChain: one chat-model interface for four providers, invoke and stream, four calls at once with asyncio, tools and memory. This class opened with a quick recap of it, then part 2: multiple tools, system prompts, structured output, and Playwright agents at the end.
LangChain is an open-source Python framework for building real AI applications on top of large language models, the recap went: it gives you models, prompts, tools, memory and retrieval, and a create function that wires them into an AI agent. LangChain is used to create LLM applications, LangGraph for stateful applications, and LangSmith for evaluation and observability. To set it up, create and activate a virtual environment, install with uv or pip, set your Gemini, DeepSeek or Groq key, or pull a local model; create_agent takes the model you want, and its key sits in the .env file.
With agent.stream you get the response token by token, which is best for a UI or live tools; invoke gives the response at once, simple and easy, best for scripts and batch processing. 99% of the time we will be using invoke, the instructor said, because LangChain is used behind the scenes, and there we always use invoke: stream only when you have created a chatbot or a UI.
A system prompt is the high-level instruction given to the AI agent, and a user prompt is what the user asked. By default, LangChain is sequential in nature, the instructor said: after smoke you run sanity, and after sanity, regression. To run in parallel, import asyncio and run the asynchronous ainvoke inside asyncio.gather. Without a tool, an AI agent is nothing: it can only reply with its limited knowledge. A tool is nothing but a function, an add or a subtract, named when you create the agent; a memory takes a configuration, and an in-memory saver keeps consecutive runs. With several tools, such as a search tool and a web content tool, the agent selects one based on the query.
Question. Why do we want structured output?
Show the answer
Answer. Because without a structured output, non-deterministic answers are very difficult to parse, the instructor answered; to save tokens too, as the class suggested. If the answer comes in a proper, systematic format, a proper JSON, you can parse it and show it in your application.
Question. Any example of a non-structured output?
Show the answer
Answer. The Gemini answer from the last class was not structured, the instructor answered. Asking it to explain the LLM in 1,000 words is more structured; or you can tell it to give a proper JSON format: that is a structured output.
10 builds that structure with Pydantic, a module for data validation, as the instructor put it: JSON schema validations, a proper structure.
from typing import Literal
from dotenv import load_dotenv
from pydantic import BaseModel
from langchain.agents import create_agent
load_dotenv()
class TestCase(BaseModel):
title:str
description:str
steps:list[str]
expected_result: str
actual_result: str
preconditions: list[str]
priority: Literal["High", "Medium", "Low"]
tags: list[str]
class TestCaseList(BaseModel):
testcases : list[TestCase]
agent = create_agent(
model="google_genai:gemini-flash-lite-latest",
# model="anthropic:claude-haiku-4-5", # optional
system_prompt=(
"You are a senior automation testing engineer. Always return test cases "
"in the exact structured JSON format requested. Be detailed and professional."
),
response_format=TestCaseList,
)
# FETCH from JIRA
user_story = ("As a logged-in user, I want to add items to my shopping cart "
"so that I can purchase them later.")
result = agent.invoke({
"messages": [{
"role": "user",
"content": f"Generate 2 detailed test cases for this user story: {user_story}",
}]
})
print("=== Structured Output ===")
test_cases = result["structured_response"].testcases
for tc in test_cases:
print(tc.model_dump_json(indent=2))
print(f"\nSuccessfully generated {len(test_cases)} test cases!")
TestCase on lines 7 to 15 inherits from BaseModel: a title, a description, the steps as a list of strings, the expected result, a priority and tags, plus an actual result and preconditions, which learners suggested in class. The priority on line 14 is a Literal: one of these three values, high, medium and low. Literal is very similar to an enum, the instructor agreed, when a learner said so. TestCaseList on lines 17 and 18 holds a list of them: one test case, and a list of multiple test cases.
The agent on lines 20 to 28 uses Gemini; line 22 keeps Claude Haiku as an option, since you can use Anthropic's model too, if you want to, by changing the model. The system prompt asks for test cases in the exact structured JSON format, and line 27 is the beauty of it, the instructor said: the response format, which should look like a test case. The user story on lines 31 and 32 stands in for one fetched from Jira, as line 30's comment says: as a logged-in user, I want to add items to my shopping cart. Lines 43 to 45 take the test cases out of structured_response and print each one as JSON. In class, the reply came back that way: the title, the description, the steps, the expected output, the priority and the tags, automatically in a JSON format, the same format as the class.
These notes ran 10 with line 21 naming the class's Groq model, the one .env.example sets as LLM_MODEL:
model="groq:openai/gpt-oss-120b",
GROQ_API_BASE, langchain-groq's own setting, points the Groq client at a stand-in on 127.0.0.1 that calls no model and answers with fixed JSON. The request itself is LangChain's: for this model, it sends the classes as a JSON schema named TestCaseList, in response_format. The priority, as sent:
"priority": {
"enum": [
"High",
"Medium",
"Low"
],
"title": "Priority",
"type": "string"
}
All 8 fields are required. The stand-in's two test cases fit, so the file prints them:
python 10_Structure_Output.py
=== Structured Output ===
{
"title": "stand-in test case 1",
"description": "fixed by the stand-in",
"steps": [
"step one",
"step two"
],
"expected_result": "as the story says",
"actual_result": "not run",
"preconditions": [
"a logged-in user"
],
"priority": "High",
"tags": [
"stand-in"
]
}
{
"title": "stand-in test case 2",
"description": "fixed by the stand-in",
"steps": [
"step one",
"step two"
],
"expected_result": "as the story says",
"actual_result": "not run",
"preconditions": [
"a logged-in user"
],
"priority": "Medium",
"tags": [
"stand-in"
]
}
Successfully generated 2 test cases!
Pydantic will force this, the instructor said: the base model says we have to follow the structure. The same stand-in, with one priority set to Urgent, stops the run with this error:
langchain.agents.structured_output.StructuredOutputValidationError: Failed to parse structured output for tool 'TestCaseList': Failed to parse data to TestCaseList: 1 validation error for TestCaseList
testcases.1.priority
Input should be 'High', 'Medium' or 'Low' [type=literal_error, input_value='Urgent', input_type=str]
For further information visit https://errors.pydantic.dev/2.14/v/literal_error.
It is very similar to an interface, the instructor said. Then the class removed the base model and got an error: without Pydantic, the LLM can give results that do not match the class, the instructor explained, and the error, as the instructor read it, says to use a Pydantic model. Which class loses BaseModel decides where the run stops; in all three, no request reaches a model:
| Removed from | The run stops at | The error |
|---|---|---|
TestCase only |
line 17, class TestCaseList(BaseModel): |
PydanticSchemaGenerationError: Unable to generate pydantic-core schema for <class '__main__.TestCase'> |
TestCaseList only |
line 20, agent = create_agent( |
ValueError: Unsupported schema type: <class 'type'>. Supported types: Pydantic models, dataclasses, TypedDicts, and JSON schema dicts. |
| both | line 20, agent = create_agent( |
the same ValueError |
Where the check happens. Pydantic checks the reply's values when the reply comes back: one priority outside the three stopped the run above. create_agent turns the class into the request's schema first, which a plain class cannot give it.
A Playwright agent, level 1
Now we are going to build our first Playwright version, the instructor said: the 11th project, a Playwright AI agent orchestrator, level 1, or level 1.5, and the levels keep increasing. The goal: a very simple AI agent that takes plain English, opens the real browser, navigates, fills, takes the screenshot and gives you a result.
With a scripted test case, normal automation, we have to write the steps and run them every time, and it is best for regression, the instructor said. A Playwright AI agent picks the order automatically; it will be very fast, and it is used for exploratory testing and quick smoke and sanity. Whatever plain English you have written, the LangChain agent will reason, react and observe, following RAO, and use whichever tool it wants.
Suppose the steps say: open a URL, x.com; click the button Y; verify Z. The agent has access to tools: for opening a URL, for clicking, for filling and for verification, there is a tool created in the LangChain code. Whenever somebody says open, the open tool is called with the URL and it opens the Chrome window: LangChain is going to execute all the tools. We are not using Playwright MCP here, the instructor said: this is an independent agent, which can run through a script.
The tools live in playwright_tools.py, a file the LangChain agent uses. Everything is now a tool, even launching a browser: to launch Playwright from Python, you start async Playwright, launch, create a context and create a page, the instructor said, the same code as on Playwright's own site, for Python with async. Close the browser, take a screenshot, navigate, go back, reload, wait for an element, type, click, hover: for everything, there is a function, and a similar wrapper could be written for Selenium too. The file opens with its rules:
"""Playwright tools for a LangChain agent (verified against Playwright 1.62).
Design rules every tool here follows, because an LLM is the caller:
1. Return a string, never raise. An agent cannot catch an exception, but it can
read "Error: no element matches #login" and try a different selector.
2. The docstring IS the tool description the model reads. Say when to use the
tool, not just what it does.
3. Prefer role/label/text lookups over CSS. The agent guesses CSS badly; it is
much better at "the button called Sign in".
"""
Question. These are all inbuilt modules, right?
Show the answer
Answer. This is just Playwright code, the instructor answered: the same code as on Playwright's site, for Python, with async.
In the file, every tool is an async function under @tool, and _needs_page, which wraps all but the first two, turns an exception into a string such as Error: ... or Timeout: .... Launching the browser:
@tool
async def launch_browser(headless: bool = False) -> str:
"""Launch a Chromium browser. Always call this first, before any other tool."""
global _playwright, _browser, _context, _page
if _browser:
return "Browser is already open."
_console_errors.clear()
_failed_requests.clear()
_playwright = await async_playwright().start()
_browser = await _playwright.chromium.launch(headless=headless, slow_mo=700)
_context = await _browser.new_context()
_page = await _context.new_page()
# 30s (the default) is a long time for an agent to sit blocked on a typo.
_page.set_default_timeout(15_000)
_page.on("console", _record_console_message)
_page.on("requestfailed", _record_failed_request)
return f"Browser launched successfully ({'headless' if headless else 'visible'} mode)."
The tool 12's system prompt prefers for typing, type_by_label, finds a field by its label, or else its placeholder, and fills it:
@tool
@_needs_page
async def type_by_label(label: str, text: str) -> str:
"""Type into the field with this form label or placeholder, e.g. label="Password".
Prefer this over type_text - it is how a human finds the field, and it does
not break when the CSS class changes.
"""
field = _page.get_by_label(label)
if await field.count() == 0:
field = _page.get_by_placeholder(label)
await field.first.fill(text)
return f'Typed "{text}" into the field labelled "{label}"'
All the tools come out as one list in the end, in the bundles the instructor named: core tools, interaction tools, assertion tools, diagnostics and advanced tools.
CORE_TOOLS = [
launch_browser, close_browser, snapshot_page, get_page_info,
navigate_to, click_by_role, click_by_text, type_by_label,
click_element, type_text, get_text, take_screenshot,
]
INTERACTION_TOOLS = [
hover_element, press_key, select_dropdown_option, set_checkbox,
upload_file, drag_and_drop, scroll_to_element, wait_for_element,
go_back, reload_page,
]
ASSERTION_TOOLS = [
assert_visible, assert_text_contains, count_elements,
get_all_texts, get_attribute_value,
]
DIAGNOSTIC_TOOLS = [get_console_errors, get_failed_requests]
ADVANCED_TOOLS = [set_viewport, mock_api_response, save_login_state]
PLAYWRIGHT_TOOLS = (
CORE_TOOLS + INTERACTION_TOOLS + ASSERTION_TOOLS
+ DIAGNOSTIC_TOOLS + ADVANCED_TOOLS
)
That is 32 tools: 12 core, 10 interaction, 5 assertion, 2 diagnostic and 3 advanced. 11 hands all of them to a DeepSeek agent:
import asyncio
from dotenv import load_dotenv
from langchain.agents import create_agent
from langchain_deepseek import ChatDeepSeek
from playwright_tools import PLAYWRIGHT_TOOLS
import os
load_dotenv()
# The .env calls the key DEEPSEEK_API, but the SDK looks for DEEPSEEK_API_KEY,
# so it has to be passed in explicitly.
llm = ChatDeepSeek(
model=os.getenv("DEEPSEEK_MODEL", "deepseek-chat"),
api_key=os.getenv("DEEPSEEK_API"),
temperature=0,
)
SYSTEM_PROMPT="""
You are an automation testing agent that controls a real browser
using Playwright.
Rules:
1. Always start by launching the browser before performing any action.
2. Perform the actions in the order they are requested.
3. Use clear CSS selectors to interact with elements on the page.
4. Take a screenshot before closing the browser to capture the final state.
5. At the end, report every step you took and whether the test PASSED or FAILED.
"""
TASK = """ Test the login functionality on https://app.thetestingacademy.com/playwright/ttacart/
1. Launch the browser
2. Navigate to the login page
3. Enter the username "<from the task post>"
4. Enter the password "<from the task post>"
5. Click the login button
6. Close the browser
"""
async def main():
agent = create_agent(
model=llm,
tools=PLAYWRIGHT_TOOLS,
system_prompt=SYSTEM_PROMPT,
)
# Playwright's async API needs ainvoke: every tool call runs on the same event loop
result = await agent.ainvoke({"messages": [{"role": "user", "content": TASK}]})
# Show each tool call and what the browser answered
print("\n===== Steps taken =====")
for msg in result["messages"]:
if msg.type == "ai" and msg.tool_calls:
for call in msg.tool_calls:
print(f"-> {call['name']}({call['args']})")
elif msg.type == "tool":
print(f" {msg.content}")
print("\n===== Final Result =====")
print(result["messages"][-1].text) # .text joins the reply's text blocks
asyncio.run(main())
Line 5 imports the tools from the file, as an array. Lines 12 to 16 build the model with ChatDeepSeek; the comment on lines 10 and 11 says why line 14 passes the key in by hand: the .env calls it DEEPSEEK_API, and the SDK looks for DEEPSEEK_API_KEY. The system prompt, lines 18 to 28, sets the rules, and the task, lines 30 to 37, says what to do: test the login on TTACart, the Testing Academy's practice shop. Line 46 runs the agent with ainvoke: asynchronous is invoked by ainvoke, and await has to be used, the instructor said. Lines 49 to 58 print every tool call and what the browser answered, then the final result. The login details are in the task post.
Question. Where did you store the username and password?
Show the answer
Answer. This is a dummy website, with its username and password on it, the instructor answered. They are not stored in the environment file: they are hardcoded for now, to show you.
The first run hit errors. The DeepSeek API was not working, and the instructor, thinking the old key deleted, created a new one; it still did not work, until the cause turned up: load environment was not called. With it, the run worked: DeepSeek entered the username and the password, clicked the login button by itself, and reported the steps, the launch browser tool, the navigation, a snapshot and the rest, with the selectors it used, and that the test passed. The pushed file calls load_dotenv() on line 8.
Question. How did it get the locators?
Show the answer
Answer. First, the large language model figured out which tool to use, the instructor answered; when it had to click an element, it figured out the selector automatically too, because it has access to the tools.
Question. Can I find broken URLs on the page too?
Show the answer
Answer. Yes, by using this, the instructor answered.
Which tool sees a broken link. get_failed_requests says, in its docstring, that it lists failed network requests, broken APIs, images, 4xx and 5xx. It listens to Playwright's requestfailed event (line 102), and Playwright's own API notes say a 404 or a 503 is still a successful response, which finishes with requestfinished, not requestfailed. So a 404 is not on its list; get_console_errors is where the browser reports it. Both, called on a local page holding an image that answers 404 and a script whose server is not there:
| Tool | What it returned |
|---|---|
get_failed_requests |
1 failed request: the script, net::ERR_CONNECTION_REFUSED; not the image |
get_console_errors |
2 console errors: net::ERR_CONNECTION_REFUSED, and the server responded with a status of 404 (Not Found) |
Question. We can use Claude also, right?
Show the answer
Answer. Yes, the instructor answered: you can use Claude, your local models, whatever model.
On a stand-in. The class ran 11 on DeepSeek against TTACart. These notes never sign in anywhere, and the one local model here cannot call tools, so 11 ran unchanged against a stand-in on 127.0.0.1 that calls no model: it replays a fixed list of tool calls against a small practice page of our own, served on the same machine, with placeholder values. DEEPSEEK_API_BASE, the client's own setting, points the DeepSeek client at the stand-in. The calls are fixed; everything a tool returns is playwright_tools.py driving a real Chromium.
The first request carried the system prompt, the task and all 32 tools, each described by its docstring. type_by_label, as sent:
{
"type": "function",
"function": {
"name": "type_by_label",
"description": "Type into the field with this form label or placeholder, e.g. label=\"Password\".\n\nPrefer this over type_text - it is how a human finds the field, and it does\nnot break when the CSS class changes.",
"parameters": {
"properties": {
"label": {
"type": "string"
},
"text": {
"type": "string"
}
},
"required": [
"label",
"text"
],
"type": "object"
}
}
}
What 11's own lines 49 to 58 printed:
python 11_Playwright_AIAgent_Orch_Lvl_1.py
===== Steps taken =====
-> launch_browser({'headless': True})
Browser launched successfully (headless mode).
-> navigate_to({'url': 'http://127.0.0.1:<port>/login'})
Navigated to http://127.0.0.1:<port>/login
-> snapshot_page({})
- main:
- heading "Practice shop" [level=1]
- text: Username
- textbox "Username"
- text: Password
- textbox "Password"
- button "Login"
-> type_by_label({'label': 'Username', 'text': 'demo_user'})
Typed "demo_user" into the field labelled "Username"
-> type_by_label({'label': 'Password', 'text': 'demo_pass'})
Typed "demo_pass" into the field labelled "Password"
-> snapshot_page({})
- main:
- heading "Practice shop" [level=1]
- text: Username
- textbox "Username": demo_user
- text: Password
- textbox "Password": demo_pass
- button "Login"
-> click_by_role({'role': 'button', 'name': 'Login'})
Clicked button named "Login"
-> get_page_info({})
URL: http://127.0.0.1:<port>/products
Title: Practice shop - Products
-> assert_text_contains({'selector': 'h1', 'expected_text': 'Products'})
PASS: expected 'Products' found in 'Products'
-> take_screenshot({'filename': 'standin_login.png'})
Screenshot saved as screenshots/standin_login.png
-> close_browser({})
Browser closed successfully.
===== Final Result =====
stand-in: that was the last call on its fixed list. It reads no page and gives no verdict.
The page received the placeholder values, opened the products page, and the check on its heading passed. The last line is the stand-in's: it reads no page, so it gives no verdict.
The full end-to-end purchase
Let's go one more level, the instructor said: a full end-to-end Playwright LangChain AI agent. The system prompt remains the same; the task is the end-to-end one: log in with the standard username and password, verify the login, go to the checkout, enter the name and the zip code, verify the total of 17.27, using the arithmetic too, click finish, verify the checkout, check the console errors, take a screenshot and reply with pass or fail. I have just changed the task, the instructor said: nothing else.
SYSTEM_PROMPT="""
You are an end-to-end automation testing agent that controls a real browser
using Playwright.
Rules:
1. Always call launch_browser FIRST, before any other action.
2. Call snapshot_page whenever you land on a new page. It returns every role and
name on that page, so you never have to guess a selector.
3. Prefer click_by_role and type_by_label over raw CSS. This app also exposes
stable [data-test="..."] attributes if you need a CSS selector.
4. Verify as you go with assert_visible and assert_text_contains. Do not assume
a step worked because the previous tool call returned no error.
5. Never invent a value you were not given, and never report a price you did not
actually read off the page.
6. Before closing, call get_console_errors and take_screenshot.
7. Report every step, every assertion with its PASS/FAIL, and one final verdict:
TEST PASSED or TEST FAILED."""
TASK = """Run the full end-to-end purchase flow on TTACart and verify the order completes.
Site: https://app.thetestingacademy.com/playwright/ttacart/
Username: <from the task post>
Password: <from the task post>
Steps:
1. Launch the browser and navigate to the site.
2. Log in with the credentials above.
3. VERIFY you land on the products page (URL ends in /inventory, heading "Products").
4. Add the FIRST product to the cart. It is "Test.allTheThings() T-Shirt (Red)" at $15.99.
Record its price, you will need it in step 8.
5. VERIFY the cart badge in the header now shows 1.
6. Open the shopping cart and VERIFY the T-shirt is listed with quantity 1.
7. Click "Checkout", then fill in the customer details:
First Name "Pramod", Last Name "Dutta", Zip/Postal Code "560001", and click "Continue".
8. You are now on "Checkout: Overview". Read the price block and VERIFY the maths:
Item total ($15.99) + Tax ($1.28) must equal the Total ($17.27).
Use the qa arithmetic in your head, and report all three numbers you actually read.
9. Click "Finish" to place the order.
10. VERIFY the confirmation page: URL ends in /checkout-complete and the page shows
the heading "Thank you for your order!".
11. Check the console for JavaScript errors, take a screenshot named "order_complete.png",
then close the browser.
Report a PASS or FAIL for every VERIFY step above, then the final verdict.
"""
In the pushed files, 12's system prompt is longer than 11's: its rules name the tools, launch_browser first, snapshot_page on every new page, click_by_role and type_by_label before CSS, an assertion after each step, no value or price it did not read, and one final verdict. The rest of 12 is 11's code, apart from blank lines and one comment's indent. The sum the task asks for holds: 15.99 + 1.28 = 17.27.
In class, the run logged in, added the products, verified the total of 17.27 and gave the results, as the instructor narrated it. The screenshot above is the repo's screenshots/order_complete.png, the name the task gives the final screenshot.
A learner found it surprising: a requirement change, and locator changes, it handles automatically. Yes, even if there is a change in locator, this does not have any problem, the instructor said: we are not keeping locators. These notes can show the tools' side of that. The same two lookups, type_by_label("Username") and type_text("#user-name"), on three versions of a local login form, with what the form then held:
| Form | What changed | By label | By CSS id |
|---|---|---|---|
/login |
nothing | typed; the field holds demo_user |
typed; the field holds demo_user |
/v2/login |
the ids and classes renamed | typed; the field holds demo_user |
Timeout: Locator.fill: Timeout 15000ms exceeded. |
/v3/login |
the label reads Email | Timeout: Locator.fill: Timeout 15000ms exceeded. |
typed; textbox "Email": demo_user |
So a lookup by label survives a markup change and not a change of wording; a CSS id, the other way round. Each time, snapshot_page read the page as it was: on the third form the field is now called Email, which is what the agent sees next. Whether a model then picks the right field is the model's part, which a stand-in cannot show.
The task from a Jira ticket
Now, I want to get my requirement from this ticket, the instructor said. There are two scenarios: sometimes the test case is given directly in the ticket, and sometimes, as in ticket 49, you have to create the test case. First, the one where everything is given: the instructor created a Jira task for the end-to-end scenario in the VWO project, a full end-to-end for a purchase. It is the same script; only the task comes from Jira, the instructor said, fetched as by the fetch Jira function written in the CrewAI chapter: a Jira URL, a Jira email, a Jira token and the Jira key, a function to fetch from Jira, and the task replaced with it. In the repo it is file 13, whose name says the task is kept as an MD file.
# ---------- Fetch the TASK from Jira ----------
# Same Jira config as chapter 07: JIRA_URL, JIRA_EMAIL, JIRA_API_TOKEN in .env
JIRA_URL = os.getenv("JIRA_URL", "https://<your-site>.atlassian.net").rstrip("/")
JIRA_EMAIL = os.getenv("JIRA_EMAIL")
JIRA_API_TOKEN = os.getenv("JIRA_API_TOKEN")
JIRA_ISSUE_KEY = os.getenv("JIRA_ISSUE_KEY", "VWO-146")
TASK_MD_FILE = Path(__file__).parent / f"{JIRA_ISSUE_KEY}.md"
def adf_to_text(node) -> str:
"""Jira Cloud returns the description as ADF (JSON). Flatten it to plain text."""
if node is None:
return ""
if isinstance(node, list):
return "".join(adf_to_text(n) for n in node)
kind = node.get("type")
if kind == "text":
return node.get("text", "")
if kind == "hardBreak":
return "\n"
inner = adf_to_text(node.get("content", []))
if kind == "listItem":
return f"- {inner.strip()}\n"
if kind in ("paragraph", "heading", "codeBlock", "blockquote"):
return inner + "\n"
return inner
def fetch_jira_task(issue_key: str) -> str:
"""GET the ticket, save it as a markdown file, and return the markdown."""
if not (JIRA_EMAIL and JIRA_API_TOKEN):
raise SystemExit("Set JIRA_EMAIL and JIRA_API_TOKEN in .env first.")
resp = requests.get(
f"{JIRA_URL}/rest/api/3/issue/{issue_key}",
auth=(JIRA_EMAIL, JIRA_API_TOKEN),
headers={"Accept": "application/json"},
params={"fields": "summary,description"},
timeout=20,
)
if resp.status_code == 401:
raise SystemExit("Jira 401: the API token is invalid or expired. "
"Create a new one at id.atlassian.com and update JIRA_API_TOKEN.")
if resp.status_code == 404:
raise SystemExit(f"Jira 404: {issue_key} does not exist or this account cannot see it.")
resp.raise_for_status()
fields = resp.json()["fields"]
markdown = (
f"# {issue_key}: {fields['summary']}\n\n"
f"Source: {JIRA_URL}/browse/{issue_key}\n\n"
f"{adf_to_text(fields.get('description')).strip()}\n\n"
"Report a PASS or FAIL for every VERIFY step above, then the final verdict.\n"
)
TASK_MD_FILE.write_text(markdown)
print(f"Saved Jira task to {TASK_MD_FILE.name}")
return markdown
fetch_jira_task asks Jira's REST API v3 for the ticket's summary and description, with the email and token as basic auth, and turns a 401 and a 404 into plain messages. Jira Cloud returns the description as ADF, JSON, as adf_to_text's docstring says, and the function flattens it to text; the ticket is saved as VWO-146.md and becomes the task. 13's main() is 12's, with the fetch and a print added. The Jira site is masked here. With no email or token set, 13 stops before any request:
python 13_FullE2E_FETCH_JIRA_TASK_MD_File_QA_LangChain.py
Set JIRA_EMAIL and JIRA_API_TOKEN in .env first.
The new settings in the repo's .env.example, with the site masked:
# 11_Playwright_AIAgent_Orch_Lvl_1.py: reads DEEPSEEK_API (passed in as api_key)
DEEPSEEK_API=sk-your_deepseek_api_key_here
DEEPSEEK_MODEL=deepseek-chat
# 13_FullE2E_FETCH_JIRA_TASK_MD_File_QA_LangChain.py: the TASK is fetched from this Jira ticket
# API token: https://id.atlassian.com/manage-profile/security/api-tokens
JIRA_URL=https://<your-site>.atlassian.net
JIRA_EMAIL=you@example.com
JIRA_API_TOKEN=your_jira_api_token_here
JIRA_ISSUE_KEY=VWO-146
# 14_MULTIPLE_TC_ExecutorFrom_JIRA_PW_LC.py: uses the Jira keys above plus DEEPSEEK_API
# Open http://localhost:8014 after starting it
EXECUTOR_PORT=8014
# 15_E2E_QA_pipeline.py and 16_Multi_Story_QA_Pipeline_UI.py: use the Groq, DeepSeek and Jira keys above
# Open http://localhost:8016 after starting 16
PIPELINE_PORT=8016
Question. If my ticket does not have all the information, how will it work?
Show the answer
Answer. It will not work, the instructor answered: if your ticket is incomplete, the steps are incomplete, so it will not execute properly.
For 14 to 16, the fetch moved into jira_client.py, shared by all three; the instructor pointed out that it is a separate utility now. Its errors are written to be shown in a UI:
def _get(path: str, params: dict | None = None) -> dict:
if not (JIRA_EMAIL and JIRA_API_TOKEN):
raise JiraError("Set JIRA_EMAIL and JIRA_API_TOKEN in .env first.")
try:
resp = requests.get(
f"{JIRA_URL}{path}",
auth=(JIRA_EMAIL, JIRA_API_TOKEN),
headers={"Accept": "application/json"},
params=params,
timeout=TIMEOUT,
)
except requests.RequestException as exc:
raise JiraError(f"Cannot reach Jira at {JIRA_URL}: {exc}") from exc
if resp.status_code == 401:
raise JiraError("Jira 401: the API token is invalid or expired. "
"Create a new one at id.atlassian.com and update JIRA_API_TOKEN.")
if resp.status_code == 400:
msgs = resp.json().get("errorMessages", []) if resp.headers.get(
"Content-Type", "").startswith("application/json") else []
raise JiraError("Jira rejected the query: " + ("; ".join(msgs) or resp.text[:200]))
if resp.status_code == 404:
# A bad token also lands here: Jira answers as an anonymous user.
raise JiraError("Jira 404: not found, or this account cannot see it. "
"If the ticket exists, check JIRA_API_TOKEN (a bad token also gives 404).")
if not resp.ok:
raise JiraError(f"Jira error {resp.status_code}: {resp.text[:200]}")
return resp.json()
A 404 that was a bad token. The class's Jira token had expired mid-class. The repo's learnings note on a Jira 404: GET /rest/api/3/issue/VWO-146 answered 404, issue does not exist, for an issue that exists, because Jira Cloud answers a bad Basic auth header as an anonymous user. GET /rest/api/3/myself with the same credentials answered 401. So when an issue or a search comes back 404 or empty, call /myself first: a 401 there means the credentials, not the key. jira_client.py's 404 branch, lines 70 to 73, says the same.
Many tickets, one by one
Can we create a UI for this too, the instructor asked: I will give the Jira tickets, and it will execute them automatically. The instruction to the coding agent was to create 14, a multiple test case executor from Jira using Playwright and LangChain, and it created everything, the UI included. If you showcase this POC in your company this week, the instructor was pretty much sure, they will love it.
Question. Can we replace the tool with MCP?
Show the answer
Answer. MCP is used by an AI agent, the instructor answered: if you use MCP here, what is the point of creating a script? You can use MCP directly from Claude Code or GitHub Copilot. These are independent agents: they do not run in Claude Code or GitHub Copilot, they run from Jenkins directly. Jenkins can access MCP too, but here we give the agent independent Playwright tools.
The first try crashed, the instructor thought, and the Jira token had expired. With a fresh one, the executor ran the tickets, and the instructor called it real-time execution by DeepSeek, running the test cases side by side: browser closed successfully, test case passed, with a screenshot at the end. It is running two tickets simultaneously, the instructor said, and then the rest, positive and negative; the last test case was queued while one ran. In the pushed 14, the tickets run one by one, as its docstring and its page's subtitle above say:
def _runner(tickets: list[dict], headless: bool):
started_at = _snapshot()["started_at"]
with _lock:
results = _state["results"]
async def run_all():
for ticket, result in zip(tickets, results):
if _stop_requested.is_set():
with _lock:
result["status"] = "SKIPPED"
continue
_update(message=f"Running {ticket['key']}")
await _run_one(result, ticket, headless)
try:
# Not asyncio.run(): that makes a new loop per run, but the DeepSeek client keeps
# its HTTP connections bound to the loop of the first run, so the second run
# fails with "Event loop is closed". One long-lived loop serves every run.
asyncio.run_coroutine_threadsafe(run_all(), _loop).result()
md_name, json_name = _write_report(_snapshot()["results"], started_at)
_update(status="stopped" if _stop_requested.is_set() else "done",
message="Run complete.", report_md=md_name, report_json=json_name,
finished_at=datetime.now().isoformat(timespec="seconds"))
except Exception as exc:
_update(status="error", message=f"{type(exc).__name__}: {exc}",
finished_at=datetime.now().isoformat(timespec="seconds"))
run_all awaits each ticket before the next, on one event loop started with the server (lines 82 to 84). The comment on lines 226 to 228 sums up the repo's second learnings note: with asyncio.run() per run, every run had a new event loop, but the DeepSeek client, created once at module level, kept its pooled connections tied to the first run's loop, so the second run's first ticket failed in 0.0 s with RuntimeError: Event loop is closed, and the rest passed. One loop for the life of the server, with every run scheduled onto it, fixed it, and 16 uses the same pattern. The executor's page above, from the repo, shows a run with one ticket errored at 0s.
Question. Please clarify how this AI is helping you to create the code.
Show the answer
Answer. It is not creating code, the instructor answered: it is running on the fly, whatever the reactions are.
Of course it will take a lot of tokens, the instructor said: it is a very costly process, and that is why it is not going to replace you. When a learner predicted that QA would disappear in one or two years, the instructor answered: they will not; who is going to create this? You are.
See, it is making a mistake too, the instructor pointed out during the run: on a wrong username, a negative test case; it makes a mistake sometimes. The repo's capture of the executor holds the agent's own report on such a case, VWO-149, invalid username or password: on its first attempt, its two type_by_label calls ran in parallel, and the password field ended up holding both values, with the username field empty; it reloaded and typed each field in turn. That is reproducible. The stand-in run of 11 again, with one change: it asks for both type_by_label calls in one turn, as the agent did:
| Turn | The stand-in asked for | What came back |
|---|---|---|
| 4 | type_by_label Username and type_by_label Password, in one turn |
Typed "demo_user" into the field labelled "Username", and Typed "demo_pass" into the field labelled "Password" |
| 5 | snapshot_page |
textbox "Username", empty; textbox "Password": demo_userdemo_pass |
| 6 | click_by_role on the Login button |
Clicked button named "Login" |
| 8 | assert_text_contains on h1, Products |
FAIL: expected 'Products' NOT found in 'Practice shop' |
| what the form sent | username empty, password demo_userdemo_pass |
Both tools reported success, and the form sent an empty username and both values as the password. Typed one turn after the other, the same calls sent the right values. In one turn, both fills were done 0.7 s after they began; one turn after the other, the two took 1.5 s. launch_browser sets slow_mo=700, which slows each Playwright action by 0.7 s: in one turn, the two waits overlapped.
Sequential by default, but not inside a turn. When the model asks for two tool calls at once, the agent sends each one to its tools node on its own (Send("tools", ...) in LangChain's create_agent), and they run together. type_by_label ends in Playwright's fill, which, in Playwright's own code, selects the field and then types the text with the keyboard into whichever field has the focus by then. Two fills at once on one page share one focus. Rule 4 of 12's and 14's system prompts covers this: do not assume a step worked because the previous tool call returned no error.
The QA pipeline
The last project, the instructor said: an end-to-end QA pipeline. It will take a ticket, fetch it, retrieve it, plan it, execute it and report it. The instructor did not write it, but told Claude, on Opus 5.5, to write it according to the learned concepts: an AI agent that fetches, retrieves, plans, executes and reports.
This time, the ticket is not a test case. Ticket 49 is a feature, like a story, as a learner said: it has to be converted into a plan, then into multiple test cases, which Playwright then runs. Groq will write the test plan, the instructor said, and DeepSeek will drive the browser, because DeepSeek is markedly better at the long step process; you can do a dry run, without RAG, and so on. 15's docstring says the same:
"""The full QA pipeline: Jira -> RAG -> plan -> cases -> browser -> Slack.
python 15_E2E_QA_pipeline.py VWO-49
Five stages, three of them agents, with a human gate before anything touches a
real browser:
1. FETCH the Jira ticket (REST v3, offline fixture fallback)
2. RETRIEVE the most similar existing test cases from a local RAG <- gate
3. PLAN a test plan grounded in BOTH the ticket and the RAG hits (Groq)
4. EXECUTE the automatable cases in Chromium (DeepSeek) <- gate
5. REPORT a reporter agent posts the verdict over a DUMMY Slack MCP
Two models on purpose: Groq writes the plan, DeepSeek drives the browser,
because DeepSeek is markedly better at long multi-step tool discipline (see
chapter 09 vs 10). Both are cheap.
--yes skip both gates (CI)
--dry-run stop after stage 3, no browser
--no-rag skip retrieval, to see what grounding is actually worth
"""
Stage 1 tries Jira and falls back to a fixture, a saved copy of the ticket in the repo:
def fetch_ticket(key: str) -> dict:
try:
ticket = fetch_issue(key)
print(f"Fetched {key} live from Jira.")
except JiraError as exc:
fixture = FIXTURES / f"{key}.json"
if not fixture.exists():
raise SystemExit(f"Jira failed ({exc}) and there is no fixture at {fixture}.")
ticket = json.loads(fixture.read_text())
print(f"Jira failed ({exc}).\nUsing the offline fixture {fixture.name}.")
print(f"\n{ticket['key']}: {ticket['summary']}\n{ticket['description'][:600]}...")
return ticket
Stage 2 is the RAG: a lightweight, local one, the instructor said, nothing but the previous test cases we have. Here it is BM25, keyword ranking with no vector database, over the 5,000 rows of the CSV from chapter 14:
def retrieve(ticket: dict, k: int = 5) -> list[dict]:
rows = list(csv.DictReader(RAG_CSV.open(encoding="utf-8")))
docs = [tokenize(" ".join(r[c] for c in ("Summary", "Description", "Component",
"Labels", "Steps", "Expected Result")))
for r in rows]
index = BM25(docs)
query = tokenize(f"{ticket['summary']} {ticket['description']}")
# The library is templated: the same case repeats once per device and browser.
# Keep one row per summary so the 5 hits are 5 different ideas.
hits, seen = [], set()
for i, score in index.top(query, k * 50):
r = rows[i]
fingerprint = r["Summary"].lower()
if fingerprint in seen:
continue
seen.add(fingerprint)
hits.append({"key": r["Issue Key"], "score": round(score, 2), "summary": r["Summary"],
"steps": r["Steps"], "expected": r["Expected Result"]})
if len(hits) == k:
break
print(f"Searched {len(rows)} existing test cases. Top {len(hits)}:")
for h in hits:
print(f" {h['key']} score {h['score']:>5} {h['summary']}")
return hits
Run here with no Jira login, 15 falls back to the fixture, ranks the library and stops at the first gate on n. No model is involved up to here:
python 15_E2E_QA_pipeline.py VWO-49
======================================================================
STAGE 1: FETCH the Jira ticket
======================================================================
Jira failed (Set JIRA_EMAIL and JIRA_API_TOKEN in .env first.).
Using the offline fixture VWO-49.json.
VWO-49: [VWO] Add Passkey and SSO Login Options to VWO Login Page
Priority:
High
Epic Link:
Authentication Enhancements
Description:
As a user, I want to log in using either Passkey or Single Sign-On (SSO), so that I can access my account more securely and conveniently without relying solely on email/password authentication.
Two new login options - “Sign in using SSO” and “Sign in with Passkey” - have been added to the login page alongside existing authentication methods. These options should function seamlessly and provide a smooth user experience across supported environments.
Acceptance Criteria:
- UI Visibility
- GIVEN the user is on the login page
- THE...
======================================================================
STAGE 2: RETRIEVE similar test cases (local RAG)
======================================================================
Searched 5000 existing test cases. Top 5:
VWO-1271 score 212.32 [User Management] UI/UX: validate rendering of SSO login
VWO-5956 score 207.36 [User Management] Functional: validate SSO login
VWO-1268 score 205.62 [User Management] UI/UX: check responsiveness of SSO login
VWO-5204 score 201.52 [User Management] UI/UX: verify layout of SSO login
VWO-1564 score 200.98 [User Management] Security: test injection defense on SSO login
[gate] Ground the test plan on these test cases? [y/N] n
Stopped at the gate. Nothing else was run.
The five hits are SSO login cases. The library is templated, as line 138's comment says: 5,000 rows hold 1,520 distinct summaries, and every row's preconditions follow one pattern. These are previous dummy test cases we have added, the instructor said. If you do not want RAG, you can ignore it.
Question. Why are we using RAG? Why do we want to find similar test cases?
Show the answer
Answer. When you find a similar test case, your steps will be accurate, the instructor answered: the LLM will hallucinate less if you add a RAG.
Stage 3 plans with Groq, in a structured output like 10's:
class PlannedCase(BaseModel):
id: str = Field(description="Short id such as TC-01")
title: str
priority: Literal["High", "Medium", "Low"]
preconditions: list[str]
steps: list[str] = Field(description="Concrete browser steps a tester can follow")
expected_result: str
automatable: bool = Field(description="True if a browser agent can run it using only "
"what the ticket gives (URL, test credentials); False if it "
"needs an SSO provider, passkey hardware or secrets not in the ticket")
reason: str = Field(description="Why it is or is not automatable right now")
grounded_on: list[str] = Field(description="Issue keys of the retrieved test cases this "
"case reuses; empty if none")
class TestPlan(BaseModel):
scope: str
out_of_scope: list[str]
risks: list[str]
test_cases: list[PlannedCase]
PLANNER_PROMPT = """You are a senior QA lead. Write a concise, risk-based test plan
for the Jira ticket you are given.
Rules:
1. Cover every acceptance criterion in the ticket, positive and negative.
2. When existing test cases are provided, reuse their wording and coverage where it
fits, and list their keys in grounded_on. Never cite a key you were not given.
3. Mark a case automatable when a browser agent can run it using ONLY the
Application URL above plus what the ticket gives (test credentials written in the
ticket count). Checking what a public page shows (buttons, labels, order, error
text, layout) needs nothing else, so it is automatable.
Mark it manual when it needs an SSO identity provider, passkey hardware, an
email inbox, or credentials the ticket does not contain.
4. Steps must be concrete enough for a browser agent: what to open, what to click,
what text to check. Do not invent URLs, credentials or text that the ticket does not give.
5. Between 4 and 8 test cases."""
The planner asks for a TestPlan, and the hits go into its prompt. These notes ran 15 with --yes --dry-run against the stand-in, which answers the planner with a fixed two-case plan and the reporter with one Slack call. The planner's request: its user message ends with the five cases, the first two of them here:
EXISTING TEST CASES FROM OUR LIBRARY:
- VWO-1271: [User Management] UI/UX: validate rendering of SSO login
Steps: 1. Log in to VWO and open the User Management module. | 2. Navigate to the SSO login screen. | 3. Perform the SSO login action with valid inputs and save. | 4. Observe the result on desktop using Safari 19.
Expected: The SSO login renders correctly with no overlap or clipping across the tested viewport.
- VWO-5956: [User Management] Functional: validate SSO login
Steps: 1. Log in to VWO and open the User Management module. | 2. Navigate to the SSO login screen. | 3. Perform the SSO login action with valid inputs and save. | 4. Observe the result on mobile (Android) using Edge 148.
Expected: The SSO login works as specified and the change is saved and reflected in the UI.
With --no-rag, the same place reads:
EXISTING TEST CASES FROM OUR LIBRARY:
(none, retrieval was skipped)
The rest of the dry run: the fixed plan, no browser, and the report.
======================================================================
STAGE 3: PLAN with Groq
======================================================================
Scope: stand-in: a fixed plan, written by no model
[AUTO ] TC-01 High stand-in case 1
[MANUAL] TC-02 Medium stand-in case 2
--dry-run: stopping before the browser.
======================================================================
STAGE 5: REPORT to Slack (dummy MCP)
======================================================================
----- Slack #qa-results (dummy) -----
*VWO-49: [VWO] Add Passkey and SSO Login Options to VWO Login Page*
Overall verdict: NOT RUN (dry run, nothing executed)
Executed: 0
Manual cases left: 1
----------------------------------------
Full report: reports/pipeline_VWO-49_YYYYMMDD_HHMMSS.md
Stage 5's Slack is a dummy, as its comment says: the same name and arguments as the Slack MCP server's tool, but it writes to a local outbox. And, as the comment in report() says, the overall verdict is decided in code, not by the model:
@tool
def slack_post_message(channel: str, text: str) -> str:
"""Post a message to a Slack channel. Use Slack mrkdwn: *bold*, bullet lines with •."""
# DUMMY: same name and arguments as the Slack MCP server's tool, but it writes
# to a local outbox instead of calling Slack. Swap in the real MCP tool later.
REPORTS.mkdir(exist_ok=True)
with SLACK_OUTBOX.open("a") as f:
f.write(json.dumps({"ts": datetime.now().isoformat(timespec="seconds"),
"channel": channel, "text": text}) + "\n")
print(f"\n----- Slack #{channel.lstrip('#')} (dummy) -----\n{text}\n" + "-" * 40)
return f"ok: posted to {channel} (dummy outbox {SLACK_OUTBOX.name})"
REPORTER_PROMPT = """You are a QA reporter. Post ONE Slack message summarising a
pipeline run by calling slack_post_message exactly once, to channel "#qa-results".
The message must contain: the ticket key and title, the overall verdict
EXACTLY as given in the data (never work it out yourself), counts of passed/failed/other,
one bullet per executed case with its status, and the number of manual cases
left for a human. Keep it under 20 lines. Report only what the data says."""
def report(ticket: dict, test_plan: TestPlan, results: list[dict], dry_run: bool):
llm = ChatGroq(model=os.getenv("LLM_MODEL", "openai/gpt-oss-120b"), temperature=0)
reporter = create_agent(model=llm, tools=[slack_post_message], system_prompt=REPORTER_PROMPT)
# The verdict is decided in code, not by the model: an LLM will happily call
# zero executed cases "PASSED".
statuses = [r["status"] for r in results]
if not statuses:
overall = "NOT RUN"
elif all(s == "PASSED" for s in statuses):
overall = "PASSED"
else:
overall = "FAILED"
A full run on the same stand-in, with --url pointing at the local practice page and one case, shows stage 4 too. The executor gets the case as its task and the same 32 tools; the stand-in writes no verdict, so verdict() finds none:
======================================================================
STAGE 4: EXECUTE automatable cases with DeepSeek + Playwright
======================================================================
[gate] Open a real browser and run 1 case(s) against http://127.0.0.1:<port>/login? -> auto-yes (--yes)
[1/1] TC-01 stand-in case 1
-> launch_browser({'headless': True})
-> navigate_to({'url': 'http://127.0.0.1:<port>/login'})
-> snapshot_page({})
-> type_by_label({'label': 'Username', 'text': 'demo_user'})
-> type_by_label({'label': 'Password', 'text': 'demo_pass'})
-> snapshot_page({})
-> click_by_role({'role': 'button', 'name': 'Login'})
-> get_page_info({})
-> assert_text_contains({'selector': 'h1', 'expected_text': 'Products'})
-> take_screenshot({'filename': 'standin_login.png'})
-> close_browser({})
=> UNKNOWN
======================================================================
STAGE 5: REPORT to Slack (dummy MCP)
======================================================================
----- Slack #qa-results (dummy) -----
*VWO-49: [VWO] Add Passkey and SSO Login Options to VWO Login Page*
Overall verdict: FAILED (executed)
Executed: 1
Manual cases left: 1
----------------------------------------
Full report: reports/pipeline_VWO-49_YYYYMMDD_HHMMSS.md
A case with no verdict is not a pass: the report calls the run FAILED.
Question. If there are 20 stories, or a PRD, will it work the same?
Show the answer
Answer. You can change this for 20 stories and multiple stories too, the instructor answered: I will ask it to create that. That became 16, below.
Question. You are creating every script with Claude Opus, right?
Show the answer
Answer. Yes, the instructor answered: you can use anything; Opus 5.5 is the default for now.
Question. Is there a mechanism, or a best practice, to consume fewer tokens?
Show the answer
Answer. The best practice will be planning, the instructor answered. Tokenomics will be a separate session: there are a lot of concepts, prompt caching, response caching and more.
A learner asked for a human review in this step, if possible: you can add a human review too, the instructor said; human in the loop is also allowed in LangChain. 15 stops at two gates, unless --yes. Human review is always required, the instructor said: everything it creates has to be reviewed, and the full pipeline has to be reviewed multiple times; only then do you deploy it.
Many stories in one page
16 is 15 for many stories, with a UI, as the instructor described it: enter stories such as VWO-49, VWO-50 and VWO-51; each one prepares a test plan, say 10 test cases, and executes them, then runs and reports. 16's docstring:
"""Multi-story QA pipeline with a UI: the 15_E2E_QA_pipeline stages, for many stories.
python 16_Multi_Story_QA_Pipeline_UI.py
open http://localhost:8016
Flow in the page:
1. Enter Jira keys (VWO-49, VWO-150) or a JQL query, click "Fetch & plan".
Every story is FETCHED, RETRIEVED against the local RAG and PLANNED by Groq.
The stories are planned in parallel (asyncio.gather, as in 06_Agent_Parallel_Vs_Sequential).
2. Review each plan. Automatable cases are pre-ticked. This review IS the human gate.
3. Click "Run selected": DeepSeek runs the ticked cases one by one in Chromium,
then the reporter agent posts one dummy Slack message per story.
A "How it works" tab shows the pipeline diagram (16_frontend/assets/how-it-works.png,
rendered by Codex from how-it-works.brief.md). A "RAG library" tab browses and searches all 5000 existing test cases
the planner is grounded on, with the same BM25 ranking the pipeline uses.
The stage functions are imported from 15_E2E_QA_pipeline.py, not copied.
"""
The plans run side by side, as in 06 from the last class, the docstring says:
async def _plan_all(tickets: list[dict], use_rag: bool):
# Each plan is a blocking Groq call: run them side by side in worker threads
await asyncio.gather(*[asyncio.to_thread(_plan_one, t, use_rag) for t in tickets])
Question. Does it fetch, plan and execute each time, or does it set up once?
Show the answer
Answer. It is a one-time fetching, the instructor answered: it fetches your two tickets once, here VWO-49 and VWO-150, and executes them.
Question. The file will use new Playwright functions, not the previous ones?
Show the answer
Answer. It will use the same, the instructor answered: the same tools.
In class, the page planned 10 test cases for one story, with similar ones found through the lightweight RAG, and five for another; you first plan, then run, and you can run all of them. While it planned, the page answered a new fetch with busy, wait for the current step to finish, its line 116. Three stories ran in the end, each with its outputs side by side, and a final report.
Where is the RAG? The instructor looked for it in the page and added it, and after a refresh it was there: the RAG library tab, in the pushed 16. Its search runs the planner's own BM25 over all 5,000 rows. Called here without starting the server, for sso login error message:
{
"total_library": 5000,
"matches": 953,
"page_size": 25,
"first": [
{
"key": "VWO-3272",
"score": 17.13,
"summary": "[User Management] Negative: prevent misuse of SSO login",
"type": "Negative"
},
{
"key": "VWO-4061",
"score": 17.13,
"summary": "[User Management] Negative: handle failure of SSO login",
"type": "Negative"
},
{
"key": "VWO-1513",
"score": 17.01,
"summary": "[User Management] Negative: handle failure of SSO login",
"type": "Negative"
}
],
"app_url for VWO-49": "https://app.vwo.com/#/login"
}
_app_url picks the URL a story's cases run against: the first URL in the story's description, else 15's default, VWO's login page. VWO-49's description has no URL.
How it works, the instructor showed in a diagram: fetch the Jira tickets, retrieve similar test cases from the RAG, the top five, create a test plan, review it, execute with DeepSeek and Playwright, and push to Slack and Markdown. In the repo, it is the How it works tab's picture; the diagram that opens the QA pipeline section above draws the same stages from 15's code.
Question. How can we verify these scripts are correct, that it executes the story correctly?
Show the answer
Answer. You have to verify, the instructor answered: you are the real orchestrator. You will run it multiple times, then you will verify: that is why QA is not going to be replaced. Multiple times you have to test it from your end.
Tasks and announcements
- The task: the multi-story Playwright executor. Now it is your responsibility to create this, the instructor said: build the multi-story Playwright executor and show it next week, in the Saturday and Sunday classes.
- Next weekend: LLM evaluation. Next Saturday and Sunday, the class learns LLM evaluation; the week after, LangGraph.
- The code and the notes. I will push the code, the instructor said at the end: it is in chapter 17 of the batch repository, files 10 to 16, in one commit at 10:06. The architecture diagram the instructor added is in it, as the How it works tab's picture; the prompts used, the instructor will also put in, if possible.
- A separate session on token costs. Tokenomics gets its own session: prompt caching, response caching and more.
- Review before you deploy. Human review is always required, and the full pipeline has to be reviewed multiple times before you deploy it.
Task. Build the multi-story Playwright executor, and show it next week, in the Saturday and Sunday classes.
Worth practising too: What does response_format=TestCaseList put in the request, and what happens to a reply whose priority is Urgent? An agent's two type_by_label calls both report success, yet the form sent the wrong values: why, and what guards against it? Why does 15 decide the overall verdict in code, and what does a case with no verdict count as?
Show the answer
Answer. The schema: the classes become a JSON schema in response_format, with priority as an enum of three, and a reply with Urgent stops the run with a validation error. The two calls: the agent runs both tool calls of one turn at the same time, and fill types into whichever field has the focus, so both texts went into the password field; verify after acting, with snapshot_page or an assertion, as rule 4 of 12's system prompt says. The verdict: an LLM will happily call zero executed cases passed, as 15's comment says, so 15 reads TEST PASSED or TEST FAILED from each case's report and decides the overall verdict itself; a case with no verdict is UNKNOWN, and the run counts as FAILED.