Overview

12 Designing LLM-powered systems

This chapter explains how large language models extend, rather than replace, established MLOps foundations. Core platform capabilities—containerization, Kubernetes orchestration, CI/CD, and system monitoring—remain essential, but LLM applications introduce new operational realities: non-deterministic outputs that break exact-match testing, token and context-window budgeting, multi-step reasoning chains that require traceability, prompt engineering as a versioned, testable artifact, and safety considerations that go beyond accuracy. The economic model also shifts to token-based usage, pushing teams to manage latency, quality, and cost together. The message is clear: LLMOps is an evolution of proven ML engineering principles adapted to the unique variability, scale, and risk profile of generative systems.

To make these ideas concrete, the chapter builds DakkaBot, an enterprise RAG assistant for company documentation. It covers the full stack: ingesting and chunking documents, creating asymmetric embeddings for documents vs. queries, indexing with a vector database (e.g., FAISS), and retrieving semantically relevant context. The augmentation step assembles and formats that context for the LLM, while generation is guided by carefully constructed prompts and tuned sampling parameters (often with low temperature for consistency). LangChain provides interchangeable, production-ready components and orchestration; LangGraph is highlighted for more complex, branching workflows. The system is wrapped in a chat UI with Chainlit, delivering streaming responses, source attribution, and robust error handling. Throughout, the chapter emphasizes composability, token-budget management, prompt/version governance, and seamless fit with existing infrastructure, from autoscaling to artifact tracking.

Production readiness centers on observability, safety, and cost control. The chapter introduces LLM-specific tracing with LangFuse to capture retrieval quality, prompt inputs, token usage, latency breakdowns, and conversation-level analytics—enabling semantic evaluation over brittle string comparisons. It prescribes versioning for prompts and retrieval parameters, A/B testing of variants, and governance over model/provider choices. Security guardrails address prompt injection, jailbreaks, and leakage risks, complemented by adversarial testing tools and input validation. Operational hardening includes rate limiting, retries, semantic caching, fallbacks across providers/models, and index versioning with rollback. By combining these patterns—composable RAG architecture, streaming UX, prompt and artifact management, and deep observability—the chapter provides a pragmatic blueprint for designing reliable, cost-aware, and trustworthy LLM-powered systems.

The mental map where we are focusing on building our RAG application (12).
Traditional ML models and LLM applications coexist in the same cluster, managed by identical infrastructure components. The same Horizontal Pod Autoscaler that scales your XGBoost recommendation engine also scales your LangChain RAG application. No separate infrastructure needed—just different workload types sharing proven Kubernetes orchestration.
LangChain chains link components where each chunk's output becomes the next chunk's input.
LangChain (left) provides sequential chains ideal for straightforward RAG pipelines, while LangGraph (right) enables complex graph-based workflows with conditional branching, parallel execution, and iterative refinement loops.
Build-time setup (top) ingests documents into a vector database and configures the LLM. Query-time flow (middle) handles user questions through embedding, retrieval, augmentation, and generation. Implementation requires three lines of LangChain code.
Google AI Studio API key generation interface with quickstart guide for Gemini model integration.
Successful launch with showing the interface that requires no frontend development.
LangFuse dashboard showing DakkaBot's traces, costs, and latency metrics.
LangFuse displays detailed traces including costs, inputs, outputs and intermediate results.

Summary

  • LLMs don't replace traditional MLOps infrastructure—they extend it. Your Kubernetes clusters, monitoring pipelines, and CI/CD systems remain essential, but they must support new components like vector databases, prompt management, and specialized observability tools.
  • The shift from single model deployments to composite systems fundamentally changes how you approach testing and debugging. Your "model" becomes an orchestrated pipeline of LLMs, embeddings, retrievers, and prompts, each with independent failure modes that require holistic monitoring.
  • Token-based pricing models require new optimization strategies. Unlike traditional compute costs that scale with infrastructure, LLM costs scale with usage patterns. Understanding prompt efficiency and context optimization becomes as important as traditional performance tuning.
  • The composable nature of LLM applications enables both flexibility and complexity. While you can swap embedding models or vector databases without rewriting integration code, the increased surface area for failures demands more sophisticated observability and error handling strategies.

FAQ

