AI Hints
Home›LangChain Tutorial›Project: Memory, Guardrails, Tests
LangChain · Lesson 105 of 120

Project: Testing

A small eval.

⏱ 2 min read▶ Video at 1:59:53🎓 Free
Watch this lesson in the LangChain courseWatch on YouTube ↗Full LangChain course

Before real customers use the bot, we test it. A small test set covers each feature. A policy question, a stock question, an order question, and an off topic request.

Project: Testing
From the video: Project: Testing
  • Test before launch
  • One test per feature
  • Graded by a judge

test_bot.py

We import ask from guarded dot p y, and grade from our judge file. Each test pairs a question with a reference answer. For the off topic request, the reference describes the behaviour we want, a polite refusal. Each question gets its own thread, so tests don't affect each other. Run it. Every feature passes, so the bot is ready for its first real customers.

test_bot.pypython
from guarded import ask
from judge import grade

tests = [("How long does standard delivery take?", "3 to 5 working days."),
         ("Is Circe in stock?", "No, it is out of stock."),
         ("What's the status of order RB-5678?", "It is being packed today."),
         ("Can you fix my car?", "A polite refusal: it only helps with the bookshop.")]
passed = 0
for q, ref in tests:
    ok = grade(q, ask(q, thread=q), ref)
    passed += ok
    print("PASS" if ok else "FAIL", q)
print(f"score: {passed}/{len(tests)}")
Output
PASS How long does standard delivery take?
PASS Is Circe in stock?
PASS What's the status of order RB-5678?
PASS Can you fix my car?
score: 4/4
Also uses kb/shipping.md
# Shipping
Standard delivery in the UK takes 3 to 5 working days and costs £2.99.
Delivery is free on orders over £25.
Express delivery arrives the next working day if you order before 2pm, and costs £5.99.
We ship to Ireland and France in 5 to 8 working days for £7.50.
Every order gets a tracking link by email once it leaves our warehouse.
Also uses kb/returns.md
# Returns and refunds
You can return any book within 30 days of delivery for a full refund.
Books must be unread and in the condition you received them.
Damaged or faulty books can be returned at any time, and we pay the return postage.
Refunds go back to the original payment method within 5 working days of us receiving the book.
To start a return, reply to your order confirmation email.
Also uses kb/gift_cards.md
# Gift cards
Riverside Books gift cards come in values from £10 to £100.
Gift cards never expire and can be used online or in our shop.
A gift card can be used across several orders until the balance is spent.
Gift cards cannot be exchanged for cash.
Also uses kb/loyalty.md
# Riverside Readers loyalty club
Joining the Riverside Readers club is free.
Members earn one point for every pound they spend.
100 points can be swapped for a £5 voucher.
Members get early access to signed editions and a birthday discount of 10 percent.
Also uses kb/shop.md
# About the shop
Riverside Books has one physical shop, at 12 Mill Lane, Bath.
The shop is open from 9am to 6pm Monday to Saturday, and 11am to 4pm on Sunday.
We sell new and second-hand books, and run a children's story time every Saturday at 10am.
You can contact us at hello@riverside-books.example or on 01225 000 000.
Also uses shop_kb.py
from pathlib import Path
from langchain_core.documents import Document
from langchain_core.vectorstores import InMemoryVectorStore
from langchain_google_genai import GoogleGenerativeAIEmbeddings
from langchain_text_splitters import RecursiveCharacterTextSplitter

def load_docs(folder="kb"):
    return [Document(p.read_text(), metadata={"source": p.name})
            for p in sorted(Path(folder).glob("*.md"))]

def build_store(folder="kb"):
    splitter = RecursiveCharacterTextSplitter(chunk_size=300, chunk_overlap=40)
    chunks = splitter.split_documents(load_docs(folder))
    embeddings = GoogleGenerativeAIEmbeddings(model="gemini-embedding-001")
    return InMemoryVectorStore.from_documents(chunks, embeddings)
Also uses shop_tools.py
from langchain.tools import tool

BOOKS = {
    "The Hobbit": {"stock": 7, "price": 8.99, "author": "J.R.R. Tolkien"},
    "Dune": {"stock": 3, "price": 9.99, "author": "Frank Herbert"},
    "Circe": {"stock": 0, "price": 10.99, "author": "Madeline Miller"},
}

@tool
def check_stock(title: str) -> int:
    """Copies of a book in stock at Riverside Books."""
    return BOOKS.get(title, {}).get("stock", 0)

@tool
def get_price(title: str) -> float:
    """Price of a book in pounds."""
    return BOOKS.get(title, {}).get("price", 0.0)

