Share E-Book

Building Reliable AI Systems MEAP V12 (all 11 chapters) Applications and agents you can trust (Rush Shahani)(Z-Library)

Author

Rust
Language English

Tested strategies to reduce hallucinations, improve performance and cost efficiency, and reduce bias or unethical behavior in your LLMs outputs. Building Reliable AI Systems shows you exactly how to guide large language models from research prototypes to scalable, robust, and efficient production systems. From model training to maintenance, an engineer will find everything they need to work with LLMs in this one-stop guide. This book complements Sebastian Raschka’s Build a Large Language Model (From Scratch), which takes a hands-on, ground-up approach to constructing LLMs. While Raschka’s book focuses on building models from scratch, Building Reliable AI Systems centers on deploying, optimizing, and maintaining reliable, production-grade AI systems. Inside Building Reliable AI Systems you’ll learn how to: Deploy LLMs into production Detect and reduce hallucinations Mitigate bias Optimize LLM performance and resource usage Advanced prompt engineering techniques Build intelligent agents and Retrieval-Augmented Generation Building Reliable AI Systems is a guide to putting LLMs into production in the real world. The book bridges the gap between theory and practice. You’ll go beyond basics like prompting into advanced optimizations: intelligent agents, Retrieval Augmented Generation (RAG), and in-depth solutions for mitigating hallucinations and bias. about the reader For data scientists or software engineers confident in Python and NLP. about the author Rush Shahani is a seasoned AI Engineer and CTO of Persana AI, a YCombinator-backed startup. At Persana, he leads the development of natural language processing and large language model systems that provide actionable insights to companies in order to drive revenue growth. His experience includes building AI systems at companies like LinkedIn, Element AI, and Shopify.

Format PDF
Size 14.1 MB
9
Views
(First 20 pages)

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

