The Testing Academy · Class Notes Saturday, 28 November (IST)
Live class · study guide

LangChain: four providers, streaming, tools and memory

Chapter 17 begins: LangChain against CrewAI, LangGraph and LangSmith, one chat-model interface for Groq, DeepSeek, a local Ollama model and Gemini, invoke against stream, four calls at once with asyncio, and an agent with tools and memory. Files 01 to 09 of chapter 17.

By Pramod Dutta, The Testing Academy. Study notes from the AI Tester Blueprint 4x class, built from the session recording, the batch repository's two chapter 17 commits, pushed during the class with README sections that the page credits where it uses them, and the batch's Eraser notes deck, whose section for this class holds the LangChain notes and the setup commands. The class ran its files on Groq, DeepSeek, Ollama and Gemini. These notes called no provider: the pushed files ran in a rebuilt copy of the chapter's own environment (Python 3.14.10, langchain 1.5.2, langgraph 1.2.24), with no network and no key, against gemma3:270m, the class's own local model, through each file's own settings; 02 and 06 needed one line changed to name it. That model cannot call tools, so the tool and memory checks of 07 and 08 ran against a local stand-in that answers by fixed rules and calls no model, and the two tools of 09 read copies of their two pages, fetched once. The outputs shown are from those runs.

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

What this class covered

  • Three ways to build an agent, and CrewAI against LangChain
  • LangChain, LangGraph and LangSmith: bricks, workflows and traces
  • Chapter 17 with uv: a fresh virtual environment, the packages and the .env
  • Groq through ChatGroq: the first invoke
  • DeepSeek, and a key the file never loads
  • A local model with Ollama: gemma3:270m and content_blocks
  • Gemini through create_agent, and No module named langchain
  • Invoke against stream
  • Four calls at once with asyncio
  • Tools and memory: @tool, InMemorySaver, thread_id and BMT
  • Two tools that reach the web: search and fetch
  • What comes next: the capstone pipeline, shown as a preview
  • Tasks and announcements: LangChain with MCP tomorrow, then DeepEval and LangGraph
  • LangChain puts every provider behind one interface: ChatGroq, ChatDeepSeek, ChatOllama or a create_agent model string, and the same .invoke() gives back an AIMessage.
  • Each provider reads its own key from the environment: GROQ_API_KEY, DEEPSEEK_API_KEY, GOOGLE_API_KEY. A file that never calls load_dotenv() never sees the .env, which is why the class exported the DeepSeek key.
  • create_agent needs the provider in the model string, as in google_genai:gemini-2.5-flash; without the prefix, LangChain looks for Vertex AI's package instead.
  • invoke() hands back the whole answer at once; stream(..., stream_mode="messages") hands it over piece by piece as it is generated.
  • asyncio.gather sends every ainvoke() at once and returns the answers in the order of the questions; the time saved depends on the server working on them together.
  • An agent is brain, memory, tool: @tool makes a function a tool whose docstring is what the model reads, and InMemorySaver with the same thread_id carries the conversation. With the saver and no thread_id, the run stops.
  • uv run uses the project's environment, not the folder's activated .venv: add packages with uv add.
02

Three ways to build an agent

THREE WAYS TO BUILD AN AI AGENT 1. VIBE CODING Claude Code, Copilot you give instructions and it builds it all; you do not understand the architecture 2. LOW-CODE, NO-CODE n8n, LangFlow much better: you understand how the flow goes; easy, for POCs 3. A PYTHON FRAMEWORK CrewAI, LangChain or LangGraph: more control, for production-ready AI agents THE DECK: AGENT = MODEL + SYSTEM PROMPT + TOOLS + A LOOP MESSAGES the question and the system prompt THE MODEL decides answer, or call a tool THE ANSWER the task is done the loop stops TOOLS a calculation, an API, a page, test cases in a fixed format calls its result The model reads the messages, decides whether to answer or call a tool, and repeats until the task is done.
The three ways as the class went through them; the loop below is the deck's own formula and sentence.

Last class built a bug triage crew with CrewAI. This class starts chapter 17, AI agents with LangChain, in Python.

There are only three ways to create an AI agent, the instructor said. The first is vibe coding: you give instructions to Claude Code or GitHub Copilot, it creates everything from scratch and does not tell you which framework it used; the problem is solved, but you do not understand the core architecture. The second, much better, is a low-code, no-code tool such as n8n or LangFlow, because you understand how the flow goes. The third is a framework: CrewAI, LangChain or LangGraph. LangChain, the instructor said, is the most popular production-ready Python framework for creating LLM agents from scratch.

LangChain is a framework for building applications powered by large language models, as the deck's note for this class puts it: it gives you the building blocks, models, prompts, tools, memory and retrieval, and a single create_agent() function that wires them into an agent. A LangChain agent is LLM-powered, which means it can take decisions, the instructor said: it has a brain, and it can use tools, memory, prompts and models. Give it tools and it can also act, the deck goes on: run a calculation, call an API, fetch a page, generate test cases in a fixed format. In the deck's one line, an agent is a model, a system prompt, tools and a loop: the model reads the messages, decides whether to answer or call a tool, and repeats until the task is done.

Question. What is the difference between CrewAI and LangChain?

Show the answer

