AI Hints
Home›LangGraph Tutorial›RAG Patterns
LangGraph · Lesson 87 of 120

Rewriting Questions

Try again.

⏱ 2 min read▶ Video at 1:34:03🎓 Free
Watch this lesson in the LangGraph courseWatch on YouTube ↗Full LangGraph course

Customers write vague questions, like, what's the deal with points? Search may find nothing useful. Rewriting the question, more clearly, often fixes that. Then we search again.

Rewriting Questions
From the video: Rewriting Questions
  • Vague questions
  • Weak search results
  • Rewrite and retry

A clearer question

The rewrite node asks the model for a clearer, more specific version of the question, and counts the attempt. We grade the search results before and after rewriting. Run it. The rewritten question is far clearer. Here both versions found the loyalty policy, but on bigger document sets, clearer questions make a real difference.

rewrite.pypython
from crag_parts import retrieve, grade, rewrite

state = {"question": "whats the deal w/ points lol", "attempts": 0}
before = grade(state | retrieve(state))["docs"]

state |= rewrite(state)
print("rewritten:", state["question"])
after = grade(state | retrieve(state))["docs"]
print(f"relevant docs: before={len(before)}, after={len(after)}")
Output
rewritten: How do I earn and redeem loyalty points?
relevant docs: before=1, after=1
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 crag_parts.py
from typing import TypedDict
from pydantic import BaseModel
from langchain.chat_models import init_chat_model
from shop_kb import build_store

store = build_store()
model = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0)

class RAG(TypedDict):
    question: str
    docs: list[str]
    attempts: int
    answer: str

class Grade(BaseModel):
    relevant: bool
grader = model.with_structured_output(Grade)

def retrieve(s):
    return {"docs": [d.page_content for d in store.similarity_search(s["question"], k=3)]}

def grade(s):
    ask = "Question: {q}\nDocument: {d}\nDoes the document help answer the question?"
    return {"docs": [d for d in s["docs"] if grader.invoke(ask.format(q=s["question"], d=d)).relevant]}

def rewrite(s):
    q = model.invoke("Rewrite this bookshop customer question so it is clear and specific. "
                     f"Reply with the question only: {s['question']}").text.strip()
    return {"question": q, "attempts": s.get("attempts", 0) + 1}

def generate(s):
    if not s["docs"]:
        return {"answer": "Sorry, I couldn't find that in our policies."}
    context = "\n".join(s["docs"])
    return {"answer": model.invoke(f"Context:\n{context}\n\nAnswer in one sentence: {s['question']}").text.strip()}

Rewriting well

Ask the rewriter to keep the meaning, and only make it clearer. Always count attempts, because some questions can't be answered from your documents, however they're phrased. One or two rewrites is usually enough.

keyvalue
Keepthe meaning
Clearerspecific words
Countattempts
Limitone or two

Summary

A rewrite node turns vague questions into clear ones, so search finds better documents. Count attempts, and stop after one or two. Next, putting it all together.

Key takeaways
  • Rewrite the question
  • Search again
  • Count attempts
Next up: Corrective RAG — the full graph