Build AI agents for test automation in plain Python. Eight short chapters ending in a browser agent that runs a real login test from a plain-English task and reports PASS or FAIL. Every code block on this page is the actual file in src/chapters/. The outputs are trimmed samples: the model words its answers differently on every run.
LangChain = build with bricksmodels, prompts, tools, agents
LangGraph = connect the bricks into workflowsstate, branching, loops, approvals
LangSmith = inspect, evaluate and improvetraces, tests, monitoring
What is LangChain?
LangChain is a framework for building applications powered by large language models. It gives you the building blocks (models, prompts, tools, memory, retrieval) and a single create_agent() function that wires them into an agent.
A LangChain agent is an LLM-powered system that can understand user input, reason, and generate responses. Give it tools and it can also take action: run a calculation, call an API, fetch a page, generate test cases in a fixed format.
Agent = Model + System prompt + Tools + a loop. The model reads the messages, decides whether to answer or call a tool, and repeats until the task is done. Everything in this guide is a variation of that one idea.
LangChain vs LangGraph vs LangSmith
The LangChain ecosystem: purpose, features and differences. This course covers the first column.
LangChain
Build LLM applications easily
A framework for developing LLM-powered applications. It provides the building blocks to chain components together and create end-to-end apps.
langchain gives you create_agent and @tool. Each model provider ships as its own package. python-dotenv loads your keys, requests is used by the web tools in chapter 06. Pydantic (used in chapter 07) is installed with LangChain.
# Gemini - used by chapters 01 to 07
GEMINI_LLM_MODEL=google_genai:gemini-flash-lite-latest
GOOGLE_API_KEY=AIza... # must start with AIza. An AQ. value is an
# OAuth token and expires within the hour.
# Groq - used by 001_Hello_LC.py and the Groq browser agent (009)
LLM_MODEL=openai/gpt-oss-120b
GROQ_API_KEY=gsk_...
# DeepSeek - used by the chapter 08 browser agent (010)
DEEPSEEK_API=sk-...
.gitignore
.env
.venv/
Optional: a local model with Ollama (offline, free)
terminal
# install from https://ollama.com, then pull a small model
ollama pull gemma2:2b
# for chapters 05 to 07 (tool calling, structured output) pick a tool-capable model
ollama pull qwen3
Project layout and how to run a chapter
project structure
chapter_17_LangChain/
├── .env # API keys (gitignored)
├── LangChain_Notes.html # these notes
├── E2E_QA_Pipeline.md # the 8-step blueprint
└── src/
├── .venv/
└── chapters/
├── 001_Hello_LC.py # raw model call, no agent
├── 002_Hello_Gemini.py # first agent
├── 003_Hello_Gemini_Steam.py # streaming
├── 004_SP.py # system prompt
├── 005_Agent_Parallel_Vs_Sequential.py
├── 006_Tool.py # one QA tool
├── 007_MultiTool.py # two tools
├── 008_Structure_output.py # Pydantic output
├── 009_Playwright_Agent_Orch.py # browser agent (Groq)
├── 010_Playwright_Agent_Orch_Deepseek.py
└── playwright_tools.py # 32 Playwright tools
terminal
cd src/chapters
../.venv/bin/python 002_Hello_Gemini.py
Model strings: one line to switch providers
Every agent takes a model as "provider:model". Swap the string, keep the rest of the code.
Model string
Needs
Why
google_genai:gemini-flash-lite-latest
GOOGLE_API_KEY
Fast, cheap, free tier. Great for learning.
anthropic:claude-haiku-4-5
ANTHROPIC_API_KEY, langchain-anthropic
Strong at tool use and structured output.
ollama:gemma2:2b
Ollama running locally
Runs on your laptop, no internet, no key.
01
Creating your first LangChain agent
Set up an agent with create_agent(), send it a message, print the reply.
You send a list of messages (role + content). The agent forwards them to the model and gives you back the full conversation, with the reply at the end.src/chapters/002_Hello_Gemini.py
import os
from dotenv import load_dotenv
from langchain.agents import create_agent
load_dotenv()
def main():
agent = create_agent(model=os.environ["GEMINI_LLM_MODEL"])
query = input("Ask your question: ")
result = agent.invoke({"messages": [("user", query)]})
print(result["messages"][-1].text)
if __name__ == "__main__":
main()
Run: python src/chapters/002_Hello_Gemini.py
Output
Ask your question: What is the capital of India?
The capital of India is New Delhi.
load_dotenv()
Python's version of import "dotenv/config". Reads .env so the API key is in the environment, not in your code.
create_agent()
Builds the agent. The model string picks the provider. Comment one line, uncomment the other, to switch cloud and local.
result["messages"][-1]
The conversation history is a list. The last item is the agent's answer; .text is its text.
Key takeaways
Set up a basic agent with create_agent()
Pass messages to the agent as a list of role + content
Extract and display the final response with result["messages"][-1].text
Use .env for API keys
Switch between cloud (Gemini) and local (Ollama) models with one line
Exercises
Create your .env with your Gemini API key and run the file.
Run the same code with Gemini and then with Ollama. Compare speed and answer quality.
Change the question to something from your own project and observe the result.
02
invoke vs stream
Two ways to get an answer, and the system + user message pattern that makes agents behave.
At a glance
invoke
Get the complete response at once
Simple and easy
Best for scripts and batch processing
VS
stream
Get the response token by token
Feels faster (real-time)
Best for chat UIs and live tools
A system message sets the behaviour and expertise of the agent. The user message is the actual question. This pair is the foundation of every good agent.
src/chapters/003_Hello_Gemini_Steam.py
import os
from dotenv import load_dotenv
from langchain.agents import create_agent
load_dotenv()
def main():
agent = create_agent(model=os.environ["GEMINI_LLM_MODEL"])
query = input("Ask your question: ")
print("\nStreaming Response:")
for token, metadata in agent.stream(
{
"messages": [
{"role": "system", "content": "You are a software testing instructor."},
{"role": "user", "content": "Explain LLM Eval in 3000 words blog"},
]
},
stream_mode="messages",
):
print(token.text, end="", flush=True)
print()
if __name__ == "__main__":
main()
Ask your question: what is LLM eval?
Streaming Response:
LLM evaluation (LLM eval) is how you measure whether a language model's answers
are correct, relevant and safe for your use case... (appears token by token)
Watch out: this file reads your question into query but never sends it. The user message is the fixed text "Explain LLM Eval in 3000 words blog". Replace that string with query to stream an answer to your own question.
Feature
invoke
stream
Response style
Full response at once
Token by token
Use case
Scripts, batch processing
Chat UIs, live demos
Speed perception
Waits until the end
Feels faster (typing effect)
Memory usage
Lower for short responses
Slightly higher
Complexity
Very simple
Slightly more code
In automation testing agents we often use both: stream for developer-facing tools where someone is watching, invoke for backend workflows such as CI jobs.
Key takeaways
invoke() returns the complete response (most common for starters)
stream() with stream_mode="messages" yields tokens in real time
Always use a system message to define the agent's role
Proper message structure (role + content) is the foundation of good agents
These two methods cover 95% of LangChain agent implementations
Exercises
Ask the same question with invoke and with stream. Which one would you use in a CI pipeline, and which in a chat UI?
Change the system message to "You are a senior Playwright engineer" and compare the answer.
Loop over result["messages"] and print each message's .type and .content to see the full history.
03
System prompts: giving your agent a personality and instructions
A system prompt is a job description you hand the agent before the conversation starts.
At a glance
User message
What the user asks
The actual question or request
Changes every time
VS
System prompt
Defines who the agent is
Sets behaviour, tone and rules
Stays constant
Huge impact on response quality
It tells the agent who it is, how it should behave, what tone to use and what rules to follow. Think of hiring: system prompt = job description, user message = task given, agent response = work delivered.
src/chapters/004_SP.py
from dotenv import load_dotenv
from langchain.agents import create_agent
load_dotenv()
agent = create_agent(
model="google_genai:gemini-flash-lite-latest",
system_prompt=(
"You are a helpful AI assistant specialized in automation testing "
"and software development. Be clear, concise, and always think step by step."
),
)
result = agent.invoke({
"messages": [{"role": "user", "content": "Who are you?"}]
})
print("Agent Response:")
print(result["messages"][-1].content)
Run: python src/chapters/004_SP.py
Output
Agent Response:
I am an AI assistant specialized in automation testing and software development.
I help with test automation, frameworks, code, and best practices.
Without a good system prompt (for example system_prompt="You are AI assistant.") the response is generic, less useful and not focused on your domain. A small change in the prompt is a big improvement in output quality.
Best practices for system prompts
Rule
Example
Define the role clearly
"You are a senior automation testing engineer..."
Set behaviour rules
"Be clear, concise, think step by step, always use tools when needed."
Name the domain expertise
Mention Playwright, Appium, test frameworks, API testing.
Give output guidelines
Ask for structured, professional or JSON output when needed.
Keep it concise
Very long prompts can reduce performance.
Real testing example
a stronger QA system prompt
system_prompt = (
"You are a senior automation testing engineer with 10+ years of experience. "
"You specialise in Playwright, Appium and API testing. "
"Always think step by step and give practical, production-ready answers. "
"When you propose a test, state the preconditions and the expected result."
)
Result: more professional, focused and practical responses.
Key takeaways
System prompts define your agent's identity and behaviour
They are one of the most powerful tools for controlling output quality
Small changes in the prompt can create big improvements
Exercises
Create 3 different system prompts: general assistant, testing expert, code reviewer.
Ask all three the same question and compare the responses.
Write a prompt specialised in generating Playwright locators and test it on a login form.
Work smarter, not slower. asyncio.gather() is Python's Promise.all().
At a glance
Sequential calls
One by one execution
Takes more time
Blocks the next call
Not efficient for batch work
VS
Parallel calls (asyncio.gather)
All at the same time
Much faster
Independent execution
Perfect for batch processing
Generate test cases for several user stories, explain several concepts, or analyse several bugs: running them one by one is slow. In parallel you get all responses much faster.src/chapters/005_Agent_Parallel_Vs_Sequential.py
import asyncio
import time
from dotenv import load_dotenv
from langchain.agents import create_agent
load_dotenv()
agent = create_agent(
model="google_genai:gemini-flash-lite-latest",
system_prompt=(
"You are an experienced software testing instructor. "
"Explain each concept in 10 bullet points"
),
)
questions = [
{"id": 0, "topic": "LLM Eval", "prompt": "What is llm Eval?"},
{"id": 1, "topic": "Smoke Testing", "prompt": "What is smoke testing?"},
{"id": 2, "topic": "Sanity Testing", "prompt": "What is sanity testing?"},
{"id": 3, "topic": "Regression Testing", "prompt": "What is regression testing?"},
]
async def main():
print("Creating LangChain agent...\n")
start = time.perf_counter()
# asyncio.gather runs every agent.ainvoke() call CONCURRENTLY
results = await asyncio.gather(*[
agent.ainvoke({"messages": [{"role": "user", "content": q["prompt"]}]})
for q in questions
])
# results come back in the same order as the questions list
for q, result in zip(questions, results):
print(f"{q['id']}. {q['topic']}")
print(result["messages"][-1].content)
print("-" * 70)
print(f"Finished {len(questions)} calls in {time.perf_counter() - start:.1f}s")
asyncio.run(main())
Creating LangChain agent...
0. LLM Eval
* LLM eval measures how good a model's answers are for your task.
* It checks accuracy, relevance, safety and consistency.
...
----------------------------------------------------------------------
1. Smoke Testing
* A quick check that the most important features of a new build work.
* It decides whether the build is stable enough for deeper testing.
...
----------------------------------------------------------------------
2. Sanity Testing
* A narrow check that a specific fix or change works as expected.
* It runs after a small change, before a full regression cycle.
...
----------------------------------------------------------------------
3. Regression Testing
* Re-running existing tests to confirm new changes broke nothing.
...
----------------------------------------------------------------------
Finished 4 calls in 3.2s
Shortcut:agent.batch([input1, input2, input3]) runs a list of inputs in parallel with one synchronous call. asyncio.gather is the pattern to know when you mix agents with other async work (Playwright, HTTP calls, databases).
Key concepts
asyncio.gather() runs multiple coroutines in parallel, like Promise.all()
Each agent.ainvoke() is independent but uses the same agent config
The system prompt is shared across all calls
Results arrive in the order of the original list, so zip(questions, results) lines them up
Real testing use cases: generate test cases for multiple user stories at once, explain multiple testing concepts, analyse multiple bugs in parallel.
Exercises
Add 3 more testing concepts to the questions list.
Run 8 to 10 questions at once.
Measure the time with asyncio.gather and again with a plain for loop calling agent.invoke(). Note the difference.
05
Creating your first tool and agent
Give your agent a tool and watch it do real work instead of guessing.
At a glance
Without tools
Agent can only reply using its knowledge
Cannot perform calculations or external tasks
Limited to text responses
VS
With tools
Agent can call tools to do real work
Gets accurate and dynamic results
Much more powerful and useful
A tool = function + metadata + input schema. In Python the @tool decorator builds all three from one function:
function body
The implementation. What runs when the agent calls the tool.
name + docstring
The metadata. Function name = tool name, docstring = description that tells the agent when to use it.
type hints
The schema. expression: str is what Zod did in TypeScript: it defines the expected input shape.
src/chapters/006_Tool.py
import ast
import operator
from dotenv import load_dotenv
from langchain.agents import create_agent
from langchain.tools import tool # create custom tools
load_dotenv()
# eval() on text a model produced is arbitrary code execution. This walks the
# parsed expression instead, so only arithmetic can ever run.
_OPS = {
ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul,
ast.Div: operator.truediv, ast.Pow: operator.pow, ast.USub: operator.neg,
}
def _safe_eval(node):
if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):
return node.value
if isinstance(node, ast.BinOp) and type(node.op) in _OPS:
return _OPS[type(node.op)](_safe_eval(node.left), _safe_eval(node.right))
if isinstance(node, ast.UnaryOp) and type(node.op) in _OPS:
return _OPS[type(node.op)](_safe_eval(node.operand))
raise ValueError("only arithmetic is allowed")
@tool
def qa_metric_calculator(expression: str) -> str:
"""Calculate a QA metric from an arithmetic expression.
Use this for pass rate, defect density, automation coverage, defect leakage
or execution time. Input must be plain arithmetic with no words, for example
'(438/500)*100' for a pass rate or '18/12' for defects per KLOC.
"""
try:
result = _safe_eval(ast.parse(expression, mode="eval").body)
return f"{round(result, 2)}"
except Exception:
return "Error: give me a plain arithmetic expression, e.g. '(438/500)*100'"
agent = create_agent(
model="google_genai:gemini-flash-lite-latest",
tools=[qa_metric_calculator], # list of available tools
system_prompt=(
"You are a QA metrics assistant for a test automation team. "
"Use the qa_metric_calculator tool whenever a number must be computed. "
"State the formula you used, then the result with its unit."
),
)
queries = [
# maths -> the agent must call the tool
"We ran 500 regression tests and 438 passed. What is the pass rate?",
"A module of 12 KLOC has 18 defects. What is the defect density per KLOC?",
# no maths -> the agent answers directly, no tool call
"What is the difference between smoke testing and sanity testing?",
]
for q in queries:
print(f"\nQuestion: {q}")
result = agent.invoke({"messages": [{"role": "user", "content": q}]})
print("Agent:", result["messages"][-1].text)
Run: python src/chapters/006_Tool.py
Output
Question: We ran 500 regression tests and 438 passed. What is the pass rate?
Agent: Pass rate = (passed / total) x 100 = (438/500) x 100 = 87.6%.
Question: A module of 12 KLOC has 18 defects. What is the defect density per KLOC?
Agent: Defect density = defects / KLOC = 18/12 = 1.5 defects per KLOC.
Question: What is the difference between smoke testing and sanity testing?
Agent: Smoke testing is a broad, shallow check that a new build is stable enough
to test. Sanity testing is a narrow check that one specific fix or change works.
The agent decides on its own whether to use the tool or answer from its knowledge. To watch that decision, print the history: for m in result["messages"]: print(m.type, getattr(m, "tool_calls", None) or m.content). You will see a tool message only for the math questions.
A tool = function + metadata + input schema, all from @tool
The agent decides when to call the tool
Clear descriptions and schemas help the agent use tools correctly
This is the foundation for building automation testing agents
Exercises
Add a new tool, for example a current date-time tool or a string manipulation tool.
Extend qa_metric_calculator to report defect leakage and automation coverage percentages.
Ask the agent more questions and observe when it uses the tool and when it does not.
06
Creating multiple tools and agents
More tools, more power. The agent picks the right one for each request.
At a glance
Single-tool agent
Can do one type of task
Limited capabilities
Good for learning basics
VS
Multi-tool agent
Can do multiple types of tasks
More capable and flexible
Ready for real-world automation
src/chapters/007_MultiTool.py
import re
import requests # call external APIs and pages
from dotenv import load_dotenv
from langchain.agents import create_agent
from langchain.tools import tool
load_dotenv()
HEADERS = {"User-Agent": "Mozilla/5.0"}
# Tool 1: search the web and return the title of the results page
@tool
def search_tool(query: str) -> str:
"""Search the web for a query and return the title of the results page."""
try:
res = requests.get("https://html.duckduckgo.com/html/",
params={"q": query}, headers=HEADERS, timeout=10)
match = re.search(r"<title>(.*?)</title>", res.text, re.S)
return match.group(1).strip() if match else "No title found"
except Exception:
return "Error performing search"
# Tool 2: fetch a URL and return its plain text (first 1000 characters)
@tool
def web_content_tool(url: str) -> str:
"""Fetch the content of a web page from a URL and return its plain text."""
try:
res = requests.get(url, headers=HEADERS, timeout=10)
text = re.sub(r"<[^>]*>", "", res.text) # strip HTML tags
return text[:1000]
except Exception:
return "Error fetching web content"
agent = create_agent(
model="google_genai:gemini-flash-lite-latest",
tools=[search_tool, web_content_tool], # pass both tools in the list
system_prompt=(
"You are a helpful automation testing assistant. "
"Use the available tools to search the web and fetch content when needed."
),
)
queries = [
"What is Playwright?", # general info (may use search)
"Search for the Appium official website", # needs search_tool
"Get content from https://playwright.dev/docs/intro", # needs web_content_tool
]
for q in queries:
print(f"\nQ: {q}")
result = agent.invoke({"messages": [{"role": "user", "content": q}]})
print(f"Agent: {result['messages'][-1].content}")
Run: python src/chapters/007_MultiTool.py
Output
Q: What is Playwright?
Agent: Playwright is an open-source framework for end-to-end testing of web apps...
Q: Search for the Appium official website
Agent: The search results page title is "Appium official website at DuckDuckGo"...
Q: Get content from https://playwright.dev/docs/intro
Agent: The page introduces Playwright, its installation via npm init playwright...
Tools available to the agent
search_tool: search the web and get the page title web_content_tool: get content from any URL
Why multiple tools?
Expand agent capabilities, handle real-world automation tasks, combine multiple data sources, make the agent more powerful and useful.
Key takeaways
Build each tool with a clear input schema (type hints)
Give good descriptions so the agent knows when to use each tool
Pass all tools in the tools=[...] list
The agent chooses the right tool automatically
This is the foundation for advanced agents
Exercises
Add a date/time tool and test it.
Build two QA tools: generate_test_data(type) returning a test email, name or phone number, and suggest_locator(element) returning a data-testid locator for a UI element.
Ask 5 different queries and observe which tool is used for each.
Build a tool that calculates percentages (for example pass rate from passed and total tests) and test it.
07
Structured output: generating test cases automatically
Get clean, validated data from the LLM using a Pydantic schema (Python's Zod).
At a glance
Without structured output
LLM returns plain text
Difficult to parse
Inconsistent format
Manual effort to extract information
VS
With structured output (Pydantic schema)
Clean, validated JSON
Consistent and reliable
Easy to use in automation frameworks
Saves time and reduces errors
src/chapters/008_Structure_output.py
from typing import Literal
from dotenv import load_dotenv
from pydantic import BaseModel
from langchain.agents import create_agent
load_dotenv()
# 1) Define the response schema with Pydantic
class TestCase(BaseModel):
title: str
description: str
steps: list[str]
expected_result: str
priority: Literal["High", "Medium", "Low"]
tags: list[str]
class TestCaseList(BaseModel):
# Tip: always wrap arrays inside an object (better compatibility, especially with Anthropic)
test_cases: list[TestCase]
# 2) Create the agent with response_format
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, # enforce the schema on the final output
)
# 3) Provide a user story and invoke the agent
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}",
}]
})
# 4) Work with the structured result: no manual parsing
print("=== Structured Output ===")
test_cases = result["structured_response"].test_cases
for tc in test_cases:
print(tc.model_dump_json(indent=2))
print(f"\nSuccessfully generated {len(test_cases)} test cases!")
Run: python src/chapters/008_Structure_output.py
Output
=== Structured Output ===
{
"title": "Add Item to Cart - Successful Flow",
"description": "Verify that a user can add an item to the shopping cart successfully.",
"steps": [
"Open the application",
"Login with valid credentials",
"Select a product",
"Add to cart"
],
"expected_result": "Item should be added to the cart and cart count should increase.",
"priority": "High",
"tags": ["cart", "functional", "smoke"]
}
...
Successfully generated 2 test cases!
The schema defines
title, description, steps (list), expected result, priority (enum: High / Medium / Low), tags (list).
response_format
Tells LangChain to enforce the Pydantic schema on the final answer. result["structured_response"] is a fully typed Python object, not a string.
Pass the schema via response_format in create_agent()
Get reliable, ready-to-use JSON output from result["structured_response"]
Perfect for automation, APIs and frameworks
Exercises
Generate 5 test cases for a new user story from your own product.
Modify the schema: add preconditions and test_data fields.
Build a LocatorList schema (element description, recommended locator, alternative locators, confidence 0 to 100, strategy enum: id, data-testid, css, xpath, role, text) and generate locators for a login form.
Feed the generated steps straight into a pytest-playwright test and run it.
08
Final project: a Playwright agent that runs your test
Describe the test in plain English. The agent opens a real browser, navigates, fills, clicks, verifies, takes a screenshot and reports the result.
At a glance
Scripted Playwright test
You write every step and selector in code
Runs the same way every time
Best for regression suites in CI
VS
Playwright agent
You describe the task, the agent picks the tools and the order
Reasons about what it sees (flash messages, page text)
Best for exploratory checks, smoke runs and quick verifications
Everything from chapters 01 to 07 in one place: a system prompt with rules, Playwright tools that share one browser (seven shown here, 32 in the file), and the ReAct loop that calls them in the right order.
Extra setup for this project
terminal
pip install -U playwright langchain-deepseek
playwright install chromium # downloads the browser Playwright will drive
The example uses DeepSeek (DEEPSEEK_API in your .env) because it is reliable at multi-step tool use. 009_Playwright_Agent_Orch.py is the same agent on Groq, so you can compare the two. Screenshots are saved to a screenshots/ folder next to the script.
File 1: the Playwright tools
Seven small tools that share one browser and one page through module-level variables, exactly like the global browser and page in the TypeScript version. Every tool returns a short string, because that string is what the agent reads next.
src/chapters/playwright_tools.py (excerpt)
import os
from functools import wraps
from playwright.async_api import (
Browser, BrowserContext, Page,
TimeoutError as PlaywrightTimeoutError, async_playwright,
)
from langchain.tools import tool
# Shared browser state across tools (module-level, like globals in TypeScript)
_playwright = None
_browser: Browser | None = None
_context: BrowserContext | None = None
_page: Page | None = None
_console_errors: list[str] = [] # filled by listeners in launch_browser()
_failed_requests: list[str] = []
def _needs_page(fn):
"""Guard + error funnel, so 20 tools do not repeat the same 6 lines.
Catching broad Exception is deliberate: a tool that RAISES kills the agent
run, while a tool that RETURNS an error string lets the agent adapt.
"""
@wraps(fn)
async def wrapper(*args, **kwargs):
if _page is None:
return "Error: Browser not launched. Call launch_browser first."
try:
return await fn(*args, **kwargs)
except PlaywrightTimeoutError as exc:
return f"Timeout: {str(exc).splitlines()[0]}"
except Exception as exc:
return f"Error: {str(exc).splitlines()[0]}"
return wrapper
@tool
@_needs_page
async def snapshot_page(selector: str = "body") -> str:
"""Get the ARIA snapshot: every role, name and value on the page as a YAML tree.
Call this FIRST whenever you do not already know what is on the page. It is
the cheapest way to find out what you can click or type into, and the names
it returns are exactly what click_by_role and type_by_label expect.
"""
snap = await _page.locator(selector).aria_snapshot()
return snap[:6000] or "Snapshot is empty."
@tool
@_needs_page
async def click_by_role(role: str, name: str) -> str:
"""Click an element by ARIA role and visible name, e.g. role="button", name="Login".
Prefer this over a CSS selector: it survives markup changes, and the
role/name pairs come straight out of snapshot_page.
"""
await _page.get_by_role(role, name=name).first.click()
return f'Clicked {role} named "{name}"'
@tool
@_needs_page
async def assert_text_contains(selector: str, expected_text: str) -> str:
"""Check an element's text contains the expected substring. Returns PASS or FAIL."""
actual = ((await _page.locator(selector).first.text_content()) or "").strip()
ok = expected_text.lower() in actual.lower()
return (f"{'PASS' if ok else 'FAIL'}: expected {expected_text!r} "
f"{'found in' if ok else 'NOT found in'} {actual!r}")
@tool
@_needs_page
async def get_console_errors() -> str:
"""List JavaScript console errors since the browser launched.
A page can look perfect and still be broken. Check this before declaring a
scenario passed.
"""
if not _console_errors:
return "No console errors."
return f"{len(_console_errors)} console error(s):\n" + "\n".join(
f"- {e}" for e in _console_errors[-20:])
# ... 28 more tools: navigation, dropdowns, upload, drag, waits, viewport,
# mock_api_response, save_login_state. See src/chapters/playwright_tools.py.
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]
ASSERTION_TOOLS = [assert_visible, assert_text_contains, count_elements,
get_all_texts, get_attribute_value]
DIAGNOSTIC_TOOLS = [get_console_errors, get_failed_requests]
PLAYWRIGHT_TOOLS = (CORE_TOOLS + INTERACTION_TOOLS + ASSERTION_TOOLS
+ DIAGNOSTIC_TOOLS + ADVANCED_TOOLS) # 32 tools
File 2: the agent
The system prompt carries the rules (launch first, act in order, screenshot before closing, report at the end). The task is the test case, written the way you would write it for a colleague.
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.environ["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 "standard_user"
4. Enter the password "tta_secret"
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())
Output (a Chromium window opens and you watch the test run)
===== Steps taken =====
-> launch_browser({})
Browser launched successfully (visible mode).
-> navigate_to({'url': 'https://app.thetestingacademy.com/playwright/ttacart/'})
Navigated to https://app.thetestingacademy.com/playwright/ttacart/
-> type_text({'selector': '#user-name', 'text': 'standard_user'})
Typed "standard_user" into #user-name
-> type_text({'selector': '#password', 'text': 'tta_secret'})
Typed "tta_secret" into #password
-> click_element({'selector': '#login-button'})
Clicked on #login-button
-> get_text({'selector': '[data-test="title"]'})
Products
-> take_screenshot({'filename': 'login_test_result.png'})
Screenshot saved as screenshots/login_test_result.png
-> close_browser({})
Browser closed successfully.
===== Final Result =====
Test PASSED. I launched the browser, opened the TTACart login page, entered
standard_user and tta_secret, clicked Login and landed on the Products page,
which confirms a successful login. The final state is saved in
screenshots/login_test_result.png and the browser is closed.
How it works
shared state
All tools read the same _page. Launch creates it, close clears it, every other tool checks it exists before acting.
async everywhere
Playwright's async API, async def tools and agent.ainvoke(). Mixing the sync API with the agent's thread pool breaks, so keep it all async.
the loop
The agent calls a tool, reads the string it returns, decides the next call. The six steps in the task, plus a check and the screenshot the rules ask for, become eight tool calls and a report.
Where this fits in real testing: agents are great for exploratory checks, smoke runs and "does this flow still work?" questions. For your regression suite keep scripted tests: they are cheaper, faster and deterministic. The next step is to combine both, for example generate a test with the agent, then save it as a normal pytest-playwright test.
Key takeaways
Tools can drive anything, including a real browser
Return short, clear strings from tools: they are the agent's eyes
Rules in the system prompt (launch first, screenshot before close, report at the end) make multi-step runs reliable
Use the async Playwright API with agent.ainvoke()
Read the message history to see every step the agent took
Exercises
Change the task to a different flow, for example log in to TTACart (https://app.thetestingacademy.com/playwright/ttacart/), add the first product to the cart and verify the cart badge shows 1.
Add three tools: get_page_title, select_option(selector, value) and wait_for_text(selector, text).
Write a negative test: enter a wrong password and verify the error message. Make the agent report FAILED when the error message does not match.
Combine with chapter 07: pass response_format=TestReport (steps, status, screenshot_path) so the final report is structured JSON.
Run with headless=True and slow_mo=0 and compare the run time.
What actually broke when we ran this
Every code block on this page was executed, not just written. These are the failures that
cost real time, in the order you are most likely to hit them.
1. A Gemini key that starts with AQ. is not an API key
A real Gemini key starts with AIza. A value starting with AQ. is a
short-lived OAuth access token: it works for about an hour, then every call
fails with a message that never mentions expiry.
the error you get
GoogleAuthenticationError: 401 UNAUTHENTICATED.
Expected OAuth 2 access token, login cookie or other valid authentication credential.
'reason': 'ACCESS_TOKEN_TYPE_UNSUPPORTED'
Check before you debug anything else:
python -c "import os;print(os.getenv('GOOGLE_API_KEY','')[:4])" must print AIza.
2. The env var name the SDK looks for is not always the one in your .env
ChatDeepSeek auto-reads DEEPSEEK_API_KEY. If your file calls it
DEEPSEEK_API, the key is silently ignored and you get a 401 that says nothing about
variable names. Pass it explicitly, or rename the variable.
llm = ChatDeepSeek(
model="deepseek-chat",
api_key=os.environ["DEEPSEEK_API"], # not DEEPSEEK_API_KEY
temperature=0, # never sample a CSS selector
)
3. load_dotenv() has to run before os.getenv, not near it
This orders wrong and fails with a confusing error three frames inside LangChain, because
os.getenv returned None long before load_dotenv() ran:
the bug
llm = ChatGroq(model=os.getenv("LLM_MODEL")) # -> None, the .env is not loaded yet
load_dotenv() # too late
Prefer os.environ["LLM_MODEL"] over os.getenv(...) for
required values: a missing key then fails immediately with a KeyError naming the
variable, instead of passing None down the stack.
4. Gemini returns content blocks, not a string
Printing message.content on a Gemini reply gives you this, signature blob and all:
Use message.text instead. In langchain-core 1.x it is a property
that concatenates the text blocks and drops the rest. (In 0.3 it was a method,
message.text().) Do not hand-roll a block parser, the library already has one.
5. The same tools, two models, two very different agents
Files 009 (Groq) and 010 (DeepSeek) are the same agent, the same 32 tools and the same system prompt.
Only the model differs. The task said "1. Launch the browser" as its first step:
Model
What it did
openai/gpt-oss-120b (Groq)
Called navigate_tobeforelaunch_browser, got the error
string back, launched, snapshotted a blank page, then gave up after 3 steps.
deepseek-chat
Followed the order, then went further than asked: verified the post-login URL and
title, asserted text=Products was visible, screenshotted, closed cleanly.
PASSED.
That is the lesson of the whole chapter: tool-call discipline is a property of the
model, not of your prompt. It is also exactly why every tool returns an error
string instead of raising, which is what made Groq's misstep recoverable rather than fatal.
6. Do not eval() what a model wrote
The obvious one-line calculator tool is eval(expression). That is arbitrary code
execution driven by text a language model produced. 006_Tool.py walks the parsed
expression instead, so __import__('os').system(...) is rejected as
"only arithmetic is allowed" rather than executed.
What comes next
You can now build an agent, control it with a system prompt, run it in parallel, give it tools, get typed output back and drive a real browser. The next lessons build on exactly these pieces.
Memory
Add a checkpointer and a thread_id so the agent remembers the conversation across calls.
Multi-agent workflows
A router agent that hands off to specialised agents (test writer, reviewer, executor) and combines their results.
RAG over your test docs
Load requirement documents, split them, embed them, and let the agent answer from your own files.
MCP servers
Connect the agent to external tool servers (filesystem, APIs, Playwright MCP) instead of hand-writing every tool.
LangGraph
State, nodes and edges. Conditional routing (score ≥ 7 then finalize, else improve), cycles with a max-attempts guard, human-in-the-loop approval with interrupt(), and the ReAct loop.
LangSmith
Turn on the three tracing lines from your .env and inspect every LLM call, tool call and token your agents make.
TypeScript to Python reference
If you have seen the TypeScript version of these lessons, this is the whole translation.
TypeScript (langchain)
Python (langchain)
import "dotenv/config"
from dotenv import load_dotenv; load_dotenv()
import { createAgent, tool } from "langchain"
from langchain.agents import create_agent from langchain.tools import tool