Answer. n8n and LangFlow are very easy to use, the instructor answered, good for POCs and for solving problems in your QA environment; production AI agents need more control, and to control the flow you need Python. CrewAI is for when you want a quick solution: multiple agents talking to each other, a simple sequence to follow, if X happens do Y, if Y happens do Z. LangChain helps when you have too many tools to work with, and a memory; it can run steps sequentially or in parallel, and it works with the Lang family, LangSmith, LangGraph and LangFuse. Both are very mature, and which one you use depends on your usage and your company; the instructor uses LangChain. For a very simple setup with multiple agents, CrewAI is good; LangChain, the instructor considers a little advanced, and a little more useful. Lang has an ecosystem whose tools work with each other, so you do not have to go to other tools; CrewAI does not have the full ecosystem as of now, but it is very good for simple steps. The deck's note for this class lists the same split: CrewAI for quick solutions, agents that talk to each other and a sequence; LangChain for tools, memory, sequential and parallel runs, and the Lang family.

The goal, the instructor said, is building AI agents for test automation in plain Python, the line the deck's note also writes.

03

LangChain, LangGraph and LangSmith

Two panels on cream paper, each with the same plain wooden board. Left, titled LangChain, with the sublabel The bricks: a neat stack of loose bricks of three shapes, blush and terracotta, with three more lying beside it. Right, titled LangGraph, with the sublabel Bricks into workflows: the same bricks laid end to end as one path that splits into two branches, one curving back on itself in a small loop, the branches meeting again at a small hinged gate near the right end, a terracotta tick above the gate.
LangChain is like building with bricks; LangGraph connects the bricks into workflows, with branching, loops and approvals, as the instructor put it.

A lot of people are confused, the instructor said: what is LangChain, what is LangGraph, what is LangSmith, and now there is LangWatch too. The simplest way to tell them apart: LangChain is like building a home with bricks; LangGraph connects the bricks into workflows, where you can have states, branching, loops and approvals; LangSmith is only for traces, testing and monitoring, for the traceability, observability and evaluation of your AI agents. LangWatch.ai is one more tool, to watch your AI agents and their tools, an observability and evals platform; the deck's note says the same.

LangGraph, you can say, is the big brother of LangChain, the instructor said. LangChain is a sequential or parallel flow, a first step, a second, a third; in LangGraph you can have a graph, with multiple decisions, branches and approvals. LangGraph is much more mature, or production-ready, than LangChain, and the most difficult to understand as a beginner, its code too: the big daddy. So LangChain comes first, and LangGraph after it. LangGraph, also known as the big daddy, basically has LangChain agents plus traceability and observability, the instructor said; the deck's note writes that line as LangGraph, the big daddy, with LangChain agents, plus LangSmith for traceability and observability.

The instructor then read out the three side by side:

LangChain LangGraph LangSmith
What it is a framework for building applications powered by LLMs: the building blocks a framework for LLM-powered applications, built on LangChain, for stateful, cyclic and deterministic workflows a developer platform for observability and evaluation
Mostly used for a quick AI agent: chatbots, RAG agents, QA agents, QA document agents end-to-end projects and production-ready agents: multi-step AI workflows, multiple agents, human in the loop, long-running stateful applications tracing, debugging, evaluations and experiments, monitoring, datasets and collaboration
04

Chapter 17 with uv

Two panels on cream paper. Left, titled One room, with the sublabel They fight: one room with two empty toy boxes against the wall and all their toys in one heap on the floor, blocks, a ball and two toy trains tied nose to nose by a taut string, straining apart. Right, titled Different rooms, with the sublabel Own toys: the same floor divided into two rooms by a wall with a door standing ajar, each room with its own toy box, the blocks and the ball tidy in one, the two trains parked in the other, a terracotta tick above the wall.
Different folders can have different virtual environments, so that they do not fight with each other: like separate rooms, each with its own toys, as the instructor put it.

Go to the chapter 17 folder, deactivate the old virtual environment and create a fresh one in this folder, the instructor said, with Python 3.14, which the instructor called more stable than the latest. The deck's five commands for it:

Terminal
uv venv --python 3.14
source .venv/bin/activate
uv pip install -U langchain langchain-google-genai langchain-groq langchain-deepseek python-dotenv requests.
uv pip install -U playwright
uv run playwright install chromium

Question. Why are we using a virtual environment?

Show the answer

Answer. A virtual environment is nothing but this, the instructor answered: in a different folder, you can have a different Python version. Different folders can have different virtual environments, so that they do not interact, or fight, with each other: as when you have one room and your brother or sister another, each with your own toys. It is specific to Python, the instructor said: Python allows you to have different versions this way.

The packages: LangChain, the Google, Groq and DeepSeek packages, python-dotenv, and requests, which is for making API requests, the instructor said; Playwright and Chromium too, for later, which is more than enough. Install them with uv rather than pip, because uv is very, very fast compared to pip; and the easiest way to turn a pip command into a uv one is to ask ChatGPT to convert it, and keep it at medium, not high.

Copied from the deck as it stands, the third command stops at its last word. Run here as a dry run:

Terminal
uv pip install -U langchain langchain-google-genai langchain-groq langchain-deepseek python-dotenv requests.
Output
error: Failed to parse: `requests.`
  cause: Package name must end with an alphanumeric character, not `.`
         requests.
                 ^

Drop the full stop after requests. It ends the deck's bullet, and uv reads it as part of the package name. Without it, the same dry run resolves 57 packages here, langchain 1.5.2 and langgraph 1.2.24 among them.

Then a .env file, the instructor said, with the Gemini or Google API key, the model, the Groq API key, and the DeepSeek API key if you want it. Why Gemini? Just an example, if somebody wants to use it: the model does not matter. The repo's sample, chapter 17's .env.example, names every setting the files read; the README notes that the real .env is gitignored:

.env.exampleTerminal
# Sample environment file. Copy to .env and fill in your own values.
#   cp .env.example .env
# Real .env files are gitignored and must never be committed.

# 01_Hello_LC.py: Groq through ChatGroq
GROQ_API_KEY=gsk_your_groq_api_key_here
LLM_MODEL=openai/gpt-oss-120b