Page 1
(This page has no text content)
Page 2
MEAP Edition Manning Early Access Program Building Reliable AI Systems Applications and agents you can trus Version 12 Copyright 2026 Manning Publications For more information on this and other Manning titles go to manning.com. © Manning Publications Co. To comment go to liveBook Licensed to THIAGO BANDEIRA <thiago@lar.ifce.edu.br>
Page 3
welcome Dear Reader, Welcome, and thank you for purchasing the MEAP of Building Reliable AI Systems. We are living in an incredible time for AI, where Large Language Models (LLMs) have revolutionized the way we interact with technology, opening up possibilities that were once unimaginable. But the true power of these models lies not just in their creation but in their ability to be deployed effectively in real-world, production-level applications—and that’s where this book comes in. This book is written for developers, engineers, and data scientists who are ready to take their knowledge of Large Language Models (LLMs) beyond theory and into real-world, production-level applications. To get the most out of this book, it helps if you have a basic understanding of Python programming and some familiarity with LLMs like OpenAI and Claude. If you’re comfortable with LLM basics like hallucinations and prompting, you’re well-prepared to jump right in. Even if you’re newer to LLMs, this book is designed to build on foundational knowledge and guide you step-by-step toward successfully deploying LLMs in production environments. While there’s been an explosion of content around the basics of LLMs—their architectures, fine-tuning, and addressing issues like hallucinations—what’s often missing is the practical guidance for taking these models beyond experimentation and into the real world. This book aims to fill that gap. In my role as CTO of Persana AI and through my work for both startups and enterprises, I’ve seen firsthand how critical it is not only to develop LLMs but to effectively productionize them—ensuring they perform reliably, ethically, and at scale in real-world applications. This book will guide you through the entire process, from mitigating hallucinations and reducing bias to optimizing performance and ensuring reliability in LLM-powered applications. You’ll dive into advanced topics like prompt engineering, creating intelligent agents, and the powerful technique of Retrieval-Augmented Generation (RAG). But this isn’t just theory—each chapter includes real-world examples and projects that demonstrate how to put these concepts into action. By the time you’ve finished, you’ll have the knowledge and tools to deploy, scale, and manage LLMs in ways that unlock their full potential—whether that’s creating reliable AI- driven systems for customer service or building intelligent assistants that streamline enterprise operations. © Manning Publications Co. To comment go to liveBook Licensed to THIAGO BANDEIRA <thiago@lar.ifce.edu.br>
Page 4
By the end of this book, you'll be equipped to deploy, scale, and manage LLMs effectively, whether you're creating reliable AI-driven systems for customer service or building intelligent assistants that streamline enterprise operations. My journey with LLMs began at Element AI, where I worked on pioneering AI solutions across industries. At LinkedIn, I contributed to the Query Formulation team, impacting over a billion users globally. Today, I collaborate with enterprises to harness the transformative power of LLMs, driving innovation and tangible results. The lessons I've learned along the way - often through challenging experiences - are distilled in these pages, providing you with a shortcut to mastery that I wish I had when I was in your shoes. Your engagement is crucial to the evolution of this book. I encourage you to share your thoughts, questions, and experiences in the liveBook Discussion forum. Your feedback will be instrumental in shaping this resource to best serve the community of LLM practitioners. Thank you for embarking on this exciting journey into the future of AI. Together, we'll unlock the immense potential of LLMs and shape the next generation of intelligent applications. Thank you for joining me on this exciting journey into the future of AI. Best regards, —Rush Shahani © Manning Publications Co. To comment go to liveBook Licensed to THIAGO BANDEIRA <thiago@lar.ifce.edu.br>
Page 5
brief contents 1 AI Reliability: Building LLMs for the Real World PART 1: RELIABLE OUTPUTS 2 Generating Trustworthy Responses with Prompt Engineering 3 Grounding Outputs with RAG 4 Embeddings and Vector Search 5 Fine-Tuning LLMs for Improved Performance PART 2: RELIABLE AGENTS 6 Creating Eective AI Agents 7 Tool Integration and MCP 8 Multi-Agent Systems PART 3: RELIABLE OPERATIONS 9 Evaluation and Performance for LLMs and Agents 10 Deploying and Monitoring 11 Bias, Privacy and Responsible AI © Manning Publications Co. To comment go to liveBook Licensed to THIAGO BANDEIRA <thiago@lar.ifce.edu.br>
Page 6
1 AI Reliability: Building LLMs for the Real World   This chapter covers Defining reliability for production AI systems and why it matters now  Navigating the new landscape: reasoning models, coding agents, and autonomous systems  Diagnosing hallucinations: why LLMs fabricate information and how to detect it  Applying a three-layer reliability framework across outputs, agents, and operations  Building your reliability toolbox  We are living through one of the most significant capability jumps in the history of artificial intelligence. Just a few years ago, the best AI models could write decent essays and answer questions. Today, they can reason through PhD-level mathematics, write production-quality code, browse the web autonomously, and coordinate complex multi-step tasks across dozens of tools. Modern LLMs (large language models like OpenAI’s GPT, Anthropic’s Claude, and Google’s Gemini) don’t just generate text. They reason through multi-step problems, plan sequences of actions, use external tools, and take real-world actions. Yet an MIT study found that 95% of generative AI pilots fail to deliver measurable ROI . They were either abandoned after testing, never made it to production, or underperformed expectations. Teams hit the same walls: hallucinations, flaky outputs, brittle tools, poor evaluations, and often a failure to define the right problem in the first place. AI feels magical in the lab and unreliable in production [11]. The gap between what these models can do on a benchmark and what they deliver in a real system is the problem this book exists to solve. © Manning Publications Co. To comment go to liveBook 1 Licensed to THIAGO BANDEIRA <thiago@lar.ifce.edu.br>
Page 7
Whether you're a software engineer, data scientist, or ML practitioner, this book teaches you to build AI systems that work on day 1,000, not just day one. You'll learn to address reliability at every layer: from grounding outputs in verified information, to building agents that take safe actions, to monitoring systems that maintain quality over time. In this book, we’ll build real-world projects such as an e-commerce assistant, a RAG-grounded support bot, a multi-agent travel planner, and production monitoring pipelines that are grounded in engineering techniques you can apply immediately. Reliability, as we use the term in this book, means a system that produces accurate outputs, takes safe actions, and maintains quality over time under real-world conditions. You’ll gain the expertise to not just use LLMs, but to engineer them for reliability. We organize this challenge into three layers: reliable outputs (getting the model to give grounded, truthful answers), reliable agents (enabling safe tool use and multi-step workflows), and reliable operations (evaluation, monitoring, and responsible AI practices that keep everything working in production). 1.1 From benchmarks to the real world To understand why reliability matters so much right now, you need to understand what's changed. The AI landscape today looks almost nothing like it did just a few years ago and the pace of change continues to accelerate. Today’s frontier models, including OpenAI’s GPT-5, Anthropic’s Claude with extended thinking, and Google’s Gemini, can reason through multi-step problems, use external tools, and coordinate complex workflows. These capabilities create enormous value, but they also create new categories of failure that didn’t exist when models only generated text. Consider the benchmarks: On graduate-level science questions (GPQA Diamond), the best models now score above 94%, surpassing PhD experts who average around 70% [18]. On real-world software engineering tasks (SWE-bench Verified), top models resolve over 85% of actual GitHub issues. These aren’t cherry-picked examples; they represent genuine capabilities that were science fiction just a short time ago. But here’s the catch that matters for this book: when Scale AI created SWE-bench Pro, a harder version using fresh, previously unseen codebases, those same top-scoring models dropped to just 58–65%. The gap between familiar benchmarks and unfamiliar real-world problems is the reliability gap. That is the central distinction of this book: benchmark capability is not the same as production reliability, as figure 1.1 illustrates. © Manning Publications Co. To comment go to liveBook 2 Licensed to THIAGO BANDEIRA <thiago@lar.ifce.edu.br>
Page 8
Figure 1.1 LLM performance across benchmarks: the gap between familiar tests and real-world tasks This gap is exactly why production reliability requires engineering beyond model selection. 1.2 The tangible impact of LLMs in the real world Large language models (LLMs) are having a profound impact on industries far beyond research labs. The examples below were chosen because each one highlights a different reliability challenge: fabricated outputs in legal, wrong policy information in customer service, insecure code in development, and unsafe actions in agentic systems (table 1.1). © Manning Publications Co. To comment go to liveBook 3 Licensed to THIAGO BANDEIRA <thiago@lar.ifce.edu.br>
Page 9
Table 1.1 The Industry Impact of LLMs Industry Example Benefit Risk Law Harvey AI and Legora streamline contract analysis, due diligence, and research Faster research, review, and drafting Fabricated citations can cause legal damage Customer Service Klarna AI replaces 700 agents, saves $40M/year Faster service, multilingual support Wrong policy info risks liability Development AI coding tools (Cursor, Claude Code, Codex) speed development 30–55% Developer productivity 43% of AI code needs production debugging Enterprise AI Salesforce Agentforce → $800M ARR, 29,000+ deals 83% of support queries resolved autonomously Biased outputs in high- stakes fields 1.2.1 Legal industry transformation The legal industry represents one of the fastest-growing areas for LLM adoption. Harvey AI, valued at $11 billion as of March 2026, serves over 100,000 legal professionals at firms including A&O Shearman, PwC, and HSBC, streamlining contract analysis, due diligence, compliance, and litigation [20]. Legora, which surpassed $100 million in annual recurring revenue while scaling from 40 to 400 employees in a single year, now serves over 1,000 organizations across 50 markets, including White & Case, Linklaters, and Barclays. Among law firms surveyed, lawyers using Legora save an average of 4.3 non-billable hours per week, and 71% report that the tool identifies issues they would have otherwise missed [21]. However, the legal profession's stringent accuracy requirements mean that AI-generated content must undergo thorough human validation. A single fabricated case citation could have serious professional consequences. As David Wakeling, head of the Markets Innovation Group at A&O Shearman, cautioned after deploying Harvey across 3,500 lawyers: "You must validate everything coming out of the system" [20]. A Stanford study on legal RAG hallucinations confirmed that even retrieval-augmented systems fabricate citations at meaningful rates. The engineering takeaway: high-stakes legal workflows require source grounding, automated citation verification against authoritative databases, and mandatory human review before any output reaches a court. 1.2.2 Customer service revolution Customer service has been transformed by LLMs through intelligent virtual assistants. Klarna deployed an OpenAI-powered customer service assistant that now handles the work equivalent to 700 full-time agents, resolving customer inquiries 2.3x faster than human agents and operating in 35 languages, saving an estimated $40 million annually. © Manning Publications Co. To comment go to liveBook 4 Licensed to THIAGO BANDEIRA <thiago@lar.ifce.edu.br>
Page 10
Intercom's Resolution Bot achieves 67% resolution rate for customer inquiries without human intervention, saving the company $50 million annually in support costs while improving customer satisfaction scores. However, early deployments revealed challenges with AI providing incorrect policy information. When a fluent assistant confidently states the wrong refund window or warranty term, customers act on it, and the company is liable for what its bot promised. The engineering takeaway: ground every policy response in a retrieved, version-controlled policy document rather than the model’s training data, and escalate to humans when confidence is low. 1.2.3 Programming and development AI-powered coding tools have become one of the fastest-growing categories in software. A recent JetBrains survey found that 74% of developers worldwide have adopted AI coding assistants. The market is fiercely competitive: Cursor, the AI-native code editor, surpassed $2 billion in annualized revenue and is used by over half the Fortune 500. Anthropic’s Claude Code reached a $2.5 billion run-rate by early 2026, the fastest-growing developer product on record, while OpenAI’s Codex CLI crossed 4 million weekly active users by April 2026 [22][23]. Workplace adoption now splits three ways: GitHub Copilot at 29%, Cursor and Claude Code each at 18% [15]. Developers consistently report completing tasks 30– 55% faster with these tools. These tools have gotten dramatically better: Claude Code now achieves 95% first-try correctness, and both tools can sustain long autonomous coding sessions [22][23]. Yet the reliability gap remains wide. A Lightrun survey found that 43% of AI-generated code still needs manual debugging in production, and CodeRabbit’s analysis shows AI-assisted code produces 1.7x more logic bugs than human-written code [24]. Across 22,000 developers tracked by Faros AI, incidents per pull request climbed 23–58% even as throughput rose [25]. The engineering takeaway: productivity gains do not reduce the need for code review, automated testing, and security validation. Faster code generation makes rigorous review more important, not less. 1.2.4 Enterprise AI – Agents that take action The most transformative applications go beyond simple text generation to agentic AI - systems that can take actions, use tools, and coordinate complex workflows. Salesforce Agentforce, launched in late 2024, has become the fastest-growing product in Salesforce’s 26-year history. Within its first full fiscal year, Agentforce had reached $800 million in annual recurring revenue (up 169% year-over-year) with over 29,000 deals closed. Salesforce’s own help portal now resolves 83% of customer service queries autonomously using Agentforce, cutting the need for human escalation nearly in half. The broader market reflects this momentum: as figure 1.2 shows, the global AI agents market has grown rapidly year-over-year and is projected to continue accelerating through 2030. © Manning Publications Co. To comment go to liveBook 5 Licensed to THIAGO BANDEIRA <thiago@lar.ifce.edu.br>
Page 11
Figure 1.2 Global AI agents market size by year, 2018-2030 (projected) Despite these impressive advancements, LLMs are not without challenges. They can still generate biased or inaccurate outputs, especially in high-stakes fields like healthcare and law where precision is critical. The issue of hallucination, where the model confidently provides false or misleading information, remains a significant concern. As LLMs become more integrated into real-world applications, addressing these risks will be crucial to ensure their safe and responsible deployment. With continued development and careful oversight, LLMs have the potential to revolutionize industries by enhancing human productivity and enabling new ways of working. The possibilities are immense, but once systems take actions, reliability is no longer only about answer quality. It also includes permissions, reversibility, tool robustness, and failure containment. The engineering takeaway: when AI systems act autonomously, you need permissions, reversibility, tool robustness, and failure containment, dimensions we’ll address when we look closer at agents later in this book. 1.3 Understanding hallucinations and Reliable AI Of all the reliability challenges you'll face with LLMs, hallucination is one of the most fundamental, and one of the most dangerous. Before we can build reliable systems, we need to understand why LLMs fabricate information. © Manning Publications Co. To comment go to liveBook 6 Licensed to THIAGO BANDEIRA <thiago@lar.ifce.edu.br>
Page 12
1.3.1 When AI hallucinates convincingly Imagine you're a lawyer preparing for a major case. Your AI research assistant finds six perfect precedents - cases with compelling legal reasoning that support your client's position. You craft a brilliant brief, cite the cases, and submit it to federal court. Then you get a call from the judge's clerk: none of the cases exist. They're complete fabrications but they sound so legitimate that even experienced legal professionals were initially fooled. The case names follow proper legal naming conventions. The citations include realistic volume numbers, page references, and years. The legal reasoning sounds plausible. Everything about them screams "authentic" except for one small detail: they were invented entirely by the AI. This has happened multiple times in courtrooms around the world, resulting in sanctions, professional embarrassment, and serious questions about whether AI can be trusted for legal research. But the legal profession isn't alone; similar stories emerge from medicine, journalism, academia, and every field where accuracy matters. 1.3.2 What exactly is a hallucination? A hallucination occurs when an LLM generates content that is factually incorrect, nonsensical, or unfaithful to the source material while presenting it with the same confidence as for accurate information. The AI doesn't signal uncertainty. It doesn't hedge. It presents fabricated information with the same authoritative tone as verified facts. This is fundamentally different from traditional software errors, which typically produce obviously wrong outputs like error messages, crashes, or garbage data. Hallucinations are wrong answers that look right. They take different forms: fabricated facts, invented citations, contradictions of provided context (intrinsic hallucination), and claims that contradict world knowledge (extrinsic hallucination). Each requires different mitigation strategies, which we’ll cover throughout the book. © Manning Publications Co. To comment go to liveBook 7 Licensed to THIAGO BANDEIRA <thiago@lar.ifce.edu.br>
Page 13
Figure 1.3 Why hallucinations happen from query to fabricated output Hallucinations happen because of how LLMs fundamentally work (figure 1.3). These models are sophisticated pattern-matching systems that learn what authoritative content looks like such as the structure, vocabulary, and style of legal citations, academic papers, or technical documentation without actually knowing whether specific facts are true. They generate text probabilistically, one token at a time, optimizing for what sounds plausible rather than what is accurate. They're trained on internet-scale data that contains errors, contradictions, and gaps. And they have no built-in mechanism to verify their outputs against ground truth before generating them. When asked about something outside their training data or where their training data is contradictory, they generate plausible- sounding text that matches learned patterns even if the content is completely fabricated. 1.3.3 What is Reliable AI? Hallucinations are just one dimension of reliability. Before going further, let’s be precise about what this book means by reliable AI, and what it doesn’t. A reliable AI system produces accurate, factual outputs without hallucinating or fabricating information. It behaves consistently, so that similar inputs yield appropriately similar outputs. It fails gracefully when it can't help: it says so rather than guessing. It stays grounded, with outputs anchored in verifiable sources and real data. It operates fairly, without perpetuating harmful biases or discriminating. It performs efficiently, meeting latency and cost requirements at scale. When given agency, it takes safe actions within defined boundaries. And it maintains quality over time, even as models update and data drifts. © Manning Publications Co. To comment go to liveBook 8 Licensed to THIAGO BANDEIRA <thiago@lar.ifce.edu.br>
Page 14
In practice, these dimensions involve real trade-offs: accuracy versus latency, safety versus cost, depth versus speed. Production reliability means navigating these trade-offs deliberately rather than pretending you can maximize everything at once. This is a practical engineering book about systems you can ship. Traditional software reliability focuses on uptime, error rates, and performance metrics. AI reliability adds a critical new dimension: semantic correctness. Your system might have 99.99% uptime while confidently generating wrong answers. That’s the gap this book teaches you to close. Building reliable AI systems requires a specific set of capabilities. You need to know how to shape model behavior through prompting, ground outputs in verified information through retrieval, adapt models to your domain when needed, give agents the ability to take safe actions, evaluate whether your system is actually working, and keep it working as data and models drift over time. By the end of this book, you’ll have all of these, and you’ll know which to reach for in any given situation. 1.4 The AI reliability framework Throughout this book, we'll use a three-layer framework for thinking about AI reliability. This framework organizes the challenges you'll face and the techniques you'll learn. Each layer builds on the previous one, and mastering all three is essential for production-ready AI systems. Figure 1.4 shows how these three layers fit together. Figure 1.4 The AI Reliability Framework - three layers from outputs to operations 1.4.1 Layer 1: Reliable outputs The question: "How do I get the LLM to give accurate, grounded answers?" © Manning Publications Co. To comment go to liveBook 9 Licensed to THIAGO BANDEIRA <thiago@lar.ifce.edu.br>
Page 15
This is the foundation. An LLM that confidently produces wrong answers isn't just useless; it's dangerous. Before your AI can take actions or operate autonomously, it needs to generate outputs you can trust. This layer is about ensuring that when your system speaks, it speaks truthfully. Prompt engineering is your first line of defense against hallucinations, and often the fastest way to improve reliability without changing anything else in your system. Prompt engineering represents the art and science of shaping how the model approaches problems. You'll learn techniques like structured prompts that guide model reasoning, Chain-of- Thought prompting that makes the model's logic explicit and auditable, few-shot examples that demonstrate the behavior you want, and guardrails that define what the model should and shouldn't do. Retrieval-Augmented Generation (RAG) is the most powerful technique for grounding AI outputs in verified information. Instead of relying solely on what the model "knows" from training, RAG retrieves relevant documents from your own knowledge base and provides them as context. The model generates responses based on this retrieved content, dramatically reducing hallucinations. Retrieval, however, introduces its own failure modes, including missed documents, stale context, and irrelevant passages, all of which you’ll learn to handle. You'll build a complete RAG pipeline, learning how to chunk documents effectively, retrieve the most relevant passages, and synthesize grounded responses with proper citations. Semantic retrieval is powered by embeddings and vector search. Embeddings are numerical representations that capture meaning, allowing you to find conceptually similar content even when the words don't match. You'll understand how embedding models work, how to choose the right one for your domain, and how to build efficient vector search systems. While RAG provides dynamic knowledge at inference time, fine-tuning shapes the model’s behavior itself: not just what it knows, but how it responds, including its tone, format, reasoning patterns, and domain conventions. Fine tuning requires adapting a model’s weights to your specific domain or task. You’ll learn when fine-tuning is worth the investment versus when RAG alone is sufficient, how to prepare high-quality training data, and techniques like LoRA that make fine-tuning practical even with limited resources. You’ll also explore knowledge distillation, the process of training smaller, faster models that retain the performance of larger ones. Distillation combined with quantization has become the standard approach for deploying reliable AI at production scale and cost. 1.4.2 Layer 2: Reliable agents The question: "How do I build agents that take actions reliably and safely?" © Manning Publications Co. To comment go to liveBook 10 Licensed to THIAGO BANDEIRA <thiago@lar.ifce.edu.br>
Page 16
Once your AI generates reliable outputs, the next step is enabling it to act - to use tools, access APIs, and coordinate workflows. This is where the stakes multiply exponentially. A wrong answer is embarrassing; a wrong action can be catastrophic. An AI travel agent that books Paris, Texas instead of Paris, France costs money and causes frustration. An AI assistant that "cleans up" the customer database by deleting records can destroy years of work in seconds. The math is sobering: as the International AI Safety Report noted, even an agent that is 85% reliable at each step will succeed end-to-end only about 20% of the time across a 10-step workflow, because errors cascade. AI systems reason, plan, and execute tasks within agent architectures. You'll learn the fundamental patterns that make agents work: the ReAct pattern that alternates between reasoning and acting, planning approaches that break complex tasks into manageable steps, and memory systems that maintain context across long interactions. You'll understand how to design agents that explain their reasoning, making their decisions auditable and their failures diagnosable. Standardized tool integration improves reliability by providing consistent error handling, traceability, and failure containment across all connected tools. Such tool integration can be achieved using the Model Context Protocol (MCP), the emerging standard for connecting AI agents to external systems. You'll learn how to give agents access to APIs, databases, and services while maintaining control. Some problems are too complex for a single agent, requiring different types of expertise or perspectives. The solution is multi-agent systems, which coordinate multiple specialized AI components for complex tasks. You'll learn patterns for agent collaboration, including supervisor architectures that coordinate specialists. You'll also learn how to prevent cascading failures, where one agent's mistake propagates through the entire system. 1.4.3 Layer 3: Reliable operations The question: "How do I evaluate, deploy, and run this responsibly - and keep it reliable over time?" Building a reliable system is only half the battle. Keeping it reliable over time as models update, data drifts, and usage patterns change requires operational discipline. Your AI works perfectly in testing. Three weeks after deployment, you discover it's been giving subtly wrong answers to 15% of users. Or it works great for most users but systematically underperforms for certain demographic groups. This layer is about preventing those scenarios. AI evaluation means measuring what matters, and performance improvement means optimizing for it. You’ll learn multiple evaluation approaches: reference-based metrics like ROUGE and BLEU that compare outputs against known correct answers; LLM-as-judge techniques that use another model to evaluate quality, relevance, and faithfulness; red teaming practices that deliberately try to break your system before users do; and human evaluation protocols for the cases where automated metrics aren’t enough. These methods are complementary, not interchangeable. Each catches different failure modes, and production systems typically combine several. You’ll also learn about observability platforms like Arize and Phoenix that help you understand how your system behaves in the wild. © Manning Publications Co. To comment go to liveBook 11 Licensed to THIAGO BANDEIRA <thiago@lar.ifce.edu.br>
Page 17
Appropriate deployment and monitoring practices keep systems reliable in production. You'll learn how to detect drift before it becomes a problem, set up alerts for quality degradation, manage model updates without breaking existing functionality, and build feedback loops that improve your system over time. Remember: Production monitoring for AI systems requires different approaches than traditional software. You're not just tracking uptime and latency, but semantic quality, hallucination rates, and user satisfaction. To ensure your systems are not just accurate but fair, safe, and trustworthy, you must prevent bias, protect privacy, and implement responsible AI. In our framework, fairness and privacy are dimensions of reliability, not separate concerns: a system that discriminates or leaks data is unreliable, regardless of its accuracy scores. You’ll learn techniques for detecting and mitigating bias, protecting user privacy, ensuring transparency in AI decisions, and building the governance structures that sustain reliability over time. 1.5 The reliability toolbox The framework above organizes where reliability challenges arise (outputs, agents, operations). This section focuses on how you solve them. Think of these as tools in a toolbox, each suited to different problems. Knowing when to use which tool is a core skill you'll develop throughout this book. The table below summarizes the key techniques and when to reach for each one. Table 1.2 The reliability toolbox: techniques and when to use them Technique What It Does When to Use It Model Selection Choosing the right LLM based on task, cost, latency, and reliability requirements Foundational decision; revisit as models evolve Prompt Engineering Structures inputs to guide model reasoning and behavior First line of defense; always start here RAG Retrieves context from external sources before generation When outputs must be grounded in documents or data Vector Search Finds semantically similar content using embeddings When keyword search isn't enough Fine-Tuning Adapts model weights to your domain or task When you need deep domain expertise Agent Frameworks Structures AI reasoning, planning, and execution Multi-step tasks requiring decisions Tool Integration (MCP) Connects AI to external APIs and services When AI needs to take actions or access live data Multi-Agent Systems Coordinates multiple specialized AI components Complex workflows requiring different skills Evaluation Measures output quality with ROUGE, LLM-as-judge, red teaming, more Always: you can’t improve what you don’t measure Monitoring Tracks AI behavior in production Any production deployment © Manning Publications Co. To comment go to liveBook 12 Licensed to THIAGO BANDEIRA <thiago@lar.ifce.edu.br>
Page 18
The key principle is to start simple and add complexity only as needed. Begin with prompt engineering, which is free and fast. If that's not enough, add RAG to ground your outputs. If you need deeper domain expertise, consider fine-tuning. If you need actions, add agent capabilities carefully. And always from day one, you should build in evaluation and monitoring so you can measure your progress and catch problems early. See the decision tree in figure 1.5 to help you decide which one to start with. Figure 1.5 The Reliability Toolbox Decision Tree - choosing the right technique for your AI System 1.6 Why reliable AI systems matter now As AI systems become embedded in healthcare, finance, legal services, and critical infrastructure, the margin for error shrinks. A production AI system includes the prompts that guide it, the retrieval pipelines that ground it, the agents that act on its behalf, and the monitoring that catches problems. Every layer introduces potential failure points. Organizations that build reliable AI systems, not just impressive demos, are able to automate faster, scale smarter, and build user trust. They ship to production with confidence because they've addressed reliability at every layer. Those who focus only on the model? They stall in experimentation, face unexpected failures, and burn budgets debugging systems that worked in testing but fail in the real world. © Manning Publications Co. To comment go to liveBook 13 Licensed to THIAGO BANDEIRA <thiago@lar.ifce.edu.br>
Page 19
The regulatory landscape adds urgency. The EU AI Act and emerging U.S. legislation don't just regulate models - they regulate systems. They demand verifiable fairness, explainability, and human oversight across the entire AI pipeline. Compliance requires reliability engineering, not just model selection. Public trust depends on system reliability, not model capability. Users don't care if your model scores well on benchmarks, they care if your system gives them wrong answers, takes incorrect actions, or treats them unfairly. High-profile failures erode trust across the industry. This book teaches you to build reliable AI systems, the full stack from prompt to production. You'll learn to address reliability at every layer: outputs, agents, and operations. The result isn't just a working prototype, but a system you can deploy, monitor, and trust. 1.7 Requirements for Following Along To work through this book's examples and projects, you'll need Python 3+ with pip package manager, a code editor like VS Code, Cursor, or similar, and an OpenAI API key. That's it for getting started. We assume you have basic familiarity with Python programming and fundamental machine learning concepts like training, evaluation, and model selection. If terms like “embeddings” or “fine-tuning” are new to you, don’t worry. We’ll cover them from the ground up. Most examples use API calls rather than local model hosting, keeping setup simple and costs low. We will explain how to install additional services and packages as needed. Optional cloud services and additional tools are introduced as needed in later chapters, with free tier options provided wherever possible. 1.8 Summary LLMs have immense potential to transform industries. Their applications span content creation, customer service, healthcare, and more. Agentic AI systems that take real-world actions introduce new categories of risk requiring sophisticated reliability engineering. The three-layer framework organizes reliability: reliable outputs (grounded, accurate answers), reliable agents (safe tool use and multi- step workflows), and reliable operations (evaluation, monitoring, and responsible AI). Curbing hallucination risks is key to keep outputs honest and grounded in facts. Performance optimization ensures LLMs meet speed responsiveness demands, and quality of real-world applications. Multi-agent systems require coordination protocols, error handling, and monitoring to prevent cascading failures. The reliability toolbox includes prompt engineering, RAG, embeddings, fine-tuning, agent frameworks, tool integration, and evaluation - start simple, add complexity as needed but always build in evaluation and monitoring. © Manning Publications Co. To comment go to liveBook 14 Licensed to THIAGO BANDEIRA <thiago@lar.ifce.edu.br>
Page 20
This book covers promising solutions to these challenges that will enable safely harnessing LLMs to create groundbreaking innovations across healthcare, science, education, entertainment, and more while building vital public trust. 1.9 References [1] Amazon Web Services. (2022). Train and deploy large language models on Amazon SageMaker. https://d1. awsstatic. com/events/ Summits/reinvent2022/ AIM405_Train- and- deploy- large-language- models-on- Amazon-SageMaker. pdf [2] OpenAI. (2023). GPT-4 Technical Report. https://cdn. openai.com/ papers/gpt- 4.pdf [3] KDnuggets. (2020). GPT-3 and Deep Learning in NLP. https://www. kdnuggets. com/2020/ 06/gpt-3- deep-learning- nlp.html [4] Salesforce. (2026). Salesforce Agentforce adoption and ARR growth, Q4 FY2026 earnings. https://futurumgroup. com/insights/ salesforce- q4-fy-2026- earnings- show- agentic- ai-scaling- guidance- steadies/ [5] Klarna & OpenAI. (2023). Klarna’s AI customer service assistant delivers major impact. https://openai. com/index/ klarna/ [6] CoSupport AI. (2023). Klarna AI wins big: How 700 agents were replaced and customers are happier. https://cosupport. ai/articles/ klarna-ai- wins-big [7] AI Street. (2023). Stripe built a payments LLM to fight fraud. https://www. ai-street. co/p/stripe- built-a-payments- llm-to-fight- fraud [8] Grand View Research / PR Newswire. (2024). AI Agents Market Size to Hit $50.3 Billion by 2030. https://www. prnewswire. com/news- releases/ ai-agents- market-size- to-hit-50- 31- billion- by-2030-at- cagr-45-8- --grand-view- research- inc-302447060. html [9] Weiser, B. (2023). A.I. Is Coming for Lawyers, and It’s Making Big Mistakes. The New York Times. https://www. nytimes.com/ 2023/05/27/ nyregion/ ai-chatbot- fake-citations. html [10] Vellum. (2026). LLM Leaderboard: Compare Top AI Models. https://www. vellum.ai/ llm- leaderboard [11] MIT. The GenAI Divide: State of AI in Business. https://fortune. com/2025/ 08/18/mit- report-95- percent-generative- ai-pilots- at-companies- failing-cfo/ [12] Dahl, M. et al. (2024). Large Legal Fictions: Profiling Legal Hallucinations in Large Language Models. Stanford Digital Humanities. https://dho.stanford.edu/wp- content/uploads/Legal_RAG_Hallucinations.pdf [13] Lightrun. (2026). 2026 State of AI-Powered Engineering Report, reported in VentureBeat. https://venturebeat.com/technology/43-of-ai-generated-code-changes-need- debugging-in-production-survey-finds © Manning Publications Co. To comment go to liveBook 15 Licensed to THIAGO BANDEIRA <thiago@lar.ifce.edu.br>
The above is a preview of the first 20 pages. Register to read the complete e-book.

Recommended for You

Loading recommended books...
Failed to load, please try again later

Tip the Site

Scan the WeChat Pay or Alipay code to tip. No login required.

WeChat Pay
Alipay
← Back to List