Guide / AI engineering Most asked
AI design walkthroughs: code assistant, AI search, document processing
Three complete AI system designs: an IDE code assistant, a Perplexity-style answer engine with citations, and an intelligent document-processing pipeline with human review.
Each walkthrough uses the same frame: requirements and quality metric → latency/cost budget → architecture → key deep dives → evaluation → failure modes → follow-ups.
Fundamentals (the designs)#
1. Code assistant (inline completion + chat in an IDE)#
Requirements. Inline completions (< 300 ms to first token), chat with repository awareness, edits across files, explain/fix errors. Metrics: acceptance rate of suggestions, completion latency, chat task success, bugs introduced. Privacy: source code is confidential.
Architecture.
IDE plugin → context builder (current file, cursor, imports, recent edits, open tabs)
→ gateway (auth, rate limit, routing) → small fast code model (completion; FIM prompt)
→ chat/agent service → strong model + tools (search repo, read file, run tests in sandbox)
Repo indexer: chunk code by AST/function → embeddings + BM25 + symbol graph → vector store (per repo/tenant)
Deep dives.
- Fill-in-the-middle (FIM) prompts: the model sees code before and after the cursor; keep prompts short to hit the latency budget. Use a small specialised model for completions, a stronger one for chat.
- Context selection is the quality lever: rank snippets by relevance: same file, imported symbols, recently edited files, semantic search of the repo, definitions of referenced symbols (language server/tree-sitter), test files. Respect the token budget; dedupe.
- Indexing: chunk by syntactic units, incremental updates on file save/git change, per-branch awareness, ignore secrets and generated files (
.env, lockfiles), enforce permissions (the user’s repo access). - Latency tricks: debounce keystrokes, cancel stale requests, speculative/predictive prefetch, prefix caching of the stable file context, streaming, local caching of recent completions, speculative decoding on the server.
- Agentic edits: plan → read files → propose diff → apply in a sandbox → run tests/linters → show diff for approval; cap steps; never auto-run destructive commands.
- Evaluation: offline pass@k on held-out functions/test generation, repo-level benchmarks (SWE-bench-style), online acceptance rate and retention, regression suite of real prompts; track suggestion correctness, not just acceptance.
- Safety: secret scanning of prompts and completions, license/copyright filters (match against public code), prompt injection from repo content or issue text (treat as data), no telemetry of code without consent.
- Failure modes: hallucinated APIs (ground with symbol index, run compile/type checks), stale index, slow completions (fall back to cached/no suggestion), context overflow on large files.
2. AI search / answer engine (Perplexity-style)#
Requirements. Answer open-ended questions with cited sources, fresh information, follow-up questions, p50 time-to-first-token ~1–2 s, streaming. Metrics: answer correctness and groundedness, citation accuracy, latency, cost per query.
Architecture.
Query → understanding (rewrite, intent, decompose into sub-queries, safety check)
→ retrieval: web search API / own index (hybrid BM25 + dense), fetch pages in parallel, extract main text
→ rerank + dedupe + snippet selection (token budget)
→ generation (cites sources by id) → streaming answer + citation validation → follow-ups
Caches: query → results, URL → extracted text; embeddings of popular queries
Deep dives.
- Query planning: rewrite for search, split multi-part questions, decide whether to search at all (simple chat vs fresh facts), time sensitivity.
- Retrieval at web scale: use a search provider or an in-house crawler plus index (More designs: crawler); fetch top 10–20 pages with strict timeouts and in parallel; extract article text (boilerplate removal); chunk and rerank with a cross-encoder to pick ~5–10 passages.
- Grounded generation: instruct “answer only from the sources, cite
[n], say unknown if unsupported”; post-check: verify each citation actually supports its claim (NLI model or LLM judge) and drop unsupported sentences; show source snippets. - Latency budget: search 300–500 ms, fetch+extract 500–800 ms (parallel, with early cut-off), rerank 100 ms, first token ~600 ms; stream tokens while still doing background work (related questions). Hedge slow fetches.
- Cost: many input tokens (sources) per query; use cheaper models for rewriting/reranking, cache aggressively (popular queries, fetched pages with TTL), prefix caching, limit sources.
- Trust and safety: source quality scoring/domain allowlists for sensitive topics (health, finance), prompt-injection defence for fetched pages (treat as data, strip instructions, never give web content tool access), copyright and robots compliance, bias and freshness handling.
- Evaluation: human-labelled question set with expected facts and sources; metrics for answer accuracy, citation precision/recall, faithfulness, freshness; adversarial sets (misinformation, injection pages); online feedback and spot audits.
- Failure modes: SEO spam sources, paywalled pages, conflicting sources (present both), stale cache for breaking news (short TTL by topic), search provider outage (secondary provider, degraded answer from the model with a warning).
3. Intelligent document processing (invoices, contracts, forms)#
Requirements. Ingest PDFs/scans/emails, extract structured fields (vendor, amount, dates, line items), validate against business rules, route low-confidence cases to humans, write into ERP. Metrics: field-level accuracy, straight-through-processing (STP) rate, cost per document, turnaround time. Volume example: 200K docs/month.
Architecture.
Ingestion (email/API/S3) → classification (doc type) → OCR/layout (for scans) → extraction (LLM with schema / vision model)
→ validation (schema, checksums, totals = sum of lines, vendor master data, duplicates) → confidence scoring
→ auto-approve ── high confidence ──► ERP/DB (idempotent write)
└─ low confidence / rule fail ──► human review UI → corrections → training/eval data
Deep dives.
- Pipeline stages with queues (Kafka/SQS) so each stage scales independently and retries safely; idempotency keyed by document hash.
- Extraction: layout-aware OCR for scans, then a model with a JSON schema / structured output; for complex documents use a multimodal model on page images; chunk long contracts and merge results; ask for evidence spans (page + bounding box or quote) per field to enable verification and reviewer UI.
- Validation is the safety net: arithmetic consistency (line items sum to total, tax rates), format checks (dates, IBAN), master-data lookups (known vendor, PO exists), duplicate detection (same vendor + invoice number + amount), cross-field rules. Failing validation lowers confidence or routes to review.
- Confidence: combine model self-reported confidence (weak), validation results, agreement between two extraction passes or two models, and per-field historical accuracy; calibrate thresholds so the auto-approve set has an error rate below the business tolerance.
- Human-in-the-loop: reviewer UI shows the document with highlighted evidence; corrections are logged as labelled data to grow the eval set and fine-tune (or add few-shot examples) for weak vendors/templates.
- Cost optimisation: classify cheaply, use a small model for easy templates, big model for hard ones; cache by template; skip OCR for digital PDFs; batch processing for non-urgent documents.
- Evaluation: field-level precision/recall against a labelled set per document type and vendor; track STP rate and error rate in production (sample audits of auto-approved docs); drift alerts when new templates appear.
- Failure modes: low-quality scans (pre-processing, ask for resubmission), multi-page tables split across pages, prompt injection inside documents (extract only; never let document text drive actions), PII (encrypt, retention policy, restricted access) (AI safety and compliance), duplicated submissions.
Most asked questions#
1. How do you get low latency for code completion? Small specialised model, short FIM prompt with selected context, streaming, request cancellation and debouncing, prefix caching and edge-close serving.
2. How do you select context for a code assistant? Combine local context (file, cursor, recent edits) with retrieval (semantic + keyword + symbol graph), ranked and trimmed to the token budget.
3. How do you ensure an AI search answer is grounded? Retrieve and rerank sources, force citations, verify claims against sources, refuse when evidence is missing.
4. How do you build document extraction you can trust? Schema-constrained extraction with evidence, deterministic validation, calibrated confidence, human review for the uncertain, and continuous evaluation on audited samples.
5. How do you measure success for each? Acceptance rate and task success (code), citation accuracy and groundedness (search), field accuracy and STP rate (documents).
Senior-level questions#
1. “The assistant suggests code with a vulnerability or a copied licensed snippet.” Add static analysis on suggestions, license-match filters, secure-coding examples and policies in prompts, evaluation on security benchmarks, user-visible warnings and an opt-out for public-code matches.
2. “Answer engine cites a source that does not support the claim.” Add a citation verification step (entailment check), require quote-level evidence, penalise in evals, and show snippets; lower-temperature, smaller claim granularity.
3. “Auto-approved invoices contain 0.5% errors; finance wants 0.05%.” Tighten thresholds and validations, add a second independent extraction and require agreement, sample audits with feedback, vendor-specific rules, and measure the cost trade-off between review labour and error cost.
4. “Scale the code index to 50K repos with branch awareness.” Shard by repo, incremental indexing from git events, content-hash dedupe of chunks across branches, tiered storage (hot repos in memory), per-tenant isolation, and query-time branch filters.
5. “Search provider is down or rate limited.” Fail over to a second provider, serve cached results for popular queries, return a model-only answer with a clear freshness disclaimer, and queue background refresh.
Quiz#
1. Why use a small model for inline completions?
Latency is critical (hundreds of ms); small specialised models are fast and cheap enough to run per keystroke.
2. What is the best defence against hallucinated function names in code suggestions?
Ground in the repository symbol index and verify with compilation, type checking or tests.
3. How do you verify a citation?
Check that the cited passage entails the claim (NLI or judge model) and drop or revise unsupported statements.
4. What are the two safety nets in document extraction?
Deterministic validation rules and human review for low-confidence cases, plus audits of auto-approved samples.
5. Why store evidence spans with extracted fields?
They let reviewers verify quickly and enable automatic checks that the value appears in the document.