# 02_DeepSeek_LC.py: ChatDeepSeek reads DEEPSEEK_API_KEY from the environment
DEEPSEEK_API_KEY=sk-your_deepseek_api_key_here

# 03_Ollama_LC.py: no key needed, runs against a local Ollama
#   ollama pull gemma3:270m

# 04_Geminy_LC.py and 05_Gemini_Steam_LC.py: create_agent needs the provider prefix
GOOGLE_API_KEY=your_google_ai_studio_api_key_here
GEMINI_LLM_MODEL=google_genai:gemini-2.5-flash

Make sure you use a Groq API key, the instructor said: Groq is cheap for us, and more than enough. A Gemini key comes from AI Studio, the instructor said: the site the deck links as aistudio.google.com.

Question. Is the Claude API provided in the enterprise edition too?

Show the answer

Answer. The Claude API is not provided even in the enterprise edition, or ultra, or any plan, the instructor answered: you need to buy it separately, and the OpenAI API too. The request: always use Groq if possible.

A learner added that this means a Playwright MCP project with LangChain: you are absolutely right, the instructor said, because we will be doing it in the future too.

05

Groq through ChatGroq

ONE INTERFACE, FOUR PROVIDERS GROQ ChatGroq(...) 01: LLM_MODEL, GROQ_API_KEY DEEPSEEK ChatDeepSeek(...) 02: DEEPSEEK_API_KEY, exported OLLAMA, A LOCAL MODEL ChatOllama(...) 03: gemma3:270m, no key GEMINI create_agent(...) 04, 05: google_genai:gemini-2.5-flash THE MESSAGES a question, or (system, human) pairs THE REPLY AIMessage .content, .text, .content_blocks invoke() with messages in, an AIMessage out: a new provider is a new class, or a new prefix in the model string.
The class's files 01 to 05 by the class each one uses and the settings it reads, from the files and .env.example; the last line is the README's point. Every one of them was run here, with a local model standing in.

The first file is 01, Hello LC: LC is LangChain. It imports load_dotenv from dotenv, ChatGroq, the class to use, from langchain_groq, and os, for operating system functions:

01_Hello_LC.pyPython
from dotenv import load_dotenv
from langchain_groq import ChatGroq
import os

load_dotenv()

def main():
    llm = ChatGroq(model=os.getenv('LLM_MODEL'), temperature=1)
    query = input("Enter a question related to qa")
    response = llm.invoke(query)
    print(response)

if __name__ == "__main__":
    main()

Line 8 builds the LLM: ChatGroq with the model from the .env, LLM_MODEL, and a temperature of 1. Line 9 takes the question, line 10 makes the API request with llm.invoke(query), and line 11 prints the response. Lines 13 and 14 make sure main() runs when you run the file, very similar to Java, the instructor said. In class, the question was explain the smoke testing in three lines, and the answer came back in a proper way: smoke testing is a quick, high-level verification process, and so on.

ChatGroq is a class created by LangChain that takes the model and reads the key by itself, from the Groq API key, the instructor said: you do not have to mention anything at all. Run here with LLM_MODEL set and no key, line 8 stops on the groq client's own message, which names GROQ_API_KEY:

Text
groq.GroqError: The api_key client option must be set either by passing api_key to the client or by setting the GROQ_API_KEY environment variable

The class ran 01 on Groq, in the folder's own venv. These notes ran the pushed file unchanged, in a rebuilt copy of that venv (Python 3.14.10, langchain 1.5.2), against gemma3:270m, the class's own local model, served by Ollama on the same machine. LLM_MODEL names it, and GROQ_API_BASE, langchain-groq's own setting, points the Groq client at a small bridge on 127.0.0.1 that hands the request to Ollama; the key is a placeholder word. The class's question, typed at the prompt:

Terminal
python 01_Hello_LC.py
Output
Enter a question related to qaexplain the smoke testing in three lines
content="Smoke testing is a process of analyzing the physical characteristics and composition of smoke to determine its properties, which can be used for various applications. It involves identifying components like VOCs (volatile organic compounds), particulate matter, and other gases that contribute to the smoke's volatile nature.\n" additional_kwargs={} response_metadata={'token_usage': {'completion_tokens': 57, 'prompt_tokens': 16, 'total_tokens': 73, 'completion_time': None, 'completion_tokens_details': None, 'prompt_time': None, 'prompt_tokens_details': None, 'queue_time': None, 'total_time': None}, 'model_name': 'gemma3:270m', 'system_fingerprint': 'fp_ollama', 'service_tier': 'on_demand', 'finish_reason': 'stop', 'logprobs': None, 'model_provider': 'groq'} id='lc_run--01a225ea-e411-7653-ab98-9bec0a036bed-0' tool_calls=[] invalid_tool_calls=[] usage_metadata={'input_tokens': 16, 'output_tokens': 57, 'total_tokens': 73}

Line 11 prints the whole AIMessage: the answer is its content, followed by the metadata, the token usage and the model's name.

Read the stand-in's answers as plumbing. gemma3:270m has 268 million parameters, a tiny brain, and here it describes smoke testing as the analysis of smoke. The code worked; the answer is wrong. The class's runs used Groq, DeepSeek and Gemini models, and the class's answer about smoke testing was the right one.

Question. Is temperature mandatory?

Show the answer

Answer. Temperature is optional, the instructor answered. 01 sets it to 1 on line 8; 03 sets it to 0, which means no creativity, the instructor said later.

Question. We can deploy this on Vercel also, right?

Show the answer

Answer. No, not Vercel, the instructor answered: this is a command-line AI agent, a headless agent with no UI as of now, and it runs through the command line.

06

DeepSeek, and a key the file never loads