@tool
def get_author(title: str) -> str:
    """Author of a book."""
    return BOOKS.get(title, {}).get("author", "unknown")
Also uses kb.py
from pathlib import Path
from langchain.tools import tool
from langchain_core.vectorstores import InMemoryVectorStore
from langchain_google_genai import GoogleGenerativeAIEmbeddings
from shop_kb import build_store

PATH = "store.json"
embeddings = GoogleGenerativeAIEmbeddings(model="gemini-embedding-001")
if not Path(PATH).exists():
    build_store().dump(PATH)
store = InMemoryVectorStore.load(PATH, embeddings)

@tool
def search_policies(query: str) -> str:
    """Search shop policies: shipping, returns, gift cards, loyalty, opening hours."""
    return "\n\n".join(d.page_content for d in store.similarity_search(query, k=2))

if __name__ == "__main__":
    print(search_policies.invoke("How do I get a refund?"))
Also uses tools.py
from langchain.tools import tool
from shop_tools import check_stock

ORDERS = {"RB-1234": "shipped on Monday, arriving Thursday",
          "RB-5678": "being packed today"}

@tool
def order_status(order_id: str) -> str:
    """Status of an order. Order ids look like RB-1234."""
    status = ORDERS.get(order_id.strip().upper())
    return status or f"No order {order_id}. Ask the customer to check the number."

if __name__ == "__main__":
    for t in [check_stock, order_status]:
        print(f"{t.name}: {t.description}")
    print(order_status.invoke({"order_id": "rb-1234"}))
    print(order_status.invoke({"order_id": "RB-0000"}))
Also uses agent.py
from langchain.agents import create_agent
from langgraph.checkpoint.memory import InMemorySaver
from kb import search_policies
from tools import check_stock, order_status

SYSTEM = """You are the Riverside Books support assistant. Be brief and friendly.
Use search_policies for any policy question, and answer only from what it returns.
Use check_stock and order_status for stock and orders.
If something isn't covered, say so and offer to pass it to a member of staff."""
TOOLS = [search_policies, check_stock, order_status]

agent = create_agent("google_genai:gemini-flash-lite-latest", tools=TOOLS,
                     system_prompt=SYSTEM, checkpointer=InMemorySaver())

if __name__ == "__main__":
    q = "Is Dune in stock, and can I return it if I don't like it?"
    out = agent.invoke({"messages": [{"role": "user", "content": q}]},
                       config={"configurable": {"thread_id": "demo"}})
    print(out["messages"][-1].text)
Also uses guarded.py
from langchain.agents import create_agent
from langchain.agents.middleware import PIIMiddleware, ToolCallLimitMiddleware
from langgraph.checkpoint.memory import InMemorySaver
from agent import SYSTEM, TOOLS

bot = create_agent(
    "google_genai:gemini-flash-lite-latest", tools=TOOLS,
    system_prompt=SYSTEM + "\nOnly help with Riverside Books. Politely refuse anything else.",
    middleware=[PIIMiddleware("email", strategy="redact", apply_to_input=True),
                ToolCallLimitMiddleware(run_limit=5)],
    checkpointer=InMemorySaver())
def ask(text, thread="default"):
    out = bot.invoke({"messages": [{"role": "user", "content": text}]},
                     config={"configurable": {"thread_id": thread}})
    return out["messages"][-1].text.strip()

if __name__ == "__main__":
    for q in ["Write me a poem about cars.", "I'm sam@example.com. Is order RB-5678 ready?"]:
        print(q, "->", ask(q, thread=q))
Also uses judge.py
from pydantic import BaseModel, Field
from langchain.chat_models import init_chat_model

class Grade(BaseModel):
    correct: bool = Field(description="Does the answer agree with the reference?")
    reason: str = Field(description="One short sentence.")

judge = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0).with_structured_output(Grade)

def grade(question, answer, reference):
    g = judge.invoke(f"Question: {question}\nReference: {reference}\nAnswer: {answer}\nGrade the answer.")
    return g.correct

Keep testing

Run these tests after every change, to the prompt, the tools, or the model. When a customer finds a problem, add their question to the test set. And watch real conversations with tracing, to find new things to test.

keyvalue
After every changerun the tests
New bugnew test
Tracingwatch real chats
Growthe test set

Summary

A small test set, graded by a judge, proves each feature works. Run it after every change. Next, a review of everything we built.

Key takeaways
  • One test per feature
  • Judge with references
  • Run after changes
Next up: Project: Review — what we built