How do LLM applications differ from traditional MLOps workflows?LLM apps break several classic assumptions. Key differences include: - Non-deterministic outputs that invalidate exact-match unit tests - Multi-step reasoning chains (retrieve → augment → generate) instead of single predictions - Prompt engineering as a first-class discipline requiring versioning and testing - Token-based, usage-driven costs vs fixed compute-time pricing - Strict context windows that constrain input/output budgets - New attack surfaces (prompt injection, data leakage) requiring specialized guardrails Despite this, core platform elements (Kubernetes, CI/CD, monitoring, security) remain essential and are extended—not replaced.
What is Retrieval-Augmented Generation (RAG), and why is it useful?RAG separates retrieval from generation to give LLMs focused, up-to-date, and private knowledge without retraining: - Overcomes training cutoffs by retrieving current documents - Selectively fetches only relevant chunks to fit context windows and reduce noise/cost - Grounds responses in cited sources to mitigate hallucinations - Enables access to private/internal data safely - Supports dynamic/real-time data and dramatically improves cost efficiency by avoiding massive prompts
How do temperature, top-k, and top-p affect LLM output variability?These sampling parameters control randomness and thus consistency: - Temperature: 0 for highly consistent, near-deterministic answers; 0.7–1.0 for balanced creativity - Top-k: limit choices to the k most likely tokens (e.g., 40 typical) for quality/variety balance - Top-p (nucleus): choose from tokens covering P% probability mass (e.g., 0.9 balanced) Guidance: use low temperature for factual RAG answers; allow more randomness for brainstorming or conversational use cases.
How do context windows and token budgets shape RAG system design?Every model caps total tokens (input + output). Budgets force tradeoffs: - Control how many chunks you retrieve and chunk length - Reserve output tokens via max_tokens to avoid truncation mid-sentence - Keep system/user prompts concise Example: 50 chunks × 500 tokens = 25K + system prompt (2K) + query (100) ≈ 27K consumed before generation; with a 32K window, only ~5K remain for the answer. Token-aware design improves reliability, latency, and cost.
What new artifacts must be tracked and versioned for LLM deployments?Beyond model weights, LLM systems require rich metadata: - Prompt artifacts: system prompts, user prompt templates, few-shot examples, reasoning templates - Configuration: token limits, sampling parameters, model/provider versions, retries/timeouts - Retrieval: vector indexes/embeddings, chunking strategy, metadata schema, retriever params - Evaluation: test prompt sets, quality/safety metrics, human feedback, A/B results Tools like MLflow (experiments/lineage) and Langfuse (LLM-specific tracing) help manage “prompt_vX + model + params” variants.
Which tools does the chapter use, and what roles do they play?Recommended stack and rationale: - Embeddings + Vector DB: Google text-embedding-004 with FAISS for fast semantic search - Orchestration: LangChain for composable chains; LangGraph for conditional/iterative agent workflows - LLMs: Gemini (e.g., gemini-2.5-flash) for cost/performance balance - UI: Chainlit for streaming chat UX, citations, and feedback without frontend coding - Observability: Langfuse for traces, token/cost tracking, latency, and step-level analysis - Security/Testing: PromptFoo for adversarial/jailbreak testing of prompts and apps
How do I build a high-quality retrieval layer for RAG?Focus on: - Chunking: use structure-aware splitters with overlap to preserve context - Embeddings: use domain-appropriate models and asymmetric settings (document vs query) - Similarity metrics: cosine works well for text; tune k and thresholds to balance coverage vs noise - Persistence and rollout: serialize FAISS indexes, track versions, support blue/green index deploys, and reindex selectively via change detection (hashes/timestamps)
How should I assemble augmentation and generation for grounded answers?Best practices: - Load the persistent index with the same embedding config used for indexing - Retrieve k relevant chunks and deduplicate/organize them - Use a structured prompt with clear sections (Context, Question, Answer), role/persona, and explicit instructions (formatting, uncertainty handling, scope) - Configure LLM with low temperature for consistency - Return structured results (answer + sources + metadata) to enable citations and debugging - Support streaming for faster time-to-first-token and better UX
How do I add observability to LLM applications, and what should I measure?Integrate Langfuse (via LangChain callbacks) to capture: - Full traces of retrieval → augmentation → generation - Prompts, responses, token usage, and costs per query - Latency breakdowns: end-to-end, generation, and span-level timings - Business/context metadata (query type, doc_count, context length, session) Use dashboards to spot bottlenecks, drift in retrieval quality, cost outliers, and user-perceived responsiveness (e.g., time-to-first-token).
What security and reliability measures are recommended?Key practices: - Input validation and output filtering to mitigate prompt injection and unsafe content - Red-teaming with PromptFoo to uncover jailbreaks and policy gaps - Robust retries with exponential backoff; rate-limit by token budgets - Semantic caching to reduce cost/latency; LLM gateways for provider failover and routing - Continuous monitoring for safety violations and automated circuit breakers
How do I deliver a production-ready chat UI for a RAG system?Use Chainlit plus a clean core: - Encapsulate logic in a reusable DakkaBotCore (async init, retriever, LLM, streaming) - Provide sync wrappers for tests and legacy code - Stream tokens for real-time UX; show sources early to build trust - Add guardrails (input validation), clear author attribution, and helpful error states - Reuse existing platform (Kubernetes, CI/CD) and standard monitoring alongside LLM-specific tracing

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
  • Machine Learning Platform Engineering 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
  • Machine Learning Platform Engineering 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
  • Machine Learning Platform Engineering ebook for free