How do I run it through DeepSeek? Things are almost the same, the instructor said. The class first wrote it with create_agent and a DeepSeek model name, then looked up LangChain's own page for DeepSeek, which the deck links, ChatDeepSeek, and found the class already there: whenever you are confused, research, because there are already libraries you can use directly; never start from scratch. The pushed file is the ChatDeepSeek version:

02_DeepSeek_LC.pyPython
from langchain_deepseek import ChatDeepSeek

llm = ChatDeepSeek(
    model="deepseek-chat",
    temperature=0,
    max_tokens=None,
    timeout=None,
    max_retries=2,
)

messages = [
    ("system", "You are a helpful coding assistant."),
    ("human", "Write a Python function to reverse a string."),
]

response = llm.invoke(messages)
print(response.content)

The model, deepseek-chat, is on line 4, and the messages, a system line and a human line, on lines 11 to 14. The first run stopped, the instructor said: the DeepSeek API key was not found. It does not read the key from the environment file, so the key had to be exported before running the program; then the reply came, a Python program to reverse a string. The pushed file, run here with no key:

Terminal
python 02_DeepSeek_LC.py
Output
pydantic_core._pydantic_core.ValidationError: 1 validation error for ChatDeepSeek
  Value error, If using default api base, DEEPSEEK_API_KEY must be set. [type=value_error, input_value={'model': 'deepseek-chat'...v1', 'model_kwargs': {}}, input_type=dict]
    For further information visit https://errors.pydantic.dev/2.14/v/value_error

Why the .env was not read. 02 never imports dotenv or calls load_dotenv(), unlike 01 and 04 to 09, so nothing copies the .env into the environment, and ChatDeepSeek reads DEEPSEEK_API_KEY from the environment only, as .env.example's comment for 02 says. Lines 1 to 9 of the file, run here four ways with a placeholder key and no request sent, show it.

Where the key is Lines 1 to 9
nowhere stop at line 3: DEEPSEEK_API_KEY must be set
only in a .env file beside the file, as pushed stop at line 3: the same error
in that .env, with load_dotenv() called first build the client: ChatDeepSeek deepseek-chat key set: True
exported in the shell, as in class build the client: ChatDeepSeek deepseek-chat key set: True

So exporting the key, as the class did, is one fix, and a load_dotenv() call before line 3 is the other.

LangChain's docs list ready classes for many providers; the deck links the page for all the providers. The instructor went through some of them: OpenAI; Anthropic, for Claude; Google, NVIDIA, Hugging Face, Microsoft and Ollama. OpenRouter is there, and Gemini; Command Code, the instructor did not think so, and it was not there.

These notes ran 02 with one line changed, line 4 naming the stand-in, and DEEPSEEK_API_BASE, the client's own setting, pointing at Ollama on the same machine, with a placeholder key exported, as the class exported its key:

Python
    model="gemma3:270m",
Terminal
python 02_DeepSeek_LC.py
Output
```python
def reverse_string(input_string):
    """Reverses a given string.

    Args:
        input_string: The string to be reversed.

    Returns:
        The string with the original characters reversed.
    """
    return input_string[::-1]  # Use slicing to reverse the string
```

**Explanation:**

1. **`def reverse_string(input_string):`**: This defines a function named `reverse_string` that takes one argument: the string `input_string`.

2. **`"""Reverses a given string."""`**:  This is a docstring, providing a brief description of what the function does. It's good practice to include docstrings for clarity and maintainability.

3. **`return input_string[::-1]`:** This line uses slicing to reverse the string.
    - `[::-1]` creates a reversed copy of the string.
    - `[::-1]` is a slicing operation that takes a slice (a sequence of characters) and reverses it in place.  The `[::-1]` part means "take the last `i` characters, then reverse them".

**Example:**

```python
string = "Hello World"
reversed_string = reverse_string(string)
print(reversed_string)  # Output: dlroW olleH
```

In this example, the function `reverse_string` is called with the string "Hello World". The reversed string is "dlroW olleH".
07

A local model with Ollama

Somebody wants a local model? ChatOllama is already there, the instructor said. To install its package, I think it will be uv add, the instructor said; and make sure Ollama is running. The first model to pull was GPT OSS, 20 billion parameters, which turned out to be 13 GB: it would take time. So Gemma 3 instead, the smallest one, the instructor said; the file and .env.example's comment name it gemma3:270m.

Question. For the Ollama model, we don't need a key, right?

Show the answer

Answer. Yes, you are right, the instructor answered: we do not need that. .env.example says the same for 03: no key needed, it runs against a local Ollama.

03_Ollama_LC.pyPython
from langchain_ollama import ChatOllama

llm = ChatOllama(
    model="gemma3:270m",
    temperature=0,
)

messages = [
    (
        "system",
        "You are a helpful assistant ",
    ),
    ("human", "program to reverse string in python"),
]
ai_msg = llm.invoke(messages)
print(ai_msg.content_blocks)

Temperature 0 on line 5 means no creativity, the instructor said. In class, the first run printed nothing at all: there was no print command. Then the first prompt, a helpful assistant that translates English to French, with I love programming, did not come back in French. Content blocks are what we need, the instructor found: ai_msg.content_blocks, on line 16. With the prompt changed to a helpful assistant and a program to reverse a string in Python, it worked: it is not pretty, it is a JSON reply, the instructor said.

03 is the one file these notes ran exactly as the class did: the same file, on the same local model.

Terminal
python 03_Ollama_LC.py
Output
[{'type': 'text', 'text': '```python\ndef reverse_string(input_string):\n    """\n    Reverses the given string.\n\n    Args:\n        input_string: The string to be reversed.\n\n    Returns:\n        The reversed string.\n    """\n    return input_string[::-1]\n\n# Example usage:\nstring = "Hello, world!"\nreversed_string = reverse_string(string)\nprint("Reversed:", reversed_string)\n```\n\n**Explanation:**\n\n1. **`reverse_string(input_string)` function:**\n   - Takes a string `input_string` as input.\n   - Uses slicing to reverse the string: `[::-1]`.  This creates a reversed copy of the string, using a step of -1 (which means reversing the order of the characters).\n\n2. **Example Usage:**\n   - We create a sample string "Hello, world!" and call the function with it.\n   - We print the reversed string to the console.\n\n**How it works:**\n\nThe `[::-1]` slicing operation creates a reversed copy of the string.  By using a step of -1, we effectively reverse the order of the characters in the string.  This is a common and efficient way to reverse strings in Python.\n'}]

content_blocks is a list of blocks, each a dictionary with its type and its text; here one text block holds the whole reply.

Question. For writing the code for CrewAI or LangChain, do we need to learn this coding, creating agents this way?

Show the answer

Answer. You need to understand what you are doing, the instructor answered: when you have understood the concept, everything will be smooth. The important thing is that you understand the flow, because right now people mostly write the code with AI agents; through practice, you get it.

08

Gemini through create_agent

Gemini next, the instructor said: the system is the same, and the only thing we want is the Gemini model. create_agent, the Gemini model, and it will fetch the Gemini API key by itself:

04_Geminy_LC.pyPython
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()

Line 9 hands create_agent a model string from the .env, GEMINI_LLM_MODEL; .env.example sets it to google_genai:gemini-2.5-flash, with the comment that create_agent needs the provider prefix. Line 11 invokes the agent with a list of messages, and line 12 prints the last message's text. The prefix picks the class, and the class reads its key. Three model strings, run here with no key:

Model string LangChain builds What happens
google_genai:gemini-2.5-flash, from .env.example ChatGoogleGenerativeAI stops: API key required, set GOOGLE_API_KEY or GEMINI_API_KEY
gemini-2.5-flash, no prefix ChatVertexAI stops: install langchain-google-vertexai
ollama:gemma3:270m, the stand-in ChatOllama answers, below

So the key it fetches by itself is GOOGLE_API_KEY, or GEMINI_API_KEY, the two names in the error. Without the prefix, a Gemini name goes to Vertex AI, another package; the README's own gotcha says the same, that the model string needs the provider prefix.

In class, the Gemini file first stopped with no module named LangChain. The help on screen said to install LangChain and the Google Gemini package, and reinstall; then the boundary value question was answered: what is boundary value testing, in five lines. The README gives the error and the fix: ModuleNotFoundError: No module named 'langchain' means the package isn't installed, and uv add langchain fixes it.

Why it was missing. The deck's uv pip install put LangChain in the chapter folder's own .venv. But inside a uv project, uv run runs the project's environment, at the repo root, and ignores the activated .venv; the project had no LangChain until uv add put it there. Re-created below with the project as it was before the class, and the folder's venv, holding LangChain, activated.

Terminal
uv run python 04_Geminy_LC.py
Output
warning: `VIRTUAL_ENV=.venv` does not match the project environment path `.venv` and will be ignored; use `--active` to target the active environment instead
Traceback (most recent call last):
  File "chapter_17_AI_Agent_LangChain/04_Geminy_LC.py", line 4, in <module>
    from langchain.agents import create_agent
ModuleNotFoundError: No module named 'langchain'

The first .venv in uv's warning is the folder's, the second the project's, at the repo root. In the same shell, the folder's python is Python 3.14.10, and uv run python is Python 3.13.14.

These notes ran 04 unchanged, with GEMINI_LLM_MODEL set to ollama:gemma3:270m, so create_agent builds a ChatOllama for the stand-in; the class's question, typed at the prompt:

Terminal
python 04_Geminy_LC.py
Output
Ask your question: what is boundary value testing in five lines
Boundary value analysis (BVA) is a statistical technique used to evaluate the risk of investment portfolios. By analyzing the values at the boundaries of a distribution, we can identify potential vulnerabilities and adjust parameters to reduce downside risks.

The code worked again, and the tiny model's answer is wrong again: it is about investments, not testing.

09

Invoke against stream

We got the reply in one go, the instructor said; if you want it in a stream, create the agent, ask the question, and use agent.stream instead of agent.invoke. Explain LLM eval in a thousand words: the answer is very big, and with a stream it keeps giving you the answer as it comes. The first try still came in one go, because the wrong one was running, as the instructor put it: we have to run five. With file 05 it streamed, first one part, then another, then another.

05_Gemini_Steam_LC.pyPython
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 1000 words blog"},
            ]
        },
        stream_mode="messages",
    ):
        print(token.text, end="", flush=True)
    print()


