Advanced LLM Practices Using RAG and LangChain
local graph
Chapter 10 — Advanced LLM Practices Using RAG and LangChain
Section titled “Chapter 10 — Advanced LLM Practices Using RAG and LangChain”After working through architectures and evaluation, we arrive at a common moment in applied natural language processing (NLP). We understand the ideas, but we still feel the friction when we try to turn them into something real. A prototype may answer one prompt well, but will then break when the question changes. A strong model produces great results, but the cost is hard to justify at scale. A local model keeps data private, but quality varies across tasks. This chapter is the turning point where we take what we already know and shape it into systems that behave well under real constraints.
We build around one practical principle: our retrieval layer stays stable, and our LLM becomes a swappable inference backend behind it. Sometimes our best choice is a local, free model because privacy and cost control dominate. Other times, we want a remote, paid model because we need stronger reasoning, longer context, or stricter compliance with output formats. Rather than treating that as a one-time decision, we make it a policy we can justify, measure, and revise without refactoring the pipeline.
From there, we design two levels of decision-making. First, we make application-level choices based on data residency, user experience expectations, cost and scale, licensing constraints, and the maturity of our infrastructure. Then, we move to real-time routing at the request level, using lightweight signals such as prompt complexity, domain hints, retrieval confidence, resource snapshots, and budget or latency goals. The outcome is a transparent operating stance. We default to a cost-efficient model, and we escalate only when the evidence is thin, the request is high-stakes, or the task requires deeper reasoning.
From there, we shift into full end-to-end systems built on retrieval-augmented generation (RAG). We design and implement an in-house healthcare chatbot that answers recall-driven clinical questions by retrieving relevant notes, composing grounded prompts, and selecting the appropriate inference backend in real time. Finally, we demonstrate how little needs to change to generalize this solution to an entirely different domain. By swapping the corpus and adjusting domain instructions, we apply the same RAG and routing blueprint to legal contracts, reinforcing the central message of the chapter.
This is what to expect from this chapter:
- Enhancing LLM performance
- Reviewing an LLM routing pipeline
- Case study 1: LangChain in healthcare
- Case study 2: LangChain design for an in-house chatbot in legal
Technical requirements
Section titled “Technical requirements”For this chapter, familiarity with Python programming is a must since the open source models, OpenAI’s API, and LangChain are all illustrated using Python code. You will also need the following:
- Open source models: Local free LLMs will be used as well. Ollama will be leveraged for that through the LLMPop Python library. It will require a Linux-based operating system, preferably with a GPU. For that, free access to Google Colab would be ideal. LLMPop can be installed via the common
pipcommand. More details can be found on the formal page: https://pypi.org/project/llmpop. - Local development environment: A local development environment setup with Python installed is required. An integrated development environment (IDE) such as PyCharm, Jupyter Notebook, or a simple text editor can be used. Note that we recommend a free Google Colab notebook, as it encapsulates all these requirements in a seamless web interface.
- Ability to install libraries: You must have permission for the installation of the required Python libraries, such as NumPy, pandas, sentence-transformers, openai, and LLMPop. Note that the code we provide includes the required installations, so you won’t have to install them ahead of time. We simply stress that you should have permission to do so, which we expect you would. Specifically, using a free Google Colab notebook would suffice.
- Hardware requirements: Depending on the complexity and size of the models you’re working with, a computer with sufficient processing power (potentially including a good GPU for ML tasks) and ample memory will be required.
You can download the example project and code for this book by following the instructions in the Download the example code files section in the Preface of this book. This chapter’s code files are included in the downloadable code bundle.
We will now get into advanced methods and techniques when building solutions with LLMs.
Enhancing LLM performance: choosing between local, free and remote, paid LLMs
Section titled “Enhancing LLM performance: choosing between local, free and remote, paid LLMs”Let’s consider the LLM itself to be a swappable inference backend behind that retrieval layer. In software engineering terms, this follows the dependency inversion principle: higher-level application logic depends on an abstraction, not on a specific model provider or deployment choice. Sometimes we want a free, local model, favorable for privacy and cost control. Other times, a remote, paid model may be optimal, which may enhance quality, latency, and tooling. We’ll also introduce LLMPop, a Python library that assists us by providing a unified command for invoking LLMs, local or remote, while the rest of the pipeline remains unchanged.
The next two subsections give us a practical decision flow. First, at the application level, what we choose to deploy for a given product or environment. Then, per request, how to route calls dynamically at runtime. In this chapter, we start with explicit, rule-based routing for clarity and transparency. More advanced approaches, such as semantic routing, where a lightweight model classifies intent or task complexity before selecting the target LLM, naturally build on the same abstraction and are discussed later as an evolutionary next step.
Application-level model selection
Section titled “Application-level model selection”When we are choosing the default LLM stack for a product, we start with the constraints of the application rather than abstract model scores:
- Security and data residency: If our RAG corpus contains regulated or high-sensitivity material such as PII, PHI, or trading IP, we may prefer a local model path (e.g., Ollama on an air-gapped server or developer laptop), so retrieved chunks never leave our boundary. Remote APIs may still be viable, assuming that the compliance professionals approve the relevant provider terms, data retention policies, and regional hosting.
- User experience expectations: Enterprise copilots and public-facing assistants often warrant a remote, paid model because frontier models deliver more consistent reasoning, better tool use, and longer contexts, which are key for multi-hop answers and complex prompts. Internal back-office tools, batch jobs, or prototyping flows can often run well on local models, currently ranging from 7B to 13B parameters, with acceptable quality.
- Cost and scale: If we expect spiky or high traffic and strict SLOs, remote providers give us elasticity and detailed per-token spend. If usage is steady and we control the hardware, local models provide near-zero marginal cost after setup, which is attractive for heavy retrieval workloads.
- Platform and licensing: Verify open-model licenses for commercial use and redistribution. Verify API terms for caching, data use, and safety requirements. Deployment targets, such as desktop versus server versus edge, may further nudge us toward a particular option.
- Technical maturity: If you already operate hardware that can support local LLMs, those could be a fast win. If you want to move quickly with minimal infrastructure setups, start remote and add local later for specific tenants or workflows.
It is interesting to keep in mind that there is another option. Many applications benefit from hybrid routing: run most traffic on a local “good-enough” model for optimal cost/privacy, and escalate specific requests to a stronger paid model when the task is hard, such as a weak retrieval signal, multi-step reasoning, long context, or user-marked “high stakes.” This free web app lets you experiment simultaneously with free LLMs and paid LLMs and evaluate them against each other: https://github.com/LiorGazit/llmpop/blob/main/notebooks/multi_llm_webapp.ipynb.
Request-level model routing
Section titled “Request-level model routing”Once we have made an application-level decision about our default deployment, we still face a second, finer-grained problem: not every request has the same requirements. Even within a single product, some questions are trivial and well-supported by retrieved context, while others are ambiguous, high-stakes, or require deeper reasoning. Request-level model routing addresses this by deciding, at runtime, which model should handle a specific task or user message. For each task, and sometimes each user message, we route based on a small set of practical signals:
- Capability and reliability: Frontier remote models tend to be best at multi-hop reasoning, long context, tool use, and following instructions. Local models have improved rapidly (quantized 7B–13B, some 70B on strong hardware), but may lag on nuanced reasoning. In practice, routers often treat context length as a first-class signal, estimating prompt “pressure” by tracking the combined token count of instructions, retrieved documents, conversation history, and the user query, and escalating when this total length approaches the effective context window of the local model.
- Privacy and data gravity: If our retrieved snippets contain sensitive IP or PHI, local inference avoids sending prompts off-box. With remote APIs, we must validate provider data policies and opt-outs.
- Latency and throughput: Local models are predictable once warmed up, but depend on our hardware; remote models offer great latency under typical load, with occasional rate limits.
- Cost and predictability: Local models are $0 per token at runtime (you pay in setup + hardware) but may incur electrical cost; remote is usage-based with transparent per-token costs and good observability.
- Licensing and deployment: Open-model licenses must be reviewed for commercial redistribution, while API terms govern data usage, caching, and safety obligations.
A pragmatic production stance is policy-driven routing. Here, we default to a cost-efficient capable model, and escalate to a stronger paid model when either of the following applies:
- Retrieval returns low-confidence evidence
- The user asks for high-stakes outputs
- The task requires a long context or complex tool orchestration
Now, let’s review a real-world practical example.
Reviewing an LLM routing pipeline
Section titled “Reviewing an LLM routing pipeline”To make these routing ideas concrete, we now walk through a practical implementation of an LLM routing pipeline. Using a simple rule-based approach, this example shows how model selection can be performed dynamically at runtime while keeping the rest of the RAG stack unchanged. We’ll guide you step by step, explaining what each part of the implementation does and why.
You can follow along with the full implementation by referring to the accompanying GitHub repository, specifically, the Ch10_LLM_routing.ipynb notebook, which mirrors the steps discussed here.
Setting up the environment and installing dependencies
Section titled “Setting up the environment and installing dependencies”We start by installing the minimal dependencies: langchain_core, psutil, pandas, and llmpop. If you plan to run remote models with OpenAI in this demo, ensure that you have an API key available:
%pip -q install llmpop%pip -q install langchain_core psutil pandasallow_paid_models = Trueif allow_paid_models: os.environ[“OPENAI_API_KEY”] = getpass(“Paste your OpenAI API key: “)These steps ensure that your environment has the necessary libraries and that remote API keys are loaded securely when needed.
Defining a catalog of candidate models
Section titled “Defining a catalog of candidate models”Next, we define a small in-memory catalog of models, both local (via Ollama) and remote (via OpenAI) LLMs. Each entry includes metadata such as a size rank, tags (general, code, math, and reasoning), and estimated cost/latency values for illustrative scoring:
@dataclassclass ModelSpec: name: str provider: str # ‘ollama’ or ‘openai’ size_rank: int # lower = smaller & faster tags: List[str] est_cost_per_1k: float # USD per 1k tokens (for cost heuristic) est_latency: float # baseline latency (seconds) notes: str = “”def build_catalog(allow_paid_models: bool = True) -> List[ModelSpec]: catalog = [ ModelSpec(name=”llama3.2:1b”, provider=”ollama”, size_rank=2, tags=[“general”], est_cost_per_1k=0.0, est_latency=0.3, notes=”Local, lightweight general model”), ModelSpec(name=”codellama”, provider=”ollama”, size_rank=2, tags=[“code”], est_cost_per_1k=0.0, est_latency=0.35, notes=”Local, code-oriented”), ModelSpec(name=”gpt-oss:20b”, provider=”ollama”, size_rank=3, tags=[“general”, “code”, “math”, “complex”], est_cost_per_1k=0.0, est_latency=0.5, notes=”Local, medium-size general model”), ] if allow_paid_models: catalog += [ ModelSpec(name=”gpt-5-mini-2025-08-07”, provider=”openai”, size_rank=1, tags=[“general”, “fast”], est_cost_per_1k=0.002, est_latency=0.08, notes=”Remote, budget/latency friendly”), ModelSpec(name=”gpt-5.2-2025-12-11”, provider=”openai”, size_rank=4, tags=[“reasoning”, “math”, “complex”], est_cost_per_1k=5.0, est_latency=0.014, notes=”Remote, strong reasoning”) ] return catalogThis catalog provides a shortlist of viable models with traits that the router will consider when selecting a backend.
Implementing lightweight heuristics for prompt analysis
Section titled “Implementing lightweight heuristics for prompt analysis”To guide routing decisions, we implement simple heuristics. One checks whether a prompt is complex (e.g., contains code or math markers or is lengthy), and another identifies domain hints such as SQL, finance, or biology. This information helps bias model selection toward specialized models when appropriate:
def is_complex_prompt(text: str) -> bool: if len(text) > 300: return True code_markers = [“\`\`\`”, “def “, “class “, “SELECT “, “FROM “, “import “, “public static void”] math_markers = [r”\bprove\b”, r”\bderive\b”, r”\bO\(“, r”\bintegral\b”, r”[0-9]+\s*[+\-*^/]\s*[0-9]+”] reasoning_terms = [r”\bchain of thought\b”, r”\bstep-by-step\b”] return any(m in text for m in code_markers) or \ any(re.search(p, text, re.IGNORECASE) for p in math_markers + reasoning_terms)def detect_specialization(text: str) -> Optional[str]: pairs = { “code”: [r”\bwrite (a|the) (python|js|sql|java|c\+\+|c#)”], “sql”: [r”\bSELECT\b.*\bFROM\b”, r”\bCREATE TABLE\b”], “finance”: [r”\bDCF\b”, r”\bWACC\b”, r”\b10-K\b”], “biology”: [r”\bRNA\b”, r”\bCRISPR\b”], “law”: [r”\bstatute\b”, r”\btort\b”], “math”: [r”\bprove\b”, r”\bintegral\b”, r”\bderivative\b”], } for tag, patterns in pairs.items(): if any( re.search( p, text, re.IGNORECASE | re.DOTALL) for p in patterns): return tag return NoneThese heuristics are intentionally basic but effective enough to steer routing decisions in the absence of a trained classifier.
Capturing a resource snapshot for local awareness
Section titled “Capturing a resource snapshot for local awareness”Since local models share hardware resources, we capture the current CPU and available RAM. High CPU usage or low memory may cause the router to prefer a remote model, even if the prompt would normally run locally:
def snapshot_resources() -> Dict[str, Any]: try: cpu = psutil.cpu_percent(interval=0.2) mem = psutil.virtual_memory() avail_gb = round(mem.available / (1024**3), 2) return {“cpu_percent”: cpu, “available_gb”: avail_gb} except Exception: return {“cpu_percent”: None, “available_gb”: None}This resource snapshot helps avoid running heavy local models when the machine is already under load.
Scoring candidate models according to routing goals
Section titled “Scoring candidate models according to routing goals”We combine the optimization target (speed, cost, or depth), prompt complexity, specialization, and resource snapshot to compute a numeric score for each model. Lower scores are better:
def score_candidate( spec: ModelSpec, *, optimization: str, complex_prompt: bool, specialization: Optional[str], resources: Dict[str, Any]) -> float: score = 0.0 # Base heuristics: each optimization target weights cost and latency differently if optimization == “speed”: score += spec.est_latency * 2.0 + spec.size_rank * 0.5 elif optimization == “cost”: score += spec.est_cost_per_1k * 1.5 + spec.size_rank * 0.3 elif optimization == “depth”: score += (0 if ( “reasoning” in spec.tags or “complex” in spec.tags) else 1.5) score += spec.size_rank * 0.2 else: score += spec.est_latency + 0.2 * spec.est_cost_per_1k # Complexity penalty/bonus: favor reasoningtagged models for complex prompts if complex_prompt and not any( t in spec.tags for t in [“reasoning”, “complex”, “math”, “code”] ): score += 1.0 # Specialization: small bonus if tags match detected specialization if specialization: if specialization in spec.tags or f”specialized:{specialization}” in spec.tags: score -= 0.5 else: score += 0.3 # Resource-aware penalties: avoid large locals on busy or low-memory machines if resources.get(“cpu_percent”) and resources[“cpu_percent”] > 70 and spec.provider == “ollama”: score += 0.8 if resources.get(“available_gb”) and resources[“available_gb”] < 2.0 and spec.provider == “ollama” and spec.size_rank >= 3: score += 0.7 return scoreThe cost-based weighting used here implicitly reflects a prior cost-benefit study, translating per token pricing and model size into a simple cost proxy. This allows the router to approximate relative cost efficiency without computing an explicit dollar total per request.
Initializing and calling models via a unified interface
Section titled “Initializing and calling models via a unified interface”We wrap the model initialization:
def init_model(spec: ModelSpec): if spec.provider == “ollama”: return init_llm( model=spec.name, provider=”ollama”, provider_kwargs={“auto_install”: True, “auto_serve”: True, “pull”: True}, temperature=0.0, ) elif spec.provider == “openai”: return init_llm( model=spec.name, provider=”openai”, temperature=0.0, ) else: raise ValueError(f”Unknown provider: {spec.provider}”)def call_model( chat_model, user_prompt: str, system_msg: str = “You are a helpful assistant.”): from langchain_core.messages import SystemMessage, HumanMessage result = chat_model.invoke( [ SystemMessage(content=system_msg), HumanMessage(content=user_prompt) ]) return getattr(result, “content”, str(result))This unified interface makes it easy to switch between local and remote models, while the rest of the pipeline stays unchanged.
Routing and dispatching the request
Section titled “Routing and dispatching the request”The core router puts everything together. It builds the catalog, analyzes the prompt, samples resources, scores candidates, and initializes the top-ranked model. If initialization fails, it falls back to the next candidate:
def route_and_dispatch( prompt: str, *, conversation_ctx: Optional[List[Dict[str, Any]]] = None, optimization: str = “speed”, runtime_info: Optional[Dict[str, Any]] = None, allow_paid_models: bool = True) -> Dict[str, Any]: catalog = build_catalog(allow_paid_models) complex_prompt = is_complex_prompt(prompt) specialization = detect_specialization(prompt) resources = snapshot_resources() # Apply penalties if API quotas are low (for illustration) quotas = (runtime_info or {}).get(“api_quotas”, {}) openai_quota_low = quotas.get(“openai_remaining”, 1000) < 50 ollama_quota_low = quotas.get(“ollama_remaining”, 1000) < 10 scored = [] for spec in catalog: s = score_candidate(spec, optimization=optimization, complex_prompt=complex_prompt, specialization=specialization, resources=resources) if spec.provider == “openai” and openai_quota_low: s += 1.0 if spec.provider == “ollama” and ollama_quota_low: s += 0.5 scored.append((s, spec)) scored.sort(key=lambda x: x[0]) chosen = scored[0][1] # Initialize and call; if fails, fallback to next candidate error = None response = None try: chat_model = init_model(chosen) response = call_model(chat_model, prompt) except Exception as e: error = f”{type(e).__name__}: {e}” if len(scored) > 1: alt = scored[1][1] chat_model = init_model(alt) response = call_model(chat_model, prompt) chosen = alt return { “chosen_model”: chosen.name, “provider”: chosen.provider, “notes”: chosen.notes, “complex_prompt”: complex_prompt, “specialization”: specialization, “optimization”: optimization, “resources”: resources, “error”: error, “response”: response, }This function encapsulates the routing logic, returning both the answer and metadata about why the model was selected.
Running the router on a sample prompt
Section titled “Running the router on a sample prompt”Finally, we wrap the router in a main() function to demonstrate its use. You can test different prompts and optimization targets (speed, cost, or depth) to see how the router responds. You can also disable paid models entirely (allow_paid_models=False) to enforce local-only operation:
def main(prompt: str, conversation_ctx: Optional[List[Dict[str, Any]]] = None, optimization: str = “speed”, runtime_info: Optional[Dict[str, Any]] = None, allow_paid_models: bool = True): result = route_and_dispatch( prompt=prompt, conversation_ctx=conversation_ctx, optimization=optimization, runtime_info=runtime_info, allow_paid_models=allow_paid_models ) print(“\n=== Router Decision ===”) print(f”Chosen: {result[‘chosen_model’]} (provider={result[‘provider’]})”) print(f”Notes: {result[‘notes’]}”) print(f”Complex prompt? {result[‘complex_prompt’]}; specialization: {result[‘specialization’]}”) print(f”Optimization: {result[‘optimization’]}”) print(f”Resources snapshot: {result[‘resources’]}”) if result[“error”]: print(f”Init error (first try): {result[‘error’]}”) print(“\n=== Model Output (truncated) ===”) print(str(result[“response”])[:1200])# Example: run the router for a coding taskprompt = “Write a short Python function that returns the nth Fibonacci number, then analyze the time complexity.”main(prompt, optimization=”speed”, runtime_info={“api_quotas”: {“openai_remaining”: 500, “ollama_remaining”: 9999}})Understanding the trade-offs we make and their consequences
Section titled “Understanding the trade-offs we make and their consequences”Given an identical retrieved context, differences in outcomes typically surface with coverage, precision, and exposition:
- Local: Concise, grounded, sometimes misses a subtle link or hedges more, often perfectly usable for triage, especially when the context is clear and short
- Remote: Richer justification, better cross-referencing between snippets, higher compliance with output format constraints
In business settings, discuss these trade-offs explicitly with the stakeholders:
- Quality vs. cost: Remote models’ answers cost money and export data; local models’ answers are free and private, but may need more follow-up
- Latency vs. control: Local latencies are hardware-bound but predictable; remote is fast on average with external rate limits and quotas
- Privacy vs. capability: If context includes sensitive material, err on local unless you have strong contractual/legal support
Hardcoding a single backend wastes money (over-paying for easy questions) or hurts quality (under-serving hard questions). We apply a policy-driven routing:
- Defaults to a capable local model
- Escalates to a stronger remote model when any of the following hold:
- Low retrieval confidence (e.g., cosine or inner-product similarity below some threshold, thin context, or high disagreement between top-k)
- High-stakes intent (detected via rules or a small classifier, e.g., “surgery scheduling,” “legal exposure,” or “dosage changes”)
- Task complexity (long questions, multi-step reasoning cues, required tool use, or long context windows)
- Low retrieval confidence (e.g., cosine or inner-product similarity below some threshold, thin context, or high disagreement between top-k)
- De-escalates back to local when the question becomes routine
With the mechanics of the router in place, we now step back and look at its behavior. Rather than walking through code again, let’s focus on how the same routing logic responds under different optimization goals and constraints, and what trade-offs those choices imply in practice.
In our Ch10_LLM_routing.ipynb notebook, we have a lightweight router that chooses the inference backend per request rather than hardcoding a single model for the entire application. The goal is pragmatic: keep the RAG pipeline identical (same retriever, same prompt template, same formatting), and vary only the LLM backend (local for privacy/cost and remote for frontier reasoning) when the request characteristics suggest it.
Let’s observe how the code performs in different scenarios based on its routing policy. We run the notebook, ideally in Google Colab, and observe the following scenarios that are driven by different trade-offs.
- Demo entrypoint and a first run: We run the router on a concrete prompt – a code task asking for a Fibonacci function plus complexity analysis – and print the decision summary. We see whether the router chose a local or remote model, why it leaned that way (complexity, specialization), and observe the model’s output.
- Scenario – Optimize for depth on a coding task: We set the optimization target to
depth, which biases scoring toward reasoning-capable models. With paid models allowed, the router tends to prefer a remote reasoning model. If paid models are disallowed, it picks the strongest available local alternative. This demonstrates how a single flag flips between enterprise-grade and offline modes without altering the calling code. - Scenario – Optimize for cost on a math puzzle: We switch to
cost, pushing the router toward cheap or free paths. The same prompt flows through the pipeline, but the candidate ranking changes, often selecting a small local model unless the heuristic signals make a compelling case for remote. The scoring weights used here implicitly reflect a prior cost-benefit analysis, where factors such as per-token pricing and model size were translated into a simple cost proxy, allowing the router to approximate relative cost efficiency without computing an explicit dollar total per request. - Scenario – Optimize for speed on a math puzzle: We set the target to
speed, favoring faster models according to their estimated base latency and size rank. On capable hardware, a small local model may win; if local resources are busy, the router can tilt toward a fast remote option. - Variants without paid models: For each scenario, we also run with paid providers disabled. The router still applies the same logic, complexity, specialization, and resources, but the choice is constrained to local candidates. This validates graceful degradation and ensures that teams can operate fully offline when required.
What we learn from this notebook is that the router turns model choice into a data-driven, per-request decision while the rest of the stack (retriever, prompts, and evaluation) stays unchanged. We can articulate why a model was selected, reproduce decisions, and iterate on policy parameters over time. Most importantly, this approach scales from a developer laptop to production clusters and supports both local privacy-first and remote frontier deployments with a single, unified interface.
Case study 1: LangChain in healthcare
Section titled “Case study 1: LangChain in healthcare”In Chapter 9, we covered advanced RAG methods so the model can reason over current, domain-specific facts rather than hallucinating or demanding expensive fine-tuning. Now, we can dive into hands-on examples in code.
Here, we’ll apply our skills to a concrete scenario and walk through the architecture, the design choices, and the trade-offs between local (free) and remote (paid) LLMs, without locking ourselves to any one vendor. The code behind this example uses a compact stack (SentenceTransformers + FAISS + a LangChain-compatible chat model) and an abstraction layer, so we can swap the LLM backend in a few lines.
We must stress that these aren’t real medical notes and that the people described in the notes aren’t real.
The scenario is that a hospital’s care team wants a faster way to surface patient records based on random queries that they have:
- “Who was that patient I saw last year who was pregnant with triplets?”
- “Did I have a patient with a family history of cancer on both sides who asked about a clinical trial?”
These are fuzzy, recall-driven queries. Traditional keyword search often misses these because the note phrasing rarely matches the clinician’s memory. A RAG pipeline is a better fit: we embed notes, retrieve semantically similar passages, and then ask an LLM to synthesize an answer only from the retrieved evidence.
Here are the requirements we’ll satisfy:
- Relevance: Return the right charts/notes from semantic retrieval, not string matches
- Grounded answers: LLM replies must point to retrieved snippets (reduced hallucinations).
- Privacy options: Run locally when notes are sensitive, and switch to remote when you need frontier reasoning
- Swappable LLM: Keep retrieval the same while changing the inference backend (local vs. remote)
At a high level, the flow is the following:

Figure 10.1: The pipeline we will apply for our healthcare use case
We’ll implement the following key components:
- Embeddings: Use a SentenceTransformers model (for example, all-MiniLM-L6-v2) to generate dense vectors for each note. This family provides good quality-to-latency ratios and is widely deployed in production RAG. The choice is pragmatic: fast, small, multilingual variants exist, and they’re easy to run on a CPU.
- Vector store (indexing): Store embeddings in FAISS. FAISS is lightweight, fast, and free. For small to medium corpora and offline demos, a flat index works well.
- Retriever: At query time, embed the clinician’s question and search top-k neighbors. In production, we’ll likely adopt the following:
- Maximal marginal relevance (MMR) to encourage diversity in the retrieved set
- A hybrid retriever (sparse + dense), so obvious keyword hits aren’t lost
- Optional re-ranking (e.g., cross-encoder) when precision at small k matters
- Maximal marginal relevance (MMR) to encourage diversity in the retrieved set
- Prompt composer: Assemble a prompt that instructs the LLM to answer only from the provided context. Include the following:
- A system instruction (domain role, tone, and a grounding rule)
- The retrieved snippets (with short citations or note IDs)
- The user’s question
- Optional constraints (format JSON, list note IDs referenced, include confidence)
- A system instruction (domain role, tone, and a grounding rule)
- LLM backend (swappable): We use a unification layer so the same chain can call either of the following:
- A local model (e.g., Llama 3.x/Mistral via Ollama) for private, $0/token runs
- A remote model (e.g., OpenAI GPT-5 class) for higher reasoning quality and longer context
- A local model (e.g., Llama 3.x/Mistral via Ollama) for private, $0/token runs
To make these routing ideas concrete, we now walk through a practical implementation of an in-house healthcare chatbot. Using a simple rule-based approach, this example shows how model selection can be performed dynamically at runtime while keeping the rest of the RAG stack unchanged. Follow the next steps to understand each part of the notebook and see how you can build and extend this solution on your own.
You can follow along with the full implementation by referring to the accompanying GitHub repository, specifically, the Ch10_in_house_chatbot_healthcare.ipynb notebook, which mirrors the steps discussed here.
Set up the environment and install dependencies
Section titled “Set up the environment and install dependencies”Start by installing the required Python packages, including LLMPop for unified model invocation, SentenceTransformers for embeddings, FAISS for vector search, and LangChain’s core components. If you plan to experiment with OpenAI models, you should also set your API key here:
%pip -q install llmpop%pip -q install sentence-transformers faiss-cpu langchain langchain_core -U langchain-community# Optional: set your OpenAI API key if you want to test remote modelsos.environ[“OPENAI_API_KEY”] = getpass(“Paste your OpenAI API key: “)These installations are required only once. You can skip the API key prompt if you want to restrict the exercise to local, open source models.
Load the mock physician notes into memory
Section titled “Load the mock physician notes into memory”This example uses a dataset of synthetic physician notes. The notebook fetches a CSV file from GitHub, stores it locally, and loads the contents via TextLoader. You can replace this dataset with your own notes in CSV or text files:
text_file_path = “mocked_up_physician_records.csv”url = “https://raw.githubusercontent.com/PacktPublishing/Mastering-NLP-from-Foundations-to-LLMs/main/Chapter8_notebooks/” + text_file_pathres = requests.get(url)with open(text_file_path, “w”) as f: f.write(res.text)# Load the file into Document objectstext_loader = TextLoader(text_file_path)documents = text_loader.load()# Inspect the first record (truncated)print(documents[0].page_content[:200])The page_content attribute of each document contains the raw note. With real medical documents that hold protected information, you can apply de-identification to protect sensitive data before embedding it.
Chunk the documents and build a vector index
Section titled “Chunk the documents and build a vector index”We split long notes into chunks using CharacterTextSplitter so they fit within the embedding model’s window. Then, we embed each chunk with a SentenceTransformers model (all-mpnet-base-v2) and store the resulting vectors in a FAISS index for efficient similarity search:
# Split notes into chunks of ~2k characters, separated by the “Title” delimitertext_splitter = CharacterTextSplitter( chunk_size=chunk_size, chunk_overlap=chunk_overlap, separator=split_text_by)split_docs = text_splitter.split_documents(documents)# Create normalized embeddings for each chunkembeddings = HuggingFaceEmbeddings( model_name=”sentence-transformers/all-mpnet-base-v2”, encode_kwargs={“normalize_embeddings”: True})# Build a FAISS vector store using cosine similarity (via MAX_INNER_PRODUCT)vector_db = FAISS.from_documents( split_docs, embeddings, distance_strategy=DistanceStrategy.MAX_INNER_PRODUCT)This step yields a vector_db object that can perform fast similarity searches over the embedded notes. We will elaborate on this setting next, as we will use it to make smart choices when evaluating the difficulty of responding to queries.
Query the vector store for relevant notes
Section titled “Query the vector store for relevant notes”Before involving a language model, we demonstrate the retrieval step alone. We search the vector store with two questions: one where an answer exists (“due to deliver in August”) and one where it does not (“due to deliver in September”). The retrieval returns the top- k chunks along with similarity scores:
# Helper to pretty-print retrieved docsdef format_documents(doc_list): formatted_entries = [] for doc, _score in doc_list: entry = ( f”vector DB identifier=’{doc.id}’\n” f”source: ‘{doc.metadata.get(‘source’, ‘’)}’\n” f”page_content=’{doc.page_content}’\n” “\nEnd of case.\n---\n” ) formatted_entries.append(entry) return “\n”.join(formatted_entries)# Question 1: answer existsquery1 = “Are there any pregnant patients who are due to deliver in August?”docs1 = vector_db.similarity_search_with_score(query1, k=top_k)print(format_documents(docs1))# Question 2: answer does not exist (September)query2 = “Are there any pregnant patients who are due to deliver in September?”docs2 = vector_db.similarity_search_with_score(query2, k=top_k)print(format_documents(docs2))For the September query, the retrieval returns similar cases, but cannot conclude whether the answer is “no.” That judgment requires a language model.
Add a language model layer to interpret retrieved evidence
Section titled “Add a language model layer to interpret retrieved evidence”We now define an instruction block and a prompt template to constrain the model: answer the question using only the retrieved context, cite the row index of supporting cases, and report “insufficient evidence” if necessary. We first call a local Llama-based model via Ollama, then optionally test the same prompt with an OpenAI model:
instructions = “””Instructions:1. Using the following context, answer the question.2. Use concise and professional tone. Keep it short!3. Below is context of cases to use for answering the question, where each case has identifying fields and a page_content text field.4. Restrict your answer to rely only on information in the page_content of the cases, and reference the Row index of the cases used in your answer. If the answer cannot be answered with the provided context, tell that in your response, and keep it to a single sentence! You must be very thorough and detail oriented in your answer!”””task_template = “””{instructions}Context:{context}Question: {question}---Response:“””# Use a local Llama model via Ollamalocal_llm = init_llm(model=”llama3.2”, provider=”ollama”)prompt = ChatPromptTemplate.from_template(task_template)result_local = (prompt | local_llm).invoke({ “instructions”: instructions, “context”: format_documents(docs2), “question”: query2})print(result_local.content)# Optional: call OpenAI GPT5.2 for comparisonimport openairesponse = openai.chat.completions.create( model=”gpt-5.2-2025-12-11”, messages=[ {“role”:”system”,”content”:”You are a medical assistant.”}, {“role”:”user”, “content”: task_template.format( instructions=instructions, context=format_documents(docs2), question=query2 )} ])print(response.choices[0].message.content)Both models conclude that no September due date is mentioned; both are correct. The OpenAI model tends to offer more elaborate framing or secondary suggestions, while the local model sticks strictly to the instructions.
Implement a simple LLM router
Section titled “Implement a simple LLM router”To avoid hardcoding our model choice, we can route each query dynamically. The choose_llm() function bases its decision on the maximum similarity score of retrieved chunks, whether the query is “highstakes,” and whether an OpenAI API key is present. The router defaults to local unless the context is weak or highstakes. The route_llm() helper both reports and instantiates the chosen model:
def choose_llm(query, docs, api_key_present, good_similarity=0.6, weak_similarity=0.3): max_similarity = docs[0][1] high_stakes = any(kw in query.lower() for kw in [ “diagnos”, “treatment”, “prescrib”, “legal”, “contract”, “compliance”, “deadline”, “critical”, “must”, “policy” ]) if not api_key_present: return “local” elif max_similarity >= good_similarity: return “local” elif max_similarity <= weak_similarity or high_stakes: return “openai” else: return “local”def route_llm(query, docs, verbose=True): api_key_present = bool( os.environ.get(“OPENAI_API_KEY”, “”).startswith(“sk-”)) choice = choose_llm(query, docs, api_key_present) if verbose: print(f”The chosen model is {choice}.”) if choice == “local”: return init_llm(model=”llama3.2”, provider=”ollama”) else: return init_llm(model=”gpt-5.2-2025-12-11”, provider=”openai”)The choose_llm() function evaluates three simple signals:
- API availability: If there is no OpenAI key configured, we must run locally. This covers laptops, air-gapped environments, or demos where cloud access is intentionally disabled.
- Retrieval tightness – maximum similarity:
- Compute the maximum similarity among the retrieved items.
- If
max_similarity ≥ good_similarity, retrieval is confident: answers are likely “close to the surface.” We prefer local; it’s cheaper, private, and good enough when the context is crisp. - If
max_similarity ≤ weak_similarity, retrieval is thin; the model will need more reasoning and careful interpolation of sparse cues. We escalate to remote to maximize quality.
- If
- Compute the maximum similarity among the retrieved items.
- High-stakes heuristics:
- A minimal keyword check flags sensitive/critical intents (e.g., diagnosis, treatment, legal, compliance, and deadline).
- If the request sounds high-stakes, we escalate to remote, even when similarity is middling, prioritizing accuracy, instruction following, and format compliance.
- A minimal keyword check flags sensitive/critical intents (e.g., diagnosis, treatment, legal, compliance, and deadline).
Retrieval confidence is a strong predictor of how much reasoning the LLM must supply. The term confidence is meant to reflect the relevance of the retrieved chunks with regard to the query. The max_similarity = docs[0][1] variable holds the maximal inner-product value for the retrieved chunks, reflecting the relevance of the top retrieved chunk.
High-confidence retrieval means the answer is basically in the text; low-confidence retrieval means the LLM must bridge gaps, where frontier models pay off. The router uses this confidence signal, along with the escalation rules described earlier, to determine how each request is handled:
- Default behavior: When none of the escalation conditions hold, we route to local. This lowers spend and keeps data in-house while still producing grounded answers thanks to RAG.
- Return value: The router returns a choice: local or OpenAI’s. The wrapper that follows instantiates the proper chat.
Now, let’s review some particular examples and how the router dealt with them.
Example 1: Simple
Section titled “Example 1: Simple”Let’s start with a simple query: What patient complained about migraine or headaches?
From a retrieval perspective, this is a straightforward case. Symptom keywords (migraine / headaches) appear explicitly or via close paraphrase in many notes; the top-k results include a passage mentioning headaches with high similarity (≥ good_similarity). In other words, the answer is retrieval-obvious.
Given this context, the router evaluates a few basic conditions. An API key is available, and the maximum similarity score from retrieval is high. Based on these signals, the router routes the request to a local model.
A local model is appropriate here for several reasons:
- The task is mostly extractive. Identify which retrieved snippet mentions headaches and synthesize a short answer citing that patient ID.
- Local small models handle shallow reasoning and short context grounding well, especially when the prompt enforces “answer only from provided context, cite IDs.”
- We save costs and keep protected content on-box.
When reviewing the output, there are a few things to look for. The response should be concise and should clearly reference the retrieved patient ID or IDs. The risk of hallucination is minimal in this case, since the context contains an explicit mention of headaches. If the local model’s answer is minimal, that is acceptable here: the requirement is correctness and proper citation, not stylistic richness.
Example 2: Difficult
Section titled “Example 2: Difficult”Now, let’s look at a more difficult query: Which patient could possibly have relatives in Europe?
From a retrieval standpoint, this question is indirect and intentionally ambiguous. The notes may not contain an explicit statement about relatives in Europe, but instead offer weaker signals such as a recent trip to Spain, immigration from Poland, or mentions that family members live abroad. As a result, the top- k retrieved passages tend to be only loosely related to the query, and the maximum similarity score often falls into a grey area, somewhere between the weak_similarity and good_similarity thresholds.
Given these signals, the router evaluates the situation more carefully. An API key is available, but the maximum similarity score is not high enough to indicate a retrieval-obvious answer. The query is also not high-stakes, since it does not trigger a clinical decision or action. Under the default policy, the router still routes the request to a local model, unless the similarity score drops below the weak_similarity threshold, in which case the request would be escalated to a stronger model.
This makes the query a useful “borderline” test case for the routing policy:
- If the local model is able to produce a correct, grounded inference based on the retrieved context, it reinforces the default-to-local strategy
- On the other hand, if the model hedges appropriately or fails to make the inference, the logs will typically show low similarity or low confidence signals
When reviewing the output, there are a few key behaviors to watch for:
- Does the model explicitly tie the claim to a retrieved snippet?
- If the context doesn’t support a firm conclusion, does it suggest it lacks sufficient evidence per the instructions? That behavior is more valuable than an overconfident guess.
Example 3: Very difficult
Section titled “Example 3: Very difficult”Finally, let’s consider a very difficult query: I might not have captured it in my notes, but one of my patients seemed angry. Who might that have been?
From a retrieval perspective, this is the hardest case so far. The query is ambiguous and effective, asking about emotional state rather than an explicit fact. Clinical notes rarely label emotions directly, so the retrieval step often surfaces only weak or indirect matches. Similarity scores frequently fall at or below the weak_similarity threshold. Any potential signal tends to come from subtle phrasing, such as repeated complaints, mentions of raised voices, or tense interactions, if such cues exist at all.
Given these conditions, the router’s decision becomes clearer. An API key is available, and the maximum similarity score is at or below the weak threshold, which triggers escalation to a remote model. Even without that explicit trigger, the nature of the task itself points toward escalation. Inferring sentiment from sparse, implicit cues is something frontier models handle more reliably than smaller local models.
So why escalate?
- This is precisely the long tail where remote models justify cost: they can parse nuance, follow stricter output formats, and avoid brittle keyword dependence
- If the evidence is truly insufficient, remote models are also better at stating limits clearly while preserving citations
When evaluating the output, there are two acceptable outcomes. Either a well-justified candidate with explicit reference or a one-sentence “insufficient evidence” reply with a brief rationale.
Taken together, these examples highlight why simple routing rules are effective. They are transparent and easy for stakeholders to audit, which is especially important in regulated domains. They are also inexpensive to maintain, since no additional training is required, and behavior can be adjusted through threshold tuning. Most importantly, they align routing decisions with business risk, escalating only when retrieval is thin or when the task demands deeper reasoning.
With routing behavior established, we can now move on to the final feature in this solution: conversation memory.
Applying conversation memory
Section titled “Applying conversation memory”At this point, our clinical staff is able to fetch patients’ records and details based on ad-hoc questions. However, in real-world settings, the staff member isn’t always able to articulate what they are looking for in a single comprehensive question. It may be a discovery process. They may start by asking one question, and then, based on the response, they may form a follow-up question, and so on. In such a case, a memory mechanism must be implemented. Without memory, the conversation could look like this:
Question: “Are there any patients who are above 65 years of age?”Answer: “Yes, patient X is 67 years old, and patient Y is 93 years old.”Question: “Is any of them living alone?”Answer: “Your question asks about ‘them’ but you have not provided details about whom you are asking about.”As we can see from this conversation, the LLM has no context for the term them in the second question, as the history of the conversation isn’t available for the LLM with our current setting. So, let’s fix that.
To do that, we will simply enhance the full prompt that we send to the LLM to include a clause for the conversation’s history. That means that after every response, we will log the question that the user sent and the response that the LLM gave, and we will add that to the next prompt. As a design note, consider that the context (meaning the retrieved chunks that are relevant for the conversation) may need to accumulate as well, so as to always allow the LLM to have all the context necessary:
task_template_with_memory = “””{instructions}Context:{context}Conversation history, later appears last:{history}Question: {question}---Response:“””That’s it, as simple as that.
We then put together the loop that iterates over the live conversation, allowing the user to take turns with the LLM:
expended_top_k = 4history = “”retrieved_docs_memory = OrderedDict()while True: print(“\nYour input:”) query_live = input() if query_live.lower() == ‘stop’: break print(“\nResponse:”) docs_live = vector_db.similarity_search_with_score( query_live, k=expended_top_k) # Accumulate retrieved documents across turns for doc, score in docs_live: retrieved_docs_memory[doc.id] = doc accumulated_context = format_documents( [(doc, None) for doc in retrieved_docs_memory.values()]) chosen_llm_live = route_llm( query_live, docs_live, verbose=False) prompt = ChatPromptTemplate.from_template( task_template_with_memory) response = (prompt | chosen_llm_live).invoke( { “instructions”: instructions, “context”: accumulated_context, “history”: history, “question”: query_live } ).content print(response) history += f”User Query: {query_live}\nResponse: {response}\n---\n\n”Feel free to converse with the LLM about the patients’ information and try different scenarios.
There is a point to be stressed with accumulating conversation history. Keep in mind that as the conversation progresses, more and more history is appended. That makes the prompt longer and longer and may go beyond the maximum token count that the LLM can process. For that purpose, it is best practice to implement a mechanism to keep the history below a certain length. There are many ways to do so. The simplest one is to remove the oldest part of the conversation history from memory (i.e., first in, first out). More advanced techniques may be to identify the least relevant parts of the conversation history, to summarize the conversation history, or even to embed the conversation history and to apply a RAG mechanism to retrieve the part of the conversation’s history on demand based on the current user query.
To conclude this example of a full prototype of a practical solution to a real-world problem, we can reflect on its practical implementation in response to a need that healthcare professionals have, and how it can enhance their practice while translating to a better care experience for patients. Both of us, as the authors of this book and its previous edition, have experienced firsthand how effective it is to join hands with medical staff and apply our methods for supporting both research and clinical care. Some of those projects have been written about and will give you a good view of applied ML and AI in the healthcare setting, in particular (Daly et al., 2022; Do et al., 2021; Agrawal et al., 2022).
Now that we have laid out the entire pipeline incrementally and derived a full solution, let us see how it can be applied to a new use case from a new industry, legal.
Case study 2: LangChain design for legal document analysis
Section titled “Case study 2: LangChain design for legal document analysis”We now have the “recipe” for a complete, end-to-end prototype of an in-house chatbot. This is a full proof of concept that can be applied to any real-world use case where the data is available in the form of free text, and the wish is to automate the process of searching through the various text data, and to converse with a model about the data that it finds.
Let’s see how, for example, we apply it to a case from the legal space, where the data is the content of legal contracts.
Legal teams are drowning in contracts, vendor MSAs (Master Services Agreements), NDAs (Non-Disclosure Agreements), DPAs (Data Processing Agreements), SOWs (Statement of Work), each with subtly different clauses that matter for risk, timelines, and revenue. Attorneys and ops partners need fast, reliable answers to questions such as “Do we allow automated data collection?” or “Which agreements mandate a 30-day termination notice?” without manually skimming hundreds of pages. An in-house, contract-aware chatbot turns unstructured agreements into a searchable, conversational interface: it retrieves the exact clauses, cites where they came from, and adapts to follow-up questions. The business impact is shorter deal cycles, fewer missed obligations, and a stronger compliance posture, while keeping sensitive documents inside our boundary. With the same RAG skeleton we already built, we simply swap the corpus and add light domain instructions to deliver immediate value to legal and commercial teams.
To see how easily we can pivot our RAG plus routing pipeline from healthcare to legal, let’s walk through a hands-on example using a dataset of plain-English contracts. This notebook uses the same underlying stack: SentenceTransformers for embeddings, FAISS for retrieval, and a simple rule-based router to decide between a local and a remote model, while tuning a few choices for the legal domain. Follow these steps to understand the code and its rationale.
You can follow along with the full implementation by referring to the accompanying GitHub repository, specifically, the Ch10_in_house_chatbot_legal.ipynb notebook, which mirrors the steps discussed here.
Install dependencies and set up the environment
Section titled “Install dependencies and set up the environment”As before, we install our core libraries: LLMPop for unified model invocation, SentenceTransformers for embedding contracts, FAISS for similarity search, and LangChain for prompts and chain management. We also set up a few configuration parameters and, optionally, an OpenAI API key if you want to test remote models:
%pip -q install llmpop%pip -q install sentence-transformers faiss-cpu langchain langchain_core -U langchain-community langchain-text-splitters# Optional: provide your OpenAI API key to enable routing to remote modelsos.environ[“OPENAI_API_KEY”] = getpass(“Paste your OpenAI API key: “)Load and prepare the contracts dataset
Section titled “Load and prepare the contracts dataset”We download a publicly available dataset of plain-English contracts from Hugging Face. The table has each row dedicated to a different contract. The columns that we leverage for this project are as follows:
Doc: A string, telling what legal document is being captured in this roworiginal_text: A string, the content of the legal document
We prepend a consistent marker to each contract and keep simple metadata (row index and source document) for later citation:
# Load the dataset from Hugging Face (local or remote)df_contracts_summarization = pd.read_json( “hf://datasets/joelniklaus/plain_english_contracts_summarization/train.jsonl.xz”, lines=True)# Add a consistent prefix and create a formatted text fielddf_contracts_summarization[“formatted_text”] = ( “Content of the contract:\n” + df_contracts_summarization[“original_text”])# Convert each row into a LangChain Document with minimal metadatadocuments = [ Document( page_content=row[“formatted_text”], metadata={“Table index”: idx, “source”: row[“doc”]} ) for idx, row in df_contracts_summarization.iterrows()]# Inspect a few sample entriesfor text in df_contracts_summarization[“formatted_text”].head(3): print(text.split(“\n”)[0], “...”) # prints the prefix and part of the contractThis structure mirrors the healthcare notes example: we’re treating each contract as a single document with a stable marker at the beginning, which simplifies downstream splitting.
Split contracts into chunks and embed them
Section titled “Split contracts into chunks and embed them”Contracts vary in length, so we use CharacterTextSplitter to break each contract into manageable chunks. We then embed each chunk using a normalized version of the all-mpnet-base-v2 model, which works well for general English text:
# Split the contracts using our markertext_splitter = CharacterTextSplitter( chunk_size=chunk_size, chunk_overlap=chunk_overlap, separator=split_text_by)split_docs = text_splitter.split_documents(documents)# Create normalized embeddings for each chunkembeddings = HuggingFaceEmbeddings( model_name=”sentence-transformers/all-mpnet-base-v2”, encode_kwargs={“normalize_embeddings”: True})# Build a FAISS vector store using inner-product similarity (equivalent to cosine here)vector_db = FAISS.from_documents( split_docs, embeddings, distance_strategy=DistanceStrategy.MAX_INNER_PRODUCT)print(f”Number of chunks indexed: {len(split_docs)}”)At this point, vector_db can perform quick similarity searches over clauses and paragraphs in our contracts.
Format retrieval results for grounding and citation
Section titled “Format retrieval results for grounding and citation”To feed retrieved clauses into a language model and ask it to reason over them, we convert the (document, score) pairs into a human-readable string that includes both the contract text and the identifying metadata. This helper function will be reused for prompting and citation:
def format_documents(doc_list): formatted_entries = [] for doc, _ in doc_list: entry = ( f”Row index: ‘{doc.metadata.get(‘Table index’, ‘’)}’\n” f”source: ‘{doc.metadata.get(‘source’, ‘’)}’\n” f”page_content=’{doc.page_content}’\n” “\nEnd of case.\n---\n” ) formatted_entries.append(entry) return “\n”.join(formatted_entries)When you query the vector store, you’ll pass the retrieved list through format_documents() to embed it into your prompt.
Implement a legal-aware LLM router
Section titled “Implement a legal-aware LLM router”The same simple routing logic used for healthcare can work here, but we refine the “high stakes” keyword list to reflect legal concepts: terms such as governing law, jurisdiction, indemnify, or termination. If the query matches those terms or the similarity scores are low, the router escalates to a remote model (if allowed); otherwise, it uses a local model:
def choose_llm(query, docs, api_key_present, good_similarity=0.6, weak_similarity=0.3): # List of legal keywords that indicate high-stakes clauses legal_high_stakes_terms = [ # Dispute resolution “arbitration”, “aaa”, “class action”, “jury trial”, “injunctive relief”, # Liability and warranty “indemnify”, “limitation of liability”, “damages”, “warranty”, # Governing law and venue “governing law”, “jurisdiction”, “venue”, “choice of law”, # IP and licensing “intellectual property”, “license”, “reverse engineer”, # Termination and breach “terminate”, “breach”, “notice”, “material breach”, # Privacy and data “privacy policy”, “personal data”, “gdpr”, # Other catchalls “refund”, “fees”, “export”, “assignment”, “third party”, “terms of service”, “acceptable use” ] high_stakes = any( term in query.lower() for term in legal_high_stakes_terms) max_similarity = docs[0][1] # highest similarity score among retrieved docs if not api_key_present: return “local” elif max_similarity >= good_similarity: return “local” elif max_similarity <= weak_similarity or high_stakes: return “openai” else: return “local”def route_llm(query, docs, verbose=True): # Check if an OpenAI key is available api_key_present = bool( os.environ.get(“OPENAI_API_KEY”, “”).startswith(“sk-”)) choice = choose_llm(query, docs, api_key_present) if verbose: print(f”The chosen model is {choice}.”) if choice == “local”: return init_llm(model=”llama3.2”, provider=”ollama”) else: return init_llm(model=”gpt-5.2-2025-12-11”, provider=”openai”)This router ensures that straightforward contract queries run locally for privacy and zero cost, while more complex or legally sensitive questions can tap remote models when available.
Test the retrieval and router with an example query
Section titled “Test the retrieval and router with an example query”Before we write prompts, it’s useful to inspect raw retrieval results. Here, we ask whether any clauses mention automated scripts or software collecting information. We print the top two chunks to verify that the right passages are being surfaced:
query1 = “Is there any mention of using automated scripts or other software to collect information?”docs1 = vector_db.similarity_search_with_score(query1, k=top_k)print(“\nTop retrieved clause:”)print(docs1[0][0].page_content)print(“\nSecond retrieved clause:”)print(docs1[1][0].page_content)At this stage, you could call route_llm() to see which model would be chosen for the query. That helps you confirm that the router is favoring local models when similarities are high and escalating when necessary.
Enable conversation memory for follow-up questions
Section titled “Enable conversation memory for follow-up questions”Contracts often require iterative exploration: after finding a relevant clause, you might ask for more details. We reuse the instruction block from the healthcare example, adjusting only the metadata labels (“Row index” instead of patient IDs). We add a history field to our prompt so the model can resolve references such as that case or the second clause without asking the user again:
instructions = “””Instructions:1. Using the following context, answer the question.2. Use a concise and professional tone. Keep it short!3. Below is context of clauses to use for answering the question, where each clause has identifying fields and a page_content text field.4. Restrict your answer to rely only on information in the page_content of the clauses, and reference the Row index of the clauses used in your answer. If the answer cannot be answered with the provided context, say so in one sentence. Be thorough and detail oriented in your answer.”””task_template_with_memory = “””{instructions} Context: {context}
Conversation history, later appears last: {history}
Question: {question}
--- Response:“””history = “”retrieved_docs_memory = OrderedDict()while True: print(“\nYour input:”) query_live = input() if query_live.lower() == ‘stop’: break print(“\nResponse:”) docs_live = vector_db.similarity_search_with_score( query_live, k=top_k) # Accumulate retrieved documents across turns for doc, score in docs_live: retrieved_docs_memory[doc.id] = doc accumulated_context = format_documents( [(doc, None) for doc in retrieved_docs_memory.values()]) chosen_llm_live = route_llm(query_live, docs_live, verbose=False) prompt = ChatPromptTemplate.from_template(task_template_with_memory) response = (prompt | chosen_llm_live).invoke( {“instructions”: instructions, “context”: accumulated_context, “history”: history, “question”: query_live} ).content print(response) history += f”User Query: {query_live}\nResponse: {response}\n---\n\n”In an interactive run, you might start with “Are there clauses where the company doesn’t store information of the user or visitor?” and follow up with “Oh, yes, good, that clause seems relevant, share more details about it!” The history string grows with each turn, giving the model enough context to answer the second question correctly.
The healthcare and legal flows share the same skeleton:
Figure 10.2: The pipeline applied for our legal use case
Swapping the corpus and a few domain-specific instructions is all it takes to repurpose the pipeline. The router ensures that we spend where it matters and keep costs and data exposure low everywhere else.
In addition to the three code solutions that we reviewed here, the book’s first edition has a good set of solutions as well. It is available in its GitHub repo: https://github.com/PacktPublishing/Mastering-NLP-from-Foundations-to-LLMs.
Summary
Section titled “Summary”In this chapter, we turned RAG from a concept into a production-minded pattern we can reuse across domains. The core stack (SentenceTransformers for embeddings, FAISS for vector search, and a LangChain-compatible chat interface) stayed constant, while the model choice became a policy decision rather than a hardcoded dependency. We learned how to navigate the trade-offs between local (free) and remote (paid) models. Local models excel when privacy, cost control, and offline operation matter; remote models shine on multi-hop reasoning, long context, and strict format compliance.
We then operationalized those ideas with a per-request router. Lightweight signals, retrieval confidence, prompt complexity, domain hints, resource snapshots, and optimization goals (speed, cost, and depth) guided model selection. The result is transparent, auditable behavior: default to local, and escalate to a stronger remote model when evidence is thin, stakes are high, or tasks are complex. Because the router and interface are unified, the rest of our application remains stable and testable.
Two end-to-end examples demonstrated portability. In healthcare, the system answered fuzzy, recall-driven clinician questions with grounded, cited responses, while preserving privacy when needed. In legal, the same blueprint became a contracts-aware assistant that retrieved exact clauses, cited their sources, and supported drill-down follow-ups. Across both, we added conversation memory with practical guardrails (truncation and summarization), ensuring continuity without overrunning context limits. We now have a reusable patternwith clean seams for model choice and policy control. This foundation is exactly what we need for the next step.
In the next chapter, we’ll build on this foundation to design multi-agent code solutions. We’ll see how multiple specialized agents, planners, tool users, critics, and executors can collaborate, negotiate, or even compete to solve complex tasks that exceed a single model’s comfort zone. We’ll introduce advanced agent frameworks, show how our existing RAG and routing patterns plug into them, and walk through real projects where coordination, not just generation, becomes the core capability.
Questions
Section titled “Questions”- In our RAG-centric architecture, what stays constant across deployments, and what is intentionally swappable, and why does that separation matter in production?
- List three application-level factors that should drive a default choice between local (free) and remote (paid) LLMs for an in-house chatbot.
- What signals does a per-request, policy-driven router use to decide when to escalate from a local model to a remote frontier model?
- How does LLMPop and a unified init_llm-style interface enable backend interchangeability without changing retrievers, prompts, or evaluation code?
- Walk through the end-to-end pipeline skeleton used in the chapter and name the role of each stage.
- In the healthcare example, why is retrieval-only insufficient for some questions, and how does adding the LLM layer change the outcome and its auditability?
- Compare expected behaviors of local vs remote models on the same retrieved context across reasoning depth, latency, privacy, and cost.
- What guardrails and formatting constraints did we impose in prompts to reduce hallucinations and ensure citable answers, and how are citations produced?
- How is conversation memory integrated into the prompt, and what practical strategies keep memory within token limits while preserving context across turns?
- In the legal-contracts chatbot, which elements were domain-specific, and which parts remained identical to the healthcare build?
References
Section titled “References”- Gazit, L. 2025. LLMPop. https://pypi.org/project/llmpop/
- Lewis, P. et al., 2020. Retrieval-Augmented Generation for Knowledge-Intensive NLP. NeurIPS
- FAISS library. Johnson, J., Douze, M., Jégou, H. Billion-scale similarity search with GPUs. IEEE TPAMI, 2019 (and/or FAISS official docs)
- Daly, B., Nicholas, K., Flynn, J., et al. Analysis of a Remote Monitoring Program for Symptoms Among Adults With Cancer Receiving Antineoplastic Therapy. JAMA Netw Open. 2022;5(3):e221078. doi:10.1001/jamanetworkopen.2022.1078
- Patterns of Metastatic Disease in Patients with Cancer Derived from Natural Language Processing of Structured CT Radiology Reports over a 10-year Period. Richard K. G. Do, Kaelan Lupton, Pamela I. Causa Andrieu, Anisha Luthra, Michio Taya, Karen Batch, Huy Nguyen, Prachi Rahurkar, Lior Gazit, Kevin Nicholas, Christopher J. Fong, Natalie Gangai, Nikolaus Schultz, Farhana Zulkernine, Varadan Sevilimedu, Krishna Juluru, Amber Simpson, and Hedvig Hricak. Radiology 2021 301:1, 115-122
- Agrawal, M.N., Lang, H., Offin, M., Gazit, L., and Sontag, D., 2022. Leveraging Time Irreversibility with Order-Contrastive Pre-training. Proceedings of The 25th International Conference on Artificial Intelligence and Statistics, in P roceedings of Machine Learning Research 151:2330-2 353. Available from https://proceedings.mlr.press/v151/agrawal22a.html