LangChain
This chapter uses LangChain's runnable interface as a composition layer for prompts, models, parsers, parallel branches, retries, loaders, splitters, history selection, and tracing.
- Explain LCEL (LangChain Expression Language) by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Memory types by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Document loaders & splitters by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Output parsers by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Custom extensions by naming its input, guarantee, internal lifecycle, important failure, and proof.
How to use this chapter
For LangChain, read the explanations first and predict every example before running it. Keep a learning repository containing code, tests, command output, and the short written submission. The roadmap checklist at the end audits coverage; the chapter itself follows the architecture learning arc appropriate to this subject.
The problem this chapter solves
This chapter uses LangChain's runnable interface as a composition layer for prompts, models, parsers, parallel branches, retries, loaders, splitters, history selection, and tracing.
A model alone has limited freshness, reliability, context, and agency. Engineering layers constrain outputs, ground claims in data, and make decisions inspectable and recoverable.
Learning outcomes
- Explain LCEL (LangChain Expression Language) by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Memory types by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Document loaders & splitters by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Output parsers by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Custom extensions by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Trace the chapter's complete execution path and identify where memory, I/O, concurrency, persistence, or rendering cost accumulates.
- Build the worked example, make one failure visible, and defend the design in a review.
Chapter progression
The order below is intentional: later sections depend on guarantees established earlier.
Runtime or system overview
Text is tokenized and processed autoregressively: each output token is sampled from a conditional distribution. Retrieval adds selected external context; tool calling asks normal code to perform actions; agent graphs persist explicit state and routes. None of these mechanisms guarantee truth, so evaluation and validation remain mandatory. In LangChain, use that execution model to decide where the chapter's validation, state ownership, cleanup, and evidence belong.
Execution trace
- Deterministic code validates the request, identity, tenant, budgets, schemas, and permitted tools before assembling model context.
- Retrieval or memory selection chooses bounded, provenance-bearing evidence; tokenization converts the assembled messages into the model's input sequence.
- The provider generates or streams tokens, or proposes typed tool arguments; application code validates every output and executes only authorized bounded actions.
- Parsers and business rules accept, repair once under policy, route, or reject the result; citations and state transitions are persisted with model, prompt, index, and dataset versions.
- Offline evaluation and production telemetry measure retrieval, faithfulness, latency, token cost, tool errors, safety outcomes, and regressions by cohort.
Memory and performance lens
Context windows hold tokens, not durable memory. Conversation memory is application-managed storage that is selected and inserted into later prompts. Embedding indexes store vectors plus metadata; agent checkpoints store state transitions. Token budgets, cache policy, and data retention must be designed explicitly. For LangChain, connect those costs to the concrete operations in the topic sections rather than assuming the friendly surface syntax is cheap.
When tuning LangChain, measure capacity per critical path, tail latency, availability/error budget, consistency lag, recovery objectives, cost per outcome, and evaluation quality rather than optimizing from source-code appearance.
1. LCEL (LangChain Expression Language)
The LCEL (LangChain Expression Language) unit begins with pipe operator (|) for composing chains: LCEL composes components implementing a common Runnable interface into sequences, maps, parallel branches, retries, and streaming pipelines. Keep transformations explicit and attach dataset/evaluation version tags. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
Requirements, ownership, and trade-offs: LCEL (LangChain Expression Language)
| Concept | Meaning | Engineering decision | |
|---|---|---|---|
| **pipe operator (\ | ) for composing chains** | LCEL composes components implementing a common Runnable interface into sequences, maps, parallel branches, retries, and streaming pipelines. | Keep transformations explicit and attach dataset/evaluation version tags. |
| RunnableSequence/Parallel/Passthrough | LCEL composes components implementing a common Runnable interface into sequences, maps, parallel branches, retries, and streaming pipelines. | Keep transformations explicit and attach dataset/evaluation version tags. | |
| invoke/stream/batch/ainvoke interface | LCEL composes components implementing a common Runnable interface into sequences, maps, parallel branches, retries, and streaming pipelines. | Keep transformations explicit and attach dataset/evaluation version tags. | |
| fallbacks + retries in LCEL | LCEL composes components implementing a common Runnable interface into sequences, maps, parallel branches, retries, and streaming pipelines. | Keep transformations explicit and attach dataset/evaluation version tags. | |
| LangSmith tracing setup | LCEL composes components implementing a common Runnable interface into sequences, maps, parallel branches, retries, and streaming pipelines. | Keep transformations explicit and attach dataset/evaluation version tags. |
Critical path and failure behavior: LCEL (LangChain Expression Language)
pipe operator (|) for composing chains. The pipe operator constructs a graph; invoke, batch, stream, and async variants drive it. Tracing records run trees and metadata.
RunnableSequence/Parallel/Passthrough. The pipe operator constructs a graph; invoke, batch, stream, and async variants drive it. Tracing records run trees and metadata.
invoke/stream/batch/ainvoke interface. The pipe operator constructs a graph; invoke, batch, stream, and async variants drive it. Tracing records run trees and metadata.
fallbacks + retries in LCEL. The pipe operator constructs a graph; invoke, batch, stream, and async variants drive it. Tracing records run trees and metadata.
LangSmith tracing setup. The pipe operator constructs a graph; invoke, batch, stream, and async variants drive it. Tracing records run trees and metadata.
Read these as one system: pipe operator (|) for composing chains establishes the starting contract, RunnableSequence/Parallel/Passthrough changes how that contract is executed or represented, and LangSmith tracing setup exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
A concrete design decision: LCEL (LangChain Expression Language)
1chain = {"context": retriever, "question": RunnablePassthrough()} | prompt | model | parserThis LCEL (LangChain Expression Language) slice makes pipe operator (|) for composing chains observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward LangSmith tracing setup, predict its behavior for empty, invalid, repeated, and large input.
Designs that fail under real load: LCEL (LangChain Expression Language)
| Risk | Why it matters | |
|---|---|---|
| pipe operator (\ | ) for composing chains | A chain abstraction does not remove provider failures or the need to validate outputs. |
| RunnableSequence/Parallel/Passthrough | A chain abstraction does not remove provider failures or the need to validate outputs. | |
| invoke/stream/batch/ainvoke interface | A chain abstraction does not remove provider failures or the need to validate outputs. | |
| fallbacks + retries in LCEL | A chain abstraction does not remove provider failures or the need to validate outputs. | |
| LangSmith tracing setup | A chain abstraction does not remove provider failures or the need to validate outputs. |
Design review exercise: LCEL (LangChain Expression Language)
- Foundation: implement or demonstrate pipe operator (|) for composing chains with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine pipe operator (|) for composing chains with RunnableSequence/Parallel/Passthrough. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for LangSmith tracing setup. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
2. Memory types
The Memory types unit begins with ConversationBufferMemory: full history: Conversation memory is a policy for selecting or compressing prior application messages before a new model call. Store canonical conversation events separately and derive prompt memory per task. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
Requirements, ownership, and trade-offs: Memory types
| Concept | Meaning | Engineering decision |
|---|---|---|
| ConversationBufferMemory: full history | Conversation memory is a policy for selecting or compressing prior application messages before a new model call. | Store canonical conversation events separately and derive prompt memory per task. |
| ConversationBufferWindowMemory: last K turns | Conversation memory is a policy for selecting or compressing prior application messages before a new model call. | Store canonical conversation events separately and derive prompt memory per task. |
| ConversationSummaryMemory: summarize old turns | Conversation memory is a policy for selecting or compressing prior application messages before a new model call. | Store canonical conversation events separately and derive prompt memory per task. |
| ConversationSummaryBufferMemory: hybrid | Conversation memory is a policy for selecting or compressing prior application messages before a new model call. | Store canonical conversation events separately and derive prompt memory per task. |
Critical path and failure behavior: Memory types
ConversationBufferMemory: full history. Buffer strategies retain text, windows drop older turns, summaries replace them with a lossy model-generated state, and hybrids combine recent detail with a summary.
ConversationBufferWindowMemory: last K turns. Buffer strategies retain text, windows drop older turns, summaries replace them with a lossy model-generated state, and hybrids combine recent detail with a summary.
ConversationSummaryMemory: summarize old turns. Buffer strategies retain text, windows drop older turns, summaries replace them with a lossy model-generated state, and hybrids combine recent detail with a summary.
ConversationSummaryBufferMemory: hybrid. Buffer strategies retain text, windows drop older turns, summaries replace them with a lossy model-generated state, and hybrids combine recent detail with a summary.
Read these as one system: ConversationBufferMemory: full history establishes the starting contract, ConversationBufferWindowMemory: last K turns changes how that contract is executed or represented, and ConversationSummaryBufferMemory: hybrid exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
Designs that fail under real load: Memory types
| Risk | Why it matters |
|---|---|
| ConversationBufferMemory: full history | Summaries can lose constraints or accumulate hallucinations; they are not an audit log. |
| ConversationBufferWindowMemory: last K turns | Summaries can lose constraints or accumulate hallucinations; they are not an audit log. |
| ConversationSummaryMemory: summarize old turns | Summaries can lose constraints or accumulate hallucinations; they are not an audit log. |
| ConversationSummaryBufferMemory: hybrid | Summaries can lose constraints or accumulate hallucinations; they are not an audit log. |
Design review exercise: Memory types
- Foundation: implement or demonstrate ConversationBufferMemory: full history with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine ConversationBufferMemory: full history with ConversationBufferWindowMemory: last K turns. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for ConversationSummaryBufferMemory: hybrid. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
3. Document loaders & splitters
The Document loaders & splitters unit begins with PyPDFLoader/Docx2txt/CSV/WebBaseLoader: Loaders normalize source documents and splitters produce retrievable chunks with provenance metadata. Record document, page/section, offsets, parser version, and content hash. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
Requirements, ownership, and trade-offs: Document loaders & splitters
| Concept | Meaning | Engineering decision |
|---|---|---|
| PyPDFLoader/Docx2txt/CSV/WebBaseLoader | Loaders normalize source documents and splitters produce retrievable chunks with provenance metadata. | Record document, page/section, offsets, parser version, and content hash. |
| RecursiveCharacterTextSplitter (recommended default) | Loaders normalize source documents and splitters produce retrievable chunks with provenance metadata. | Record document, page/section, offsets, parser version, and content hash. |
| TokenTextSplitter and MarkdownHeaderTextSplitter | Loaders normalize source documents and splitters produce retrievable chunks with provenance metadata. | Record document, page/section, offsets, parser version, and content hash. |
| chunk size vs overlap tradeoffs | Loaders normalize source documents and splitters produce retrievable chunks with provenance metadata. | Record document, page/section, offsets, parser version, and content hash. |
Critical path and failure behavior: Document loaders & splitters
PyPDFLoader/Docx2txt/CSV/WebBaseLoader. Recursive splitters try separators in priority order; token splitters bound model input more directly; header splitters preserve document hierarchy.
RecursiveCharacterTextSplitter (recommended default). Recursive splitters try separators in priority order; token splitters bound model input more directly; header splitters preserve document hierarchy.
TokenTextSplitter and MarkdownHeaderTextSplitter. Recursive splitters try separators in priority order; token splitters bound model input more directly; header splitters preserve document hierarchy.
chunk size vs overlap tradeoffs. Recursive splitters try separators in priority order; token splitters bound model input more directly; header splitters preserve document hierarchy.
Read these as one system: PyPDFLoader/Docx2txt/CSV/WebBaseLoader establishes the starting contract, RecursiveCharacterTextSplitter (recommended default) changes how that contract is executed or represented, and chunk size vs overlap tradeoffs exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
Designs that fail under real load: Document loaders & splitters
| Risk | Why it matters |
|---|---|
| PyPDFLoader/Docx2txt/CSV/WebBaseLoader | Fixed characters do not equal fixed tokens, and extraction order can differ from visual order in PDFs. |
| RecursiveCharacterTextSplitter (recommended default) | Fixed characters do not equal fixed tokens, and extraction order can differ from visual order in PDFs. |
| TokenTextSplitter and MarkdownHeaderTextSplitter | Fixed characters do not equal fixed tokens, and extraction order can differ from visual order in PDFs. |
| chunk size vs overlap tradeoffs | Fixed characters do not equal fixed tokens, and extraction order can differ from visual order in PDFs. |
Design review exercise: Document loaders & splitters
- Foundation: implement or demonstrate PyPDFLoader/Docx2txt/CSV/WebBaseLoader with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine PyPDFLoader/Docx2txt/CSV/WebBaseLoader with RecursiveCharacterTextSplitter (recommended default). Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for chunk size vs overlap tradeoffs. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
4. Output parsers
The Output parsers unit begins with StrOutputParser: An output parser turns model text into an explicit application type and rejects malformed or semantically invalid results. Prefer provider schema support and validate business invariants after shape validation. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
Requirements, ownership, and trade-offs: Output parsers
| Concept | Meaning | Engineering decision |
|---|---|---|
| StrOutputParser | An output parser turns model text into an explicit application type and rejects malformed or semantically invalid results. | Prefer provider schema support and validate business invariants after shape validation. |
| JsonOutputParser with Pydantic schema | Pydantic models parse untrusted input into typed values and serialize explicit output contracts. | Separate create, update, internal, and public schemas. |
| RetryOutputParser for malformed output | An output parser turns model text into an explicit application type and rejects malformed or semantically invalid results. | Prefer provider schema support and validate business invariants after shape validation. |
Critical path and failure behavior: Output parsers
StrOutputParser. Structured-output modes constrain generation where supported; otherwise parsing and a bounded repair attempt happen after generation.
JsonOutputParser with Pydantic schema. Pydantic v2 compiles a Core Schema evaluated by pydantic-core. Field validation precedes model-level invariants; from_attributes reads object attributes.
RetryOutputParser for malformed output. Structured-output modes constrain generation where supported; otherwise parsing and a bounded repair attempt happen after generation.
Read these as one system: StrOutputParser establishes the starting contract, JsonOutputParser with Pydantic schema changes how that contract is executed or represented, and RetryOutputParser for malformed output exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
Designs that fail under real load: Output parsers
| Risk | Why it matters |
|---|---|
| StrOutputParser | Repeated repair can hide a bad prompt and increase latency and cost. |
| JsonOutputParser with Pydantic schema | Validation can coerce values unless strictness is configured; never expose secrets through a broad response model. |
| RetryOutputParser for malformed output | Repeated repair can hide a bad prompt and increase latency and cost. |
Design review exercise: Output parsers
- Foundation: implement or demonstrate StrOutputParser with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine StrOutputParser with JsonOutputParser with Pydantic schema. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for RetryOutputParser for malformed output. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
5. Custom extensions
The Custom extensions unit begins with custom BaseLoader lazy_load contract: Loaders normalize source documents and splitters produce retrievable chunks with provenance metadata. Record document, page/section, offsets, parser version, and content hash. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
Requirements, ownership, and trade-offs: Custom extensions
| Concept | Meaning | Engineering decision |
|---|---|---|
| custom BaseLoader lazy_load contract | Loaders normalize source documents and splitters produce retrievable chunks with provenance metadata. | Record document, page/section, offsets, parser version, and content hash. |
| custom RunnableLambda transform | LCEL composes components implementing a common Runnable interface into sequences, maps, parallel branches, retries, and streaming pipelines. | Keep transformations explicit and attach dataset/evaluation version tags. |
| custom memory/history selection policy | A history-selection policy chooses which canonical conversation events, summaries, retrieved facts, and tool results enter the next model context. | Use a custom policy when fixed last-K memory loses important constraints or wastes tokens on irrelevant turns. |
| callback and tracing metadata hygiene | LangChain callbacks observe runnable starts, streams, tool calls, results, and errors; metadata hygiene limits what those traces record and how runs can be correlated. | Attach prompt/dataset/application versions and safe correlation IDs, sample deliberately, and redact secrets, raw credentials, and unnecessary document content. |
Critical path and failure behavior: Custom extensions
custom BaseLoader lazy_load contract. Recursive splitters try separators in priority order; token splitters bound model input more directly; header splitters preserve document hierarchy.
custom RunnableLambda transform. The pipe operator constructs a graph; invoke, batch, stream, and async variants drive it. Tracing records run trees and metadata.
custom memory/history selection policy. The application stores durable events separately, filters them by tenant and task, applies a token budget, preserves recent constraints, and may create a versioned lossy summary for older context.
callback and tracing metadata hygiene. Callbacks receive nested run identifiers, tags, inputs, outputs, token usage, and exceptions. A tracing backend persists that tree, so redaction and tenant/project scoping must occur before export.
Read these as one system: custom BaseLoader lazy_load contract establishes the starting contract, custom RunnableLambda transform changes how that contract is executed or represented, and callback and tracing metadata hygiene exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
A concrete design decision: Custom extensions
1key=lambda item: item.scoreThis Custom extensions slice makes custom BaseLoader lazy_load contract observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward callback and tracing metadata hygiene, predict its behavior for empty, invalid, repeated, and large input.
Designs that fail under real load: Custom extensions
| Risk | Why it matters |
|---|---|
| custom BaseLoader lazy_load contract | Fixed characters do not equal fixed tokens, and extraction order can differ from visual order in PDFs. |
| custom RunnableLambda transform | A chain abstraction does not remove provider failures or the need to validate outputs. |
| custom memory/history selection policy | Treating a model-written summary as authoritative memory can preserve hallucinations and discard permissions, corrections, or audit evidence. |
| callback and tracing metadata hygiene | Tracing every prompt and tool payload by default can create a durable cross-tenant data leak and unexpected retention cost. |
Design review exercise: Custom extensions
- Foundation: implement or demonstrate custom BaseLoader lazy_load contract with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine custom BaseLoader lazy_load contract with custom RunnableLambda transform. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for callback and tracing metadata hygiene. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
Complete worked example
This example integrates the chapter rather than demonstrating an isolated method.
1from langchain_core.output_parsers import StrOutputParser2from langchain_core.runnables import RunnableParallel, RunnablePassthrough3
4context = RunnableParallel(5 semantic=semantic_retriever,6 lexical=lexical_retriever,7) | reciprocal_rank_fusion8
9chain = (10 {"question": RunnablePassthrough(), "context": context}11 | answer_prompt12 | model.with_retry(stop_after_attempt=3)13 | StrOutputParser()14)15
16answer = await chain.ainvoke("How is termination handled?")Expected result
1Lexical and semantic branches run concurrently, fuse candidates, and feed one traced, retry-bounded generation.Line-by-line reading
| Line | Code | Explanation | |
|---|---|---|---|
| 1 | from langchain_core.output_parsers import StrOutputParser | Imports the named dependency; import executes the module once per interpreter cache and binds selected names here. | |
| 2 | from langchain_core.runnables import RunnableParallel, RunnablePassthrough | Imports the named dependency; import executes the module once per interpreter cache and binds selected names here. | |
| 4 | context = RunnableParallel( | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. | |
| 5 | semantic=semantic_retriever, | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. | |
| 6 | lexical=lexical_retriever, | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. | |
| 7 | `) \ | reciprocal_rank_fusion` | Implements the next python statement in the example's data flow. |
| 9 | chain = ( | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. | |
| 10 | {"question": RunnablePassthrough(), "context": context} | Implements the next python statement in the example's data flow. | |
| 11 | `\ | answer_prompt` | Implements the next python statement in the example's data flow. |
| 12 | `\ | model.with_retry(stop_after_attempt=3)` | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 13 | `\ | StrOutputParser()` | Implements the next python statement in the example's data flow. |
| 14 | ) | Implements the next python statement in the example's data flow. | |
| 16 | answer = await chain.ainvoke("How is termination handled?") | Starts or resumes asynchronous I/O and yields control until the awaited operation completes. |
Step-by-step execution
- Deterministic code validates the request, identity, tenant, budgets, schemas, and permitted tools before assembling model context.
- Retrieval or memory selection chooses bounded, provenance-bearing evidence; tokenization converts the assembled messages into the model's input sequence.
- The provider generates or streams tokens, or proposes typed tool arguments; application code validates every output and executes only authorized bounded actions.
- Parsers and business rules accept, repair once under policy, route, or reject the result; citations and state transitions are persisted with model, prompt, index, and dataset versions.
- Offline evaluation and production telemetry measure retrieval, faithfulness, latency, token cost, tool errors, safety outcomes, and regressions by cohort.
Common mistakes and professional corrections
| Area | Common failure | Better engineering choice |
|---|---|---|
| LCEL (LangChain Expression Language) | A chain abstraction does not remove provider failures or the need to validate outputs. | Keep transformations explicit and attach dataset/evaluation version tags. |
| Memory types | Summaries can lose constraints or accumulate hallucinations; they are not an audit log. | Store canonical conversation events separately and derive prompt memory per task. |
| Document loaders & splitters | Fixed characters do not equal fixed tokens, and extraction order can differ from visual order in PDFs. | Record document, page/section, offsets, parser version, and content hash. |
| Output parsers | Repeated repair can hide a bad prompt and increase latency and cost. | Prefer provider schema support and validate business invariants after shape validation. |
| Custom extensions | Fixed characters do not equal fixed tokens, and extraction order can differ from visual order in PDFs. | Record document, page/section, offsets, parser version, and content hash. |
Interview and review notes
- Define the central abstraction without naming a library function.
- Trace one request, call, query, message, render, or state transition from input to observable result.
- Compare two alternatives from this chapter by guarantee, cost, and failure behavior.
- Explain the most likely production bug and the test or metric that reveals it.
- State what remains authoritative after process loss, retry, reconnect, or deployment.
Practice set
Easy
- Define every bold term in the concept tables in one precise sentence.
- Reproduce the focused examples and annotate the value or state after each important line.
- Explain the chapter progression diagram aloud in two minutes.
Medium
- Replace one convenient default with an explicit policy for validation, timeout, ordering, pagination, cleanup, or error handling.
- Write a negative test for each topic group.
- Compare the measured behavior before and after one justified change.
Hard
- Combine all topic groups into one thin vertical slice.
- Inject a realistic failure at the most important external boundary and prove recovery.
- Write a one-page design note covering ownership, trade-offs, security, observability, and rollback.
Chapter submission
Submit:
- source code or reproducible commands;
- automated tests plus one deliberately failing-before-fix test;
- captured output, query plan, trace, screenshot, or metric;
- a 300–500 word explanation of the execution flow and one rejected alternative;
- a short README with setup, versions, limitations, and cleanup steps.
- Continue with the Document Chat Assistant project workshop.
Self-review rubric
| Dimension | Beginning | Competent | Professional |
|---|---|---|---|
| Explanation | Names APIs | Explains behavior | Connects guarantees, internals, and trade-offs |
| Implementation | Happy path only | Validated and tested | Clear ownership, failure recovery, and cleanup |
| Evidence | Manual claim | Repeatable output | Tests plus meaningful measurement or inspection |
| Communication | Steps missing | Reproducible README | Decisions, limits, and alternatives are explicit |
Roadmap coverage checklist
| - [ ] LCEL (LangChain Expression Language): pipe operator ( | ) for composing chains |
|---|
- To do: LCEL (LangChain Expression Language): RunnableSequence/Parallel/Passthrough
- To do: LCEL (LangChain Expression Language): invoke/stream/batch/ainvoke interface
- To do: LCEL (LangChain Expression Language): fallbacks + retries in LCEL
- To do: LCEL (LangChain Expression Language): LangSmith tracing setup
- To do: Memory types: ConversationBufferMemory: full history
- To do: Memory types: ConversationBufferWindowMemory: last K turns
- To do: Memory types: ConversationSummaryMemory: summarize old turns
- To do: Memory types: ConversationSummaryBufferMemory: hybrid
- To do: Document loaders & splitters: PyPDFLoader/Docx2txt/CSV/WebBaseLoader
- To do: Document loaders & splitters: RecursiveCharacterTextSplitter (recommended default)
- To do: Document loaders & splitters: TokenTextSplitter and MarkdownHeaderTextSplitter
- To do: Document loaders & splitters: chunk size vs overlap tradeoffs
- To do: Output parsers: StrOutputParser
- To do: Output parsers: JsonOutputParser with Pydantic schema
- To do: Output parsers: RetryOutputParser for malformed output
- To do: Custom extensions: custom BaseLoader lazy_load contract
- To do: Custom extensions: custom RunnableLambda transform
- To do: Custom extensions: custom memory/history selection policy
- To do: Custom extensions: callback and tracing metadata hygiene
Quick revision
- LCEL (LangChain Expression Language): connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Memory types: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Document loaders & splitters: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Output parsers: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Custom extensions: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Re-read the worked-example execution trace instead of memorizing isolated syntax.
- If you cannot name the owner of state and cleanup, the design is not yet complete.
Mastery check
How well can you recall this?
Finished this lesson?