if __name__ == "__main__":
    main()

Line 10, the question's input(), is commented out: the query was not being used, the instructor noticed in class, and the prompt is fixed on line 16. stream_mode="messages" on line 19 makes stream() hand over the reply as it is generated, one piece and its metadata at a time, and line 21 prints each piece at once, with no newline. 04 prints once, at the end; the README calls this streaming tokens as they arrive.

Run here unchanged, with GEMINI_LLM_MODEL naming the stand-in, and every write to the screen logged:

Terminal
python 05_Gemini_Steam_LC.py
Output
Streaming Response:
## LLM Eval: A Comprehensive Guide for Software Testers

In the ever-evolving landscape of software development, performance and reliability are paramount. Developers need to ensure their applications can handle demanding workloads efficiently, adapting to changing requirements and maintaining a consistent user experience. This is where LLM Evaluation (LLeV) comes into play.

LLM Evaluation is a powerful technique that leverages Large Language Models (LLMs) to analyze code and identify potential issues before they impact the application's functionality. It goes beyond simple static analysis by employing techniques like semantic understanding, code similarity analysis, and automated testing to uncover hidden bugs, vulnerabilities, and performance bottlenecks.

The answer runs to 77 lines and 1,246 words. It reached the screen in 1,603 writes of about 6 characters each, over 6.1 seconds, the first one 0.2 s after the Streaming Response line. The first six pieces: ## LL M Eval : A. Here each piece is a token or so; how big a piece is depends on the provider.

