Project Workshop — Document Chat Assistant
This is a portfolio submission, not a copy-and-run tutorial. A reviewer must be able to clone it, configure it without guessing, execute the critical path, observe a deliberate failure, run the tests, and understand the most important…
- What you are building
- Architecture
- Acceptance criteria
- Suggested repository structure
- Build plan: vertical slices
LangChain · LCEL · pgvector · FastAPI · OpenAI
Expected effort: 4–7 focused hours · Minimum meaningful tests: 12What you are building
This is a portfolio submission, not a copy-and-run tutorial. A reviewer must be able to clone it, configure it without guessing, execute the critical path, observe a deliberate failure, run the tests, and understand the most important design decision from the README.
Architecture
Critical interaction
Ownership table
| Boundary | Owns | Must not own |
|---|---|---|
| Interface | Parsing, protocol validation, identity extraction, status or presentation mapping | Core business invariants |
| Application/domain | Authorization inputs, state transitions, orchestration, transaction intent | Framework globals or raw transport objects |
| Repository/gateway | One persistence or external protocol, bounded retries, error translation | Product policy |
| Background/UI projection | Recoverable derived state and delivery progress | Hidden authoritative truth |
| Operations | Configuration, health, deployment, telemetry, recovery | Business decisions encoded only in dashboards |
Acceptance criteria
| ID | Required behavior | Evidence | |
|---|---|---|---|
| AC-1.1 | pipe operator (\ | ) for composing chains produces the specified behavior inside LCEL (LangChain Expression Language) | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-1.2 | RunnableSequence/Parallel/Passthrough produces the specified behavior inside LCEL (LangChain Expression Language) | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check | |
| AC-1.3 | invoke/stream/batch/ainvoke interface produces the specified behavior inside LCEL (LangChain Expression Language) | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check | |
| AC-1.4 | fallbacks + retries in LCEL produces the specified behavior inside LCEL (LangChain Expression Language) | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check | |
| AC-1.5 | LangSmith tracing setup produces the specified behavior inside LCEL (LangChain Expression Language) | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check | |
| AC-2.1 | ConversationBufferMemory: full history produces the specified behavior inside Memory types | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check | |
| AC-2.2 | ConversationBufferWindowMemory: last K turns produces the specified behavior inside Memory types | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check | |
| AC-2.3 | ConversationSummaryMemory: summarize old turns produces the specified behavior inside Memory types | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check | |
| AC-2.4 | ConversationSummaryBufferMemory: hybrid produces the specified behavior inside Memory types | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check | |
| AC-3.1 | PyPDFLoader/Docx2txt/CSV/WebBaseLoader produces the specified behavior inside Document loaders & splitters | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check | |
| AC-3.2 | RecursiveCharacterTextSplitter (recommended default) produces the specified behavior inside Document loaders & splitters | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check | |
| AC-3.3 | TokenTextSplitter and MarkdownHeaderTextSplitter produces the specified behavior inside Document loaders & splitters | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check | |
| AC-3.4 | chunk size vs overlap tradeoffs produces the specified behavior inside Document loaders & splitters | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check | |
| AC-4.1 | StrOutputParser produces the specified behavior inside Output parsers | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check | |
| AC-4.2 | JsonOutputParser with Pydantic schema produces the specified behavior inside Output parsers | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check | |
| AC-4.3 | RetryOutputParser for malformed output produces the specified behavior inside Output parsers | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check | |
| AC-5.1 | custom BaseLoader lazy_load contract produces the specified behavior inside Custom extensions | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check | |
| AC-5.2 | custom RunnableLambda transform produces the specified behavior inside Custom extensions | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check | |
| AC-5.3 | custom memory/history selection policy produces the specified behavior inside Custom extensions | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check | |
| AC-5.4 | callback and tracing metadata hygiene produces the specified behavior inside Custom extensions | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
Suggested repository structure
1project/2├── app/3│ ├── main.py4│ ├── api/{routes.py,dependencies.py}5│ ├── domain/{models.py,services.py,errors.py}6│ ├── repositories/7│ ├── schemas/8│ ├── workers/9│ └── observability.py10├── migrations/11├── tests/{unit,integration,contract}/12├── pyproject.toml13├── Dockerfile14└── compose.yamlBuild plan: vertical slices
| Milestone | Capability | First implementation | Exit condition | |
|---|---|---|---|---|
| 1 | LCEL (LangChain Expression Language) | pipe operator (\ | ) for composing chains; RunnableSequence/Parallel/Passthrough; invoke/stream/batch/ainvoke interface | Demonstration plus focused tests |
| 2 | Memory types | ConversationBufferMemory: full history; ConversationBufferWindowMemory: last K turns; ConversationSummaryMemory: summarize old turns | Demonstration plus focused tests | |
| 3 | Document loaders & splitters | PyPDFLoader/Docx2txt/CSV/WebBaseLoader; RecursiveCharacterTextSplitter (recommended default); TokenTextSplitter and MarkdownHeaderTextSplitter | Demonstration plus focused tests | |
| 4 | Output parsers | StrOutputParser; JsonOutputParser with Pydantic schema; RetryOutputParser for malformed output | Demonstration plus focused tests | |
| 5 | Custom extensions | custom BaseLoader lazy_load contract; custom RunnableLambda transform; custom memory/history selection policy | Demonstration plus focused tests | |
| 6 | Hardening and delivery | Security, recovery, telemetry, performance, documentation | Full acceptance suite and recorded demonstration |
For each milestone, first create a failing acceptance test or a reproducible command. Implement the thinnest path to an observable result, add the nearest durable invariant, inject one expected failure, and refactor only after evidence protects the behavior.
Reference vertical slice
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.Code 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. |
Risk register
| Area | Failure to reproduce | Required design response |
|---|---|---|
| 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 | Tracing every prompt and tool payload by default can create a durable cross-tenant data leak and unexpected retention cost. | Attach prompt/dataset/application versions and safe correlation IDs, sample deliberately, and redact secrets, raw credentials, and unnecessary document content. |
Engineering checklist for this stack
- To do: begin from requirements and quantitative SLOs
- To do: assign one owner to authoritative state
- To do: make consistency and ordering scope explicit
- To do: design degraded behavior and reconciliation
- To do: record decisions and migration boundaries
Test strategy
Implement at least 12 meaningful cases. A long list of shallow happy-path tests does not satisfy the requirement.
| Risk class | Minimum | Examples |
|---|---|---|
| Happy path and contract | 2 | Correct output, status/schema, durable state |
| Validation and boundaries | 2 | Empty, malformed, extreme, unsupported transition |
| Authorization or trust boundary | 1 | Missing identity, wrong tenant/role, injection or unsafe content |
| Failure and recovery | 2 | Timeout, retry, rollback, reconnect, dependency outage |
| Duplicate or concurrency | 1 | Same identity twice, racing update, redelivery |
| Performance and operations | 4 | Query bound, lag, p95, resource limit, telemetry |
Representative test scaffold
1@pytest.mark.anyio2async def test_duplicate_request_is_idempotent(client, auth_headers):3 headers = {**auth_headers, "Idempotency-Key": "stable-1"}4 first = await client.post("/resources", json={"name": "one"}, headers=headers)5 second = await client.post("/resources", json={"name": "one"}, headers=headers)6 assert first.status_code == 2017 assert second.status_code in {200, 201}8 assert first.json()["id"] == second.json()["id"]Failure drills
- Stop the primary external dependency during the critical path. Capture the failure, cleanup, telemetry, and recovery.
- Repeat the same operation with the same stable identity. Prove one logical outcome or document why repetition is forbidden.
- Crash after durable state changes but before the response, acknowledgement, or projection. Re-run and reconcile.
- Submit the largest supported input and one slightly larger input.
- Remove one permission and prove denial without state change or information leakage.
- Roll back the change or restore the dependency, then run a smoke test and reconciliation check.
Performance experiment
State the dataset, payload distribution, concurrency, rate, duration, cache state, and resource limits before measuring. Publish p50, p95, p99, throughput, error rate, and the technology-specific correctness signal such as query count, consumer lag, duplicate effects, rendered updates, token cost, or recall. Change one variable at a time and retain raw output.
Submission package
- Complete source with a locked/reproducible environment.
- README.md with problem, architecture, setup, commands, configuration, assumptions, and trade-offs.
- Acceptance and risk-focused tests with a short explanation of what mocks intentionally do not cover.
- One design record explaining the most consequential choice and a rejected alternative.
- Security notes, sample non-secret configuration, and cleanup commands.
- A demonstration record: terminal transcript, screenshots, trace, query plan, or metrics dashboard.
- A 5–8 minute walkthrough following input → validation → state → failure → evidence.
Grading rubric
| Dimension | Weight | Full-credit evidence |
|---|---|---|
| Product behavior | 25 | Acceptance criteria pass through real public boundaries |
| Architecture and ownership | 20 | Responsibilities and state authority are explicit |
| Tests and recovery | 20 | Important negative, duplicate, concurrent, and outage cases pass |
| Security and data correctness | 15 | Least privilege, validation, constraints, and secret handling are demonstrated |
| Performance and operations | 10 | Reproducible measurement, useful telemetry, and rollback/recovery |
| Documentation and explanation | 10 | A new reviewer can reproduce and defend the result |
Mastery check
How well can you recall this?
Finished this lesson?