Project Workshop — Legal Document Q&A (RAG)
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 · pgvector · BGE-M3 · BGE-Reranker · RAGAS · FastAPI
Expected effort: 5–8 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 | fixed-size vs semantic vs recursive chunking produces the specified behavior inside Chunking & embedding strategies | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-1.2 | document-specific: markdown headers/HTML/code produces the specified behavior inside Chunking & embedding strategies | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-1.3 | OpenAI text-embedding-3-small/large dimensions+cost produces the specified behavior inside Chunking & embedding strategies | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-1.4 | BGE-M3 and E5-large open source alternatives produces the specified behavior inside Chunking & embedding strategies | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-1.5 | batching embeddings efficiently produces the specified behavior inside Chunking & embedding strategies | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.1 | BM25 keyword search (TF-IDF) produces the specified behavior inside Hybrid search (BM25 + semantic) | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.2 | Reciprocal Rank Fusion (RRF) for score merging produces the specified behavior inside Hybrid search (BM25 + semantic) | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.3 | weighted hybrid: α×semantic + (1-α)×BM25 produces the specified behavior inside Hybrid search (BM25 + semantic) | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.4 | PostgreSQL ts_vector + pgvector combined produces the specified behavior inside Hybrid search (BM25 + semantic) | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.1 | cross-encoder rerankers: Cohere Rerank/BGE-Reranker produces the specified behavior inside Re-ranking & evaluation | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.2 | two-stage: retrieve 50 → rerank → top 5 produces the specified behavior inside Re-ranking & evaluation | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.3 | RAGAS metrics: faithfulness/answer relevancy/context precision/recall produces the specified behavior inside Re-ranking & evaluation | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.4 | LLM-as-judge for answer quality produces the specified behavior inside Re-ranking & evaluation | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-4.1 | pgvector vs Pinecone vs Chroma vs Weaviate produces the specified behavior inside Vector store & embedding choices | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-4.2 | Matryoshka representation learning and dimension truncation produces the specified behavior inside Vector store & embedding choices | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-4.3 | metadata filtering and tenant isolation produces the specified behavior inside Vector store & embedding choices | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-4.4 | index build/update/delete and re-embedding cost produces the specified behavior inside Vector store & embedding choices | 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 | Chunking & embedding strategies | fixed-size vs semantic vs recursive chunking; document-specific: markdown headers/HTML/code; OpenAI text-embedding-3-small/large dimensions+cost | Demonstration plus focused tests |
| 2 | Hybrid search (BM25 + semantic) | BM25 keyword search (TF-IDF); Reciprocal Rank Fusion (RRF) for score merging; weighted hybrid: α×semantic + (1-α)×BM25 | Demonstration plus focused tests |
| 3 | Re-ranking & evaluation | cross-encoder rerankers: Cohere Rerank/BGE-Reranker; two-stage: retrieve 50 → rerank → top 5; RAGAS metrics: faithfulness/answer relevancy/context precision/recall | Demonstration plus focused tests |
| 4 | Vector store & embedding choices | pgvector vs Pinecone vs Chroma vs Weaviate; Matryoshka representation learning and dimension truncation; metadata filtering and tenant isolation | Demonstration plus focused tests |
| 5 | 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
1WITH semantic AS (2 SELECT id, ROW_NUMBER() OVER (ORDER BY embedding <=> :query) AS rank3 FROM chunks WHERE tenant_id = :tenant_id LIMIT 504), lexical AS (5 SELECT id, ROW_NUMBER() OVER (ORDER BY ts_rank_cd(search_vector, websearch_to_tsquery(:text)) DESC) AS rank6 FROM chunks7 WHERE tenant_id = :tenant_id AND search_vector @@ websearch_to_tsquery(:text)8 LIMIT 509)10SELECT id, SUM(score) AS rrf_score11FROM (12 SELECT id, 1.0 / (60 + rank) AS score FROM semantic13 UNION ALL14 SELECT id, 1.0 / (60 + rank) AS score FROM lexical15) candidates16GROUP BY id ORDER BY rrf_score DESC LIMIT 20;Expected result
1Returns tenant-filtered candidates ranked by reciprocal contributions from semantic and lexical retrieval.Code reading
| Line | Code | Explanation |
|---|---|---|
| 1 | WITH semantic AS ( | Begins a declarative database or protocol operation; subsequent lines refine its contract. |
| 2 | SELECT id, ROW_NUMBER() OVER (ORDER BY embedding <=> :query) AS rank | Begins a declarative database or protocol operation; subsequent lines refine its contract. |
| 3 | FROM chunks WHERE tenant_id = :tenant_id LIMIT 50 | Adds a relational selection, combination, ordering, bound, or returned-value rule to the statement. |
| 4 | ), lexical AS ( | Implements the next sql statement in the example's data flow. |
| 5 | SELECT id, ROW_NUMBER() OVER (ORDER BY ts_rank_cd(search_vector, websearch_to_tsquery(:text)) DESC) AS rank | Begins a declarative database or protocol operation; subsequent lines refine its contract. |
| 6 | FROM chunks | Adds a relational selection, combination, ordering, bound, or returned-value rule to the statement. |
| 7 | WHERE tenant_id = :tenant_id AND search_vector @@ websearch_to_tsquery(:text) | Adds a relational selection, combination, ordering, bound, or returned-value rule to the statement. |
| 8 | LIMIT 50 | Adds a relational selection, combination, ordering, bound, or returned-value rule to the statement. |
| 9 | ) | Implements the next sql statement in the example's data flow. |
| 10 | SELECT id, SUM(score) AS rrf_score | Begins a declarative database or protocol operation; subsequent lines refine its contract. |
| 11 | FROM ( | Adds a relational selection, combination, ordering, bound, or returned-value rule to the statement. |
| 12 | SELECT id, 1.0 / (60 + rank) AS score FROM semantic | Begins a declarative database or protocol operation; subsequent lines refine its contract. |
| 13 | UNION ALL | Implements the next sql statement in the example's data flow. |
| 14 | SELECT id, 1.0 / (60 + rank) AS score FROM lexical | Begins a declarative database or protocol operation; subsequent lines refine its contract. |
| 15 | ) candidates | Implements the next sql statement in the example's data flow. |
| 16 | GROUP BY id ORDER BY rrf_score DESC LIMIT 20; | Adds a relational selection, combination, ordering, bound, or returned-value rule to the statement. |
Risk register
| Area | Failure to reproduce | Required design response |
|---|---|---|
| Chunking & embedding strategies | One oversized batch can exceed memory or API limits; retrying a partially stored batch without stable IDs can duplicate or mismatch records. | Batch by both item count and token budget, use strict identity/order checks, and checkpoint progress for restartable ingestion. |
| Hybrid search (BM25 + semantic) | Applying inconsistent analyzers to indexed text and queries or using stop-word rules blindly can remove the only discriminating evidence. | Keep lexical search for names, codes, quotations, rare terminology, and exact legal language that embeddings may blur. |
| Re-ranking & evaluation | The term evaluation does not mean Redis EVAL; one aggregate score can hide regressions on rare or safety-critical question groups. | Evaluate retrieval separately from generation, retain per-question evidence, and gate prompt/model/index changes against baselines and latency budgets. |
| Vector store & embedding choices | Mixing vector versions or applying tenant filters after retrieval can return incorrect or unauthorized results. | Benchmark recall and filtered latency with tenant-realistic data and plan blue-green re-embedding when the model changes. |
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?