Question. So my understanding is: create a virtual environment, install LangChain, create a Python file, and write some code with the chat model?

Show the answer

Answer. Yes, you are absolutely right, the instructor answered.

10

Four calls at once with asyncio

After the break: you can run agents sequentially or in parallel, the instructor said, with asyncio, async input and output, a module used for asynchronous, parallel work. 06 loads the environment and creates one agent, from Gemini Flash, the instructor said, with a system prompt; the pushed file then puts four questions to it: LLM eval, smoke, sanity and regression testing.

06_Agent_Parallel_Vs_Sequential.pyPython
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())

async def on line 23 makes main() a function that supports parallelism, the instructor said; time.perf_counter() on line 25 notes the start, and asyncio.gather on line 28 invokes all the questions, with await wherever you use it. You do not have to remember this code, the instructor said: it is just an example, to show that parallel execution is supported. In class it executed all of them and gave the replies: four calls, as the class's run showed.

The pushed file has no sequential version: its name says parallel versus sequential, and the README's diagram draws both. The README's point is that four sequential calls cost the sum of four latencies, and four concurrent calls roughly the slowest one.

Run here with line 8 naming the stand-in:

Python
    model="ollama:gemma3:270m",
Terminal
python 06_Agent_Parallel_Vs_Sequential.py
Output
Creating LangChain agent...

0. LLM Eval
Alright, let's dive into the world of LLM Evaluation! It's a crucial process for ensuring the quality and reliability of AI models used in various applications. Here's a breakdown of key concepts:

*   **LLM Evaluation:** This encompasses a comprehensive approach to assessing the performance, accuracy, and fairness of an LLM (Large Language Model). It involves analyzing metrics like accuracy, precision, recall, F1-score, BLEU score, and other relevant benchmarks.

*   **Metrics:** The evaluation process relies heavily on quantifiable measures that capture specific aspects of the model's behavior and performance. These metrics can be categorized into several key areas:

The four answers fill 123 lines, and the run ends:

Text

----------------------------------------------------------------------
Finished 4 calls in 9.7s

From the guard's log, when each request left the program and when its answer closed, in seconds from the start:

Request Question Sent Answer closed Order closed
1 LLM Eval 1.31 s 6.20 s 2
2 Smoke Testing 1.36 s 8.66 s 3
3 Sanity Testing 1.36 s 11.05 s 4
4 Regression Testing 1.36 s 3.97 s 1

All four left within 0.05 s of each other: that is asyncio.gather. The stand-in then answered one at a time, each answer starting only as the one before it closed, so the total, 9.7 s, is the sum of the four, not the slowest one: the time saved depends on the server working on all four at once. The answers still print in the order of the questions, as line 33's comment says, though the answer on Regression Testing closed first.

But the real magic comes when you add a tool, the instructor said: without a tool, this is a useless agent.

11

Tools and memory

BMT: BRAIN, MEMORY, TOOL the n8n AI agent node 07_LLM_LC_Tool.py CHAT MODEL Groq BRAIN LINE 21 ChatGroq(...) model="openai/gpt-oss-120b" MEMORY Simple Memory MEMORY LINES 22 AND 26 InMemorySaver() thread_id: "demo" TOOL Calculator TOOL LINES 10 TO 18, 23 @tool add, sub plain functions as tools AI agent is brain, memory, tool: the same three parts in the n8n node and in create_agent().
The comparison the class made on screen, with the file's own line numbers. In the n8n node the class showed, the brain was Groq, the memory simple memory and the tool a calculator.

Question. This seems like basic question and answer. How can we make an agent that understands and achieves a goal, and plans on behalf of a user?

Show the answer

Answer. Only when it has tools, the instructor answered: when it has access to tools, then only it can do that. Adding tools is what the class did next.

How do we add a tool? Using MCP? No, simple, the instructor said: as in CrewAI, create a function and mark it as a tool, and the rest is the same. This is the brain, this is the tool, and an AI agent has a memory too: InMemorySaver, a class from langgraph.checkpoint.memory; we are borrowing LangGraph's memory, the instructor said.

07_LLM_LC_Tool.pyPython
from dotenv import load_dotenv
from langchain.agents import create_agent
from langchain.tools import tool
from langchain_groq import ChatGroq
from langgraph.checkpoint.memory import InMemorySaver


load_dotenv()

@tool
def add(a: int, b: int) -> int:
    """Add two numbers."""
    return a + b

@tool
def sub(a: int, b: int) -> int:
    """Add two numbers."""
    return a - b

agent = create_agent(
    model=ChatGroq(model="openai/gpt-oss-120b", temperature=0),
    checkpointer=InMemorySaver(),
    tools=[add,sub]
)
# The same thread_id keeps conversation memory while the program runs.
config = {"configurable": {"thread_id": "demo"}}

for question in [
    "My name is Pramod. Use the add tool for 5 - 3.",
    "What is my name and what was the result?",
]:result = agent.invoke(
        {"messages": [{"role": "user", "content": question}]},
        config,
    )


print(result["messages"][-1].content)

