Overview

7 Creating LLM-based Applications using LangChain and LlamaIndex

This chapter shows how to turn large language models into practical applications by combining LangChain for orchestration and LlamaIndex for connecting models to private data. It begins with a concise view of LLMs—their scale, pretraining and fine-tuning—and motivates moving beyond single-model pipelines toward modular systems that mix providers and capabilities. The overarching goal is to build chat and task-focused tools that can reason over both public knowledge and domain-specific documents, while balancing speed, cost, quality, and data privacy, whether models run in the cloud or locally.

With LangChain, you compose applications from prompt templates, LLMs, and output parsers into executable chains using a simple pipeline syntax. The chapter demonstrates using Hugging Face–hosted models (for example, Zephyr) via HuggingFaceEndpoint and OpenAI models via ChatOpenAI, then shows how to run the chain, parse responses, and maintain conversational context. Conversation memory is handled either by injecting history into the prompt or by using RunnableWithMessageHistory for cleaner state management. Beyond Q&A, the same pattern supports text completion and swapping in other instruction-tuned models (such as Falcon), while noting that provider-hosted inference happens remotely and local inference remains possible for select tasks.

LlamaIndex brings Retrieval-Augmented Generation to your own files by ingesting documents, creating vector embeddings, and indexing them for efficient retrieval. The workflow covers loading PDFs with SimpleDirectoryReader, embedding locally with a Hugging Face model (such as BAAI/bge-small-en-v1.5) to preserve privacy, building and persisting a VectorStoreIndex, and then querying it with either a local LLM (for example, Llama 3.2–3B Instruct) or a cloud model like gpt-4o-mini, highlighting the trade-off between speed/quality and data confidentiality. The chapter concludes by wrapping the query or chat engine in a lightweight Gradio interface, switching from as_query_engine to as_chat_engine for multi-turn conversations, and optionally accelerating local inference on available GPUs.

Large Language Models are trained using large amount of data – books, articles, web pages, videos, and images.
The input variable is linked to the variable in the string template
Creating a Hugging Face token
The 'HuggingFaceH4/zephyr-7b-alpha' is a Text Generation model.
User can ask questions and get a response from the LLM
You can get the model to complete your sentence
Applying for an OpenAI API key
The “Training Documents” folder contains four PDF files
The Gradio interface is bound to the query engine
Asking a question regarding the purchases stored in the PDF receipts
Asking a series of follow-up questions and the chatbot can maintain the conversation
The Gradio chat user interface
Using the chat user interface to chat with the chat engine

Summary

  • A Large Language Model (LLM) is a type of AI model that is designed to understand and generate human-like text based on the patterns and structures it has learned from massive amount of training data.
  • A "token" is a chunk of text that a model processes as a single unit.
  • LangChain is a framework built around LLMs , designed to simplify the creation of applications using LLMs.
  • A LangChain application is made up of components chained together.
  • You can run an LLM locally or use one that is cloud-based, such as those from OpenAI.
  • LlamaIndex is a data framework for LLM-based applications to ingest, structure, and access private or domain-specific data.
  • RAG is a technique used to enhance the performance of large language models (LLMs) by integrating them with an external retrieval system.
  • Running a model locally for vector embedding ensures your data stays within your computer.
  • You can create a web frontend for your LLM applications using Gradio

FAQ

What is a Large Language Model (LLM) and how is it trained? A Large Language Model is an advanced NLP model trained on massive datasets (books, articles, web pages, etc.) to understand and generate human-like text. Training typically involves: - Pre-training: learning statistical relationships between tokens to acquire grammar, syntax, and semantics. - Fine-tuning: adapting the model to specific tasks (classification, translation, Q&A, etc.). LLMs operate on tokens (subword units produced by techniques like Byte-Pair Encoding), which help them handle diverse vocabularies efficiently.
What is LangChain and what components does a “chain” include? LangChain is a framework that simplifies building LLM-based applications by connecting modular components. A typical chain can include: - Prompt Templates: reusable prompt structures with variables. - LLMs: the underlying models (e.g., GPT-4o-mini, Zephyr, Falcon). - Agents: components that decide which actions to take. - Memory: mechanisms for short- or long-term conversational context.
How do I create and use a PromptTemplate in LangChain? Define a string template with variables, then supply those variables as input. Example idea: a template with a single variable “question” is combined with a model and an output parser using pipeline-style chaining (the | operator). The chain takes user input, formats the prompt, calls the model, and parses the response into a string.
How can I use a Hugging Face–hosted model in LangChain, and where does inference happen? - Create a Hugging Face account and set a read token in your environment. - Install langchain-huggingface and use HuggingFaceEndpoint with the model’s inference API URL (e.g., HuggingFaceH4/zephyr-7b-alpha). - Chain it with your prompt and a string output parser. Inference runs on Hugging Face’s servers (not locally), so responses come from their hosted infrastructure.
How do I maintain conversational context between turns in LangChain? Two common approaches: - Prompt-based history: add a “history” variable to your prompt template and pass prior exchanges each turn. - RunnableWithMessageHistory: use LangChain’s built-in class to store and retrieve message history, so the chain can keep track of prior user/assistant messages automatically.
Can I switch to other LLM providers like OpenAI or different Hugging Face models? Yes. - OpenAI: install langchain_openai, set OPENAI_API_KEY, then use ChatOpenAI with a model like gpt-4o-mini. - Other Hugging Face models: point HuggingFaceEndpoint to a different model (e.g., tiiuae/falcon-7b-instruct). Because LangChain abstracts the interface, you can usually reuse your existing prompt and chain logic with minimal changes.
What is LlamaIndex and how does RAG help me query my private data? LlamaIndex is a data framework that lets LLM apps ingest, structure, and access private/domain data. It implements Retrieval-Augmented Generation (RAG): your documents (e.g., PDFs, Word, HTML, CSV, JSON) are loaded, transformed into vector embeddings, indexed, and then retrieved at query time so the LLM can ground its answers in your specific data without retraining the base model.
What are vector embeddings in this workflow, and can I keep embedding local for privacy? Embeddings are numerical vectors that capture semantic information about text. They enable efficient similarity search and retrieval. In the chapter, a local Hugging Face embedding model (BAAI/bge-small-en-v1.5) is used, so embedding runs on your machine—helping preserve data privacy during the indexing step.
How do I build, persist, and reload a vector index with LlamaIndex? - Load documents (e.g., PDFs) with SimpleDirectoryReader. - Create embeddings (e.g., HuggingFaceEmbedding with BAAI/bge-small-en-v1.5). - Build the index with VectorStoreIndex.from_documents and persist it to disk. - Later, reload with StorageContext.from_defaults and load_index_from_storage using the same embedding model. Persisting saves time by avoiding re-embedding unchanged data.
How do I query or chat over my indexed data, and what about performance vs. privacy? - Querying: use index.as_query_engine(llm=...). - Conversational use: use index.as_chat_engine(llm=...) and call chat(...) to maintain multi-turn context. - Local vs. hosted models: Local models (e.g., meta-llama/Llama-3.2-3B-Instruct) keep data on your machine but may be slower and lower quality. Hosted models (e.g., OpenAI gpt-4o-mini) are faster and often higher quality but send queries (and relevant context) to the provider’s servers and incur usage costs. You can wrap either engine with a simple UI using Gradio to make interactive querying or chatting easier.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Hugging Face in Action ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Hugging Face in Action ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Hugging Face in Action ebook for free