Two consecutive questions, the instructor said: the first gives a name and asks for a sum with the tool, and the second asks for the name and the result. The LLM uses the tool and gets eight, and it remembers the name because of the in-memory saver. The configuration, the thread ID on line 26, keeps the conversation in memory while the program runs: with the same thread ID it remembers, and if you do not use the configuration, the AI agent will not remember. The class's run answered with the name, and eight.

Then a second tool, subtraction: if somebody mentions subtraction, it will use subtraction, the instructor said, and the answer, two, came. The pushed file holds both tools, and its first question asks the add tool for 5 - 3, on purpose, the README says: watch which tool the model picks. Line 37 sits outside the loop, so only the second answer is printed.

How many tools can we add, the instructor asked the class, and answered: unlimited. There is no limitation, and you can have hundreds of tools. The repo's 08 adds a third, multiply.

In n8n we have the same feature, the instructor said, and showed it: an AI agent with a chat model, Groq; a simple memory; and a calculator as its tool. Brain, memory, tool: BMT. An AI agent is brain, memory, tool. The deck has written the same formula since the batch's early sections: AI Agent, Brain + Memory + Tools.

On the class's own local model. The class ran 07 on Groq. On gemma3:270m it cannot run at all: Ollama refuses any request that offers tools to this model. With line 21 naming it, through the same Groq client, the traceback's first lines:

Python
    model=ChatGroq(model="gemma3:270m", temperature=0),
Output
Traceback (most recent call last):
  File "chapter_17_AI_Agent_LangChain/07_LLM_LC_Tool.py", line 31, in <module>
    ]:result = agent.invoke(
               ~~~~~~~~~~~~^
            {"messages": [{"role": "user", "content": question}]},
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
            config,
            ^^^^^^^
        )

Then 102 lines of LangGraph, LangChain and groq frames, and the last two:

Text
groq.BadRequestError: Error code: 400 - {'error': {'message': 'registry.ollama.ai/library/gemma3:270m does not support tools', 'type': 'invalid_request_error', 'param': None, 'code': None}}
During task with name 'model' and id 'fdd576ef-71d8-3f37-c1ff-78a89eb5b43f'

A scripted stand-in. So these notes checked 07 against bridge.py, a stand-in on 127.0.0.1 that calls no model and answers by three fixed rules. A tool's result gets back stand-in: the tool returned and the result. A request that offers tools and asks for 5 - 3 gets a tool call, sub(a=5, b=3), the call the README's diagram of this file shows. Anything else gets a line saying how many messages the request carried, and what the first one reads. The file runs unchanged, with GROQ_API_BASE pointing the Groq client at the stand-in. The replies are fixed text; what each request carries is the file's own doing.

The first request offers the model both tools, and their descriptions are the docstrings, as the README says: the docstring becomes the description the model reads.

JSON
[
  {
    "type": "function",
    "function": {
      "name": "add",
      "description": "Add two numbers.",
      "parameters": {
        "properties": {
          "a": {
            "type": "integer"
          },
          "b": {
            "type": "integer"
          }
        },
        "required": [
          "a",
          "b"
        ],
        "type": "object"
      }
    }
  },
  {
    "type": "function",
    "function": {
      "name": "sub",
      "description": "Add two numbers.",
      "parameters": {
        "properties": {
          "a": {
            "type": "integer"
          },
          "b": {
            "type": "integer"
          }
        },
        "required": [
          "a",
          "b"
        ],
        "type": "object"
      }
    }
  }
]

sub's docstring is add's. Line 17 gives sub the description Add two numbers., so the model reads two tools that say the same and has only their names to tell them apart. The README's own Q&A warns about it: a copy-pasted docstring misleads the model, so write each one for the model. In 08, mul says it too.

08_LLM_LC_Tool_Multiple.pyPython
@tool
def mul(a: int, b: int) -> int:
    """Add two numbers."""
    return a * b
Tool Its description, as 08's first request sends it
add Add two numbers.
sub Add two numbers.
mul Add two numbers.

Now memory, from both sides: four runs of 07, three of them with one line changed, and what the request for the second question carried, from the guard's copy of each request:

Run Line changed Requests The second question's request carried 07 printed
as pushed: the saver, and the thread_id demo none 3 5 messages: the first question, the tool call, its result, the answer, then the second question carried 5 message(s)
a new thread_id for each question 33 3 1 message: the second question alone carried 1 message(s)
checkpointer=None, the same thread_id 22 3 1 message: the second question alone carried 1 message(s)
config = {}: the saver, no thread_id 26 0 none: it stops before the first request ValueError, below

So the memory is the saver and the thread ID together: with a new thread ID, or no saver, the second question goes out alone, and no model could answer it with the name. Without a thread ID, the agent does not quietly forget: with the saver in place, it stops before the first request.

Text
ValueError: Checkpointer requires one or more of the following 'configurable' keys: thread_id, checkpoint_ns, checkpoint_id

The README adds that InMemorySaver lives in process memory, keyed by thread_id: a new thread_id or a new run starts with a blank history.

12

Two tools that reach the web

Let me show you another example, the instructor said: this one we will not create now; we will create it tomorrow. A real example, with two tools:

09_Multiple_Tool.pyPython
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?",   
    "Search for the TheTestingAcademy", # needs web_content_tool                             # 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}")

The search tool goes to DuckDuckGo's HTML page and returns the title of the results page; the web content tool goes to the URL, strips the tags and returns the first 1,000 characters. create_agent gets both, on line 38, and the agent decides which one to use, the instructor said: it has a brain. Based on the question, it uses the search tool or the get content tool, by itself. In class, What is Playwright? came back as an open source framework; then the search for the official website, and the content of Playwright's intro page. Can we add more, the instructor asked, and proposed a search for The Testing Academy too: it will search for it. The pushed file has that query on line 47, and line 47's comments do not fit it, since it is a search and the comment says it needs web_content_tool.

What do the tools return? Called here directly, with no model, on copies of the two pages fetched once with curl and served by the guard, so nothing left the machine:

Tool Called with It returns
search_tool TheTestingAcademy DuckDuckGo
search_tool Appium official website DuckDuckGo
web_content_tool Playwright's intro page 1,000 characters, below

DuckDuckGo answered the one request made from here with a check for automated traffic, HTTP 202, titled DuckDuckGo, so that one word is what search_tool hands the model, whatever the query. Even on a results page, the tool returns the page's title, never the results. The fetch, the intro page's first 1,000 characters with its tags stripped:

Text
Installation | Playwright{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","item":"https://playwright.dev/docs/intro","name":"Installation","position":1}]}


!function(){var t=function(){try{return new URLSearchParams(window.location.search).get("docusaurus-theme")}catch(t){}}()||function(){try{return window.localStorage.getItem("theme-e2a")}catch(t){}}();document.documentElement.setAttribute("data-theme",t||(window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light")),document.documentElement.setAttribute("data-theme-choice",t||"system")}(),function(){try{for(var[t,e]of new URLSearchParams(window.location.search).entries())if(t.startsWith("docusaurus-data-")){var a=t.replace("docusaurus-data-","data-");document.documentElement.setAttribute(a,e)}}catch(t){}}()Skip to main contentPlaywrightDocsMCPCLIAPINode.jsNode.jsPythonJava.NETSearchGetting StartedInstallationWriting testsGenerating testsRunning and debugging testsTrace vie

The title, a block of structured data and the page's theme script fill them, before any of the page's own text.

Check what a tool returned before you credit it. With these returns, an answer naming Appium's official website, or saying what Playwright is, comes from what the model already knows, not from the tools. An agent calling a tool is no proof that it used what the tool gave back.

Question. We can give any website for this, right?

Show the answer

Answer. Yes, yes, the instructor answered: you are right.

Question. Can we extend this tool calling for a file, a separate class?

Show the answer

Answer. There are hundreds of tools we can have, the instructor answered; tools can also use MCP, and LangChain can connect with MCPs too, to be shown in the next lecture, tomorrow.

13

What comes next: the capstone pipeline

Two panels on cream paper, each with the same wooden desk top. Left, titled Junior QA, with the sublabel Does every step: a row of five objects joined in order by a thin terracotta line, a ticket card, a plan sheet, a test card, a small laptop whose screen shows a play triangle, and a report sheet. Right, titled Human review, with the sublabel Still needed: the same report sheet alone under a large magnifying glass, a wooden rubber stamp beside it and a small terracotta tick above.
A LangChain agent can be a junior QA, the instructor said, from the Jira ticket to the result; somebody still has to do the human review.

A LangChain agent can be a junior QA, the instructor said at the start of the class: it can find the latest Jira ticket, read it, create a test plan and test cases, write a Playwright test case, execute it and give you the result, without you doing anything at all; even fix it if there is a problem, and give the result to your QA manager or QA lead. That is scary for a lot of people, the instructor said, but somebody has to do the human review, somebody has to write these LangChain scripts, and somebody has to orchestrate it all.

The ultimate goal is an end-to-end QA pipeline with Playwright execution: a Jira ticket, a test plan, test cases, Playwright tests written and run through Playwright MCP, and the result. That is the capstone project, to be done with LangChain, the instructor said. At the end of the class, the instructor showed it: given one of the class's own tickets, VWO-49 as the repo names it, it fetches the ticket, prepares a test plan, executes the code and reports, and all of these are tools. First of all it will plan, then it will report, and it will execute, the instructor said. That comes in an upcoming session.

It can be deployed on a machine, AWS, DigitalOcean, GCP, or your own Linux or Windows machine, and run 24x7, the instructor said. It is an independent entity: the moment your Playwright tests have run in Jenkins, the agent can attach to that, for bug triaging, flaky test RCA, QA reporting and more. It will not replace automation; it will attach to the automation. Coming soon too: a lighter version of a QA Copilot, where a supervisor agent decides whether a bug needs triaging, an RCA, test design or missing test cases.

Question. How will it take the XPath, or the element, automatically?

Show the answer

Answer. By using Playwright MCP or something, the instructor answered: it will figure it out from there, automatically.

The next class continues chapter 17.

14

Tasks and announcements

  • Tomorrow: LangChain with MCP, and the web tools built. LangChain can connect with MCPs, the instructor said, to be shown tomorrow; the multiple-tools example will be created tomorrow too, the instructor said, and in the repo it is 09_Multiple_Tool.py.
  • The capstone pipeline comes in an upcoming session: a Jira ticket in; a plan, a Playwright run and a report out.
  • The code and the notes. I am pushing the code right now, the instructor said, and the notes: you will see the notes soon. The code is in chapter 17 of the batch repository, in two commits pushed during the class.
  • Three topics left. LangChain, then DeepEval, then LangGraph: for the next two or three weeks, the instructor asked for 100 percent focus.
  • Rate limits in CrewAI. For a learner hitting rate limits with CrewAI, the instructor's suggestion was a top-up on DeepSeek's platform.
  • Next class: tomorrow, Sunday 29 November.

Question. In my current project they use Azure Boards. Can I use Azure Boards too?

Show the answer

Answer. You can, if you want to, the instructor answered: you just have to write a function to fetch a ticket from Azure Boards. The Jira version of such a function, fetch_jira_ticket(), is on the last class's page.

Question. We create agents in CrewAI, and it has guardrails. What about LangChain?

Show the answer

Answer. Do not worry about it, the instructor answered: guardrails can be added in LangChain too, into your prompts, or for security purposes. I will show you, the instructor said.