Building Agent-Powered Applications Your guide to generative AI, RAG, fine-tuning, and orchestration for production use (Vasyl Zvarydchuk)(Z-Library)
ai
No Description
15
Views
0
Downloads
0.00
Total Donations
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
Building Agent-Powered Applications Your guide to generative AI, RAG, fine-tuning, and orchestration for production use Vasyl Zvarydchuk, Ph.D.
Page
3
Building Agent-Powered Applications Copyright © 2026 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author nor Packt Publishing, nor its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. This book was written by Vasyl Zvarydchuk, Ph.D. Generative AI tools were used only to assist with ideation, phrasing, and diagram drafts, and all technical content and code were created, verified, and tested by the author and Packt's editorial team. Packt does not accept AI-generated content that replaces expert authorship. Portfolio Director: Gebin George Relationship Lead: Ali Abidi Project Manager: Prajakta Naik Content Engineer: Aditi Chatterjee Technical Editor: Rahul Limbachiya Indexer: Tejal Soni Production Designer: Alishon Falcon Growth Lead: Nimisha Dua First published: April 2026 Production reference: 1270426 Published by Packt Publishing Ltd. Grosvenor House 11 St Paul's Square Birmingham B3 1RB, UK ISBN 978-1-80760-517-9 www.packtpub.com
Page
4
Contributors About the author Vasyl Zvarydchuk is a principal AI engineer, applied data scientist, and researcher with over 15 years of experience building AI-powered and data-driven systems. With expertise across software engineering, artificial intelligence, machine learning, and data science, he brings together deep research insight and practical engineering experience. He has worked on the design and architecture of large-scale, distributed, and cloud-based systems, helping deliver intelligent solutions with real-world business impact. His experience spans both the theoretical foundations of AI and the practical challenges of building production-ready systems. Vasyl holds a Ph.D. in artificial intelligence, applied mathematics, and computer science. Vasyl lives with his family in Washington state, where he enjoys hiking, biking, camping, and fishing whenever the Pacific Northwest weather cooperates. This book is his way of sharing what he's learned and helping engineers, data scientists, and business leaders bridge the gap between traditional development and the future of intelligent systems.
Page
5
This book would not have been possible without the help, encouragement, and support of many incredible people. First and foremost, I want to thank my family — my amazing wife and our daughter — for their unwavering support, patience, and understanding. Writing this book meant many long evenings, late nights, and stolen weekends, and I couldn't have done it without their love and encouragement every step of the way. I'm deeply grateful to my friends who were the first reviewers and readers of this book. Your feedback, ideas, and honest critiques were invaluable. A heartfelt thank you to Alex Shyronosov and Alex Manekovskyi for your early reviews, thoughtful insights, and countless helpful suggestions. Your support and contributions played a key role in shaping and improving this book — I truly couldn't have done it without you. A very special thanks to Egor Pushkin, Chief Architect for Data and AI at Oracle Cloud, for generously sharing his time and expertise in our in-depth conversation featured in this book. His perspectives on the state of AI, the future of large language models, and the emergence of agentic systems added depth, credibility, and inspiration to this work. Finally, thanks to everyone who supported this journey in ways big and small — mentors, colleagues, fellow engineers, and readers who encouraged me to take on this challenge. This book is as much yours as it is mine. — Vasyl Zvarydchuk
Page
6
About the reviewer Ashok Singamaneni is a principal data engineer and open source innovator recognized for advancing large-scale data platforms, AI-assisted engineering, and distributed systems. He co- created Brickflow and Spark Expectations, two widely adopted frameworks with more than thirteen million downloads, that modernize orchestration and data quality for Lakehouse teams. Ashok has presented at the Databricks AI Summit and has appeared on The Data Engineering Show Podcast. He is known for mentoring engineers, shaping platform strategy, and driving reliable, scalable data systems.
Page
7
Subscribe for a free ebook New frameworks, evolving architectures, research drops, production breakdowns – AI_Distilled filters the noise into a weekly briefing for engineers and researchers working hands-on with LLMs and generative AI systems. Subscribe now and receive a free eBook, along with weekly insights that help you stay focused and informed. Subscribe at https://packt.link/8Oz6Y or scan the QR code below.
Page
8
Table of Contents Preface xix Free benefits with your book ............................................................................ xxxi Part 1: Foundations of AI, NLP, and LLMs 1 Chapter 1: Artificial Intelligence and Natural Language Processing Fundamentals 3 Technical requirements ........................................................................................ 4 Machine learning basics ....................................................................................... 4 Training machine learning models • 11 Supervised, unsupervised, and reinforcement learning • 15 Neural networks • 18 Fine-tuning • 22 Core machine learning problems ........................................................................ 23 Regression • 23 Classification • 23 Clustering • 25 Ranking and recommendation • 26 Core NLP problems and concepts ........................................................................ 26 Tokenization • 28 Sentence-level tokenization • 30 Stemming, lemmatization, and stopwords • 31 Embeddings • 34 Generating embeddings • 40
Page
9
Sentence-level embeddings • 41 Similarity metrics • 43 Cosine similarity • 43 Euclidean distance • 45 Manhattan similarity • 46 Summary ........................................................................................................... 46 Chapter 2: Understanding Large Language Models 49 Technical requirements ...................................................................................... 50 Sequence-to-sequence models ............................................................................ 50 Encoder • 52 Decoder • 55 Transformers • 59 Train, run, and benchmark LLMs ........................................................................ 63 Training objectives • 64 LLM training datasets • 65 Benchmark LLMs • 70 Small language models • 74 Multimodal models ............................................................................................ 74 Using LLMs ........................................................................................................ 76 Context window • 76 Sampling and randomness • 78 Hallucinations • 81 LLM families • 83 GPT models • 83 Gemini • 86 LLaMA • 86 Claude • 87 Model selection • 87 Summary ........................................................................................................... 89 Table of Contents viii
Page
10
Chapter 3: Prompt Engineering 91 Technical requirements ...................................................................................... 92 Understanding prompt structure ........................................................................ 92 System and user prompts • 92 System prompt structure • 95 User prompt structure • 97 Examples and n-shot learning • 97 Example selection • 100 Zero-shot prompting • 101 Static and dynamic few-shot prompting • 102 Core prompt techniques ................................................................................... 109 Chain of thought • 110 Tree-of-Thought prompting • 111 Self-consistency prompting • 112 System role or persona-based prompting • 114 Other techniques • 115 Multi-prompt engineering techniques • 116 Static multi-prompt flows • 119 Dynamic multi-prompt flows • 119 Multi-prompt chain of thought • 121 Iterative self-refinement • 124 Prompt chaining • 126 Summary .......................................................................................................... 127 Part 2: Building LLM Applications in Practice 129 Chapter 4: Understanding Language Tasks 131 Technical requirements ..................................................................................... 132 Text summarization .......................................................................................... 132 Extractive summarization • 133 Abstractive summarization • 135 ix Table of Contents
Page
11
Summarization parameters • 137 Summary length • 137 Maximum tokens • 137 Randomness settings • 137 Refocus • 137 Model selection • 138 Multimodal summarization • 138 Text-first multimodal summarization • 139 Multimodal models • 139 Summarizing tabular data • 140 Large document summarization • 141 Text classification .............................................................................................. 144 Sentiment analysis • 147 Intent detection • 150 Information extraction ...................................................................................... 152 Named entity recognition • 153 Classical NLP pipelines • 154 Transformer-based fine-tuned models • 155 Large language model for NER • 156 Relation and event extraction • 157 Multilanguage support ...................................................................................... 159 Language detection • 161 Machine translation • 163 Summary .......................................................................................................... 165 Chapter 5: Generation, Question Answering, and Reasoning 167 Text generation ................................................................................................ 168 Text generation parameters • 171 Instruction and prompt • 171 Few-shot prompting • 172 Output length • 173 Randomness • 173 Table of Contents x
Page
12
Model selection • 174 Code generation • 174 Synthetic data generation • 178 Question answering .......................................................................................... 179 Closed-domain and open-domain QA • 180 Multi-hop and conversational QA • 182 QA for structured data • 184 Reasoning ........................................................................................................ 189 LLM reasoning • 190 Commonsense reasoning • 190 Arithmetic, logical, and symbolic reasoning • 191 Temporal reasoning • 193 Causal reasoning • 193 Analogical reasoning • 194 Multi-hop reasoning • 195 Reasoning models • 195 Unknown reasoning • 197 Summary ......................................................................................................... 198 Chapter 6: Retrieval-Augmented Generation 201 Technical requirements .................................................................................... 202 RAG components .............................................................................................. 202 Static retrieval and parser • 203 Generator • 205 Lexical retrieval • 207 Term frequency and inverse document frequency • 209 BM25 • 213 Inverted indexes • 215 Semantic retrieval • 216 Document preprocessing • 217 Select document length • 218 Embedding models • 220 xi Table of Contents
Page
13
Choose a similarity metric • 220 Find the most relevant documents • 221 Approximate nearest neighbor (ANN) • 222 Tree-based methods • 223 Graph-based methods • 223 Quantization-based methods • 225 RAG implementations ....................................................................................... 225 Custom pipeline • 226 Lexical retriever • 226 Semantic retriever • 228 Hybrid approach, vector databases • 232 Vector databases • 233 RAG as a service • 238 Summary ......................................................................................................... 239 Chapter 7: LLM Fine-Tuning 241 The anatomy of fine-tuning .............................................................................. 242 How fine-tuning affects the model • 244 Full fine-tuning • 246 Partial fine-tuning • 248 Parameter-efficient fine-tuning: adapters and LoRA • 250 Supervised fine-tuning • 252 Preference-based fine-tuning: RLHF and DPO • 254 When and how to fine-tune ............................................................................... 257 How to fine-tune • 258 Fine-tuning on local or on-premises hardware • 258 Fine-tuning in the cloud • 258 Fine-tuning as a managed feature • 259 Choosing the right model and strategy • 260 Select the model family • 261 Choosing the model size • 262 Selecting the fine-tuning strategy • 264 Table of Contents xii
Page
14
Prompting, RAG, or fine-tuning • 265 Fine-tuning datasets ........................................................................................ 269 Hosting fine-tuned models ................................................................................ 271 Summary .......................................................................................................... 273 Part 3: Designing, Building, and Evaluating AI Agents 275 Chapter 8: Exploring the Architecture of AI Agents 277 Technical requirements .................................................................................... 278 Agent basics ..................................................................................................... 278 Agent terminology • 278 LLM agent architecture • 282 Conversational agents • 283 Background agents • 284 LLM agent examples • 285 Customer support agent • 285 Lead generation agent • 285 Personal email filtering agent • 285 Chat GPT, Gemini Chat, and Microsoft 365 Copilot • 286 Agent memory .................................................................................................. 286 Short-term memory • 287 LLM context window and efficiency • 289 Context relevance • 293 Long-term memory • 295 User preferences • 295 Profile data • 296 Previous conversations • 297 Tools and orchestration .................................................................................... 298 Agent orchestration • 299 Orchestration as a sequence of multi-label classification • 302 Orchestration plan • 303 Multi-plan orchestration • 304 xiii Table of Contents
Page
15
Dynamic orchestration plans • 305 Orchestration challenges • 308 Multi-agent flows .............................................................................................. 311 Code-level multi-agent flows • 312 Multi-agent communication patterns • 316 Worker and supervisor • 317 Sequential chat • 317 Roundtable discussion • 318 Hierarchical task delegation model • 318 Competitive agent model • 318 Agent goals and control mechanisms • 319 Summary ......................................................................................................... 320 Chapter 9: Building AI Agents 323 Technical requirements .................................................................................... 324 Agent design .................................................................................................... 324 Functional requirements • 325 System requirements • 326 Interaction mode • 327 Implementation approach • 327 Skills, tools, and capabilities • 328 Memory, state, and learning • 329 Reasoning and control mechanisms • 329 Safety and control boundaries • 330 Evaluation and success metrics • 330 Deployment and operations • 331 Agent memory implementation ......................................................................... 331 Custom memory development • 331 Memory tools and frameworks • 333 Mem0 • 333 Agent platforms memory implementation • 335 Memory-augmented learning • 335 Table of Contents xiv
Page
16
Tools and orchestration ..................................................................................... 337 Custom tools orchestration • 337 Function calling frameworks • 338 OpenAI function calling framework • 339 LangChain function calling • 341 Tools orchestration in an agentic platform • 342 Model context protocol • 343 Agent decision-making and planning ................................................................ 345 Agent reasoning techniques • 346 Planning strategies • 346 Sequential decision-making • 347 Hierarchical task decomposition • 347 Skill chaining • 348 Error handling and recovery strategies • 349 Human-in-the-loop • 350 Multi-agent frameworks and protocols .............................................................. 351 AutoGen framework (Microsoft Agent Framework) • 351 Agent-to-agent protocol • 355 Implementing AI agents in practice ................................................................... 359 Email filtering agent – requirements • 359 Functional requirements • 359 System requirements • 360 Interaction mode • 360 Memory, state, and learning • 361 Reasoning and control mechanisms • 362 Safety and control boundaries • 362 Evaluation and success metrics • 363 Deployment and operations • 363 Email filtering agent – design • 364 Email filtering agent – implementation • 365 Summary ......................................................................................................... 367 xv Table of Contents
Page
17
Chapter 10: Evaluating LLM Applications and Agents 369 Technical requirements .................................................................................... 370 Evaluation challenges ....................................................................................... 370 Evaluation strategy • 371 Multi-task AI agents' evaluation • 375 Evaluation datasets .......................................................................................... 376 Public datasets • 378 Building custom evaluation datasets • 378 Synthetic and human-generated datasets • 381 Evaluation metrics ........................................................................................... 383 Closed-ended task evaluation • 383 Accuracy and exact match • 384 Precision, recall, and F1 for binary classification • 385 Multi-class classification metrics • 387 Similarity metrics for open-ended tasks • 387 Lexical similarity-based metrics • 388 Semantic similarity-based metrics • 390 Human as a judge • 392 LLM as a judge • 398 Online vs. offline evaluations • 400 Agent evaluation .............................................................................................. 403 RAG-based agent evaluation • 403 Retriever evaluation • 404 Generator evaluation • 405 Conversational agent evaluation • 406 Agent memory evaluation • 406 Tool orchestration evaluation • 408 Background agent evaluation • 411 Responsible AI ................................................................................................... 411 Responsible AI risks and evaluation criteria • 413 Evaluation datasets for safety, bias, and fairness • 414 Table of Contents xvi
Page
18
Jailbreak and adversarial prompt evaluation • 416 Evaluation tools and frameworks ....................................................................... 417 Summary ......................................................................................................... 420 Chapter 11: Unlock Your Exclusive Benefits 423 Unlock this Book's Free Benefits in 3 Easy Steps ................................................. 424 Appendix 1: Expert Insights 427 Appendix 2: Bibliography 433 Other Books You May Enjoy 442 Index 445 xvii Table of Contents
Page
19
(This page has no text content)
Page
20
Preface Throughout history, artificial intelligence (AI) has evolved in waves, each marked by major breakthroughs. From early theoretical concepts to the rise of deep learning (DL), each wave has pushed the boundaries of what machines can do. But none have been as transformative, fast-moving, or democratizing as the current era, powered by large language models (LLMs). Each new wave of AI has arrived faster than the previous one and with greater impact [1]. In the past, it took decades to move from theoretical concepts and basic implementations in the 1950s-1960s to the rise of machine learning (ML) in the 1990s, and another 20 years before deep learning gained traction. But the leap from deep learning to LLMs happened in just several years, reshaping entire industries almost overnight. As breakthroughs accelerate, the time between innovation and real-world adoption continues to shrink, and we are now experiencing the fastest AI wave yet. Figure 1: AI genealogy: from the early days of AI to the rise of LLMs With the release of models like GPT-3, and the viral success of ChatGPT (chatgpt.com), AI made a dramatic leap, from solving narrow, task-specific problems to becoming a general- purpose tool capable of solving many different tasks across multiple domains. For the first time, software engineers and applied data scientists can build powerful, human-like AI systems without needing years of specialized AI experience. It's also worth highlighting that LLMs have fundamentally changed the kind of AI applications we can build. Instead of training and maintaining a collection of separate, specialized models for each problem, we can now build intelligent systems that handle many tasks at once, all powered by a single LLM. That one model can understand language, generate content, answer questions, support decision-making, and even automate multi-step workflows.
The above is a preview of the first 20 pages. Register to read the complete e-book.
AI Reading Assistant
Whole-book reading guide from stratified index samples; jump to passages in the text
AI guide
# Building Agent-Powered Applications
## 【One-Line Pitch】
A practical, end-to-end guide for software engineers and data scientists who want to move from traditional development into building production-ready generative AI applications—covering everything from NLP fundamentals through LLM architecture, prompt engineering, RAG, fine-tuning, and agent orchestration.
## 【Book Arc】
- **Opening (~0%–10%)**: Establishes the AI/NLP foundation—neural networks, supervised vs. unsupervised vs. reinforcement learning, tokenization, embeddings, and similarity metrics. Designed as a refresher for data scientists and an accessible entry point for software engineers new to AI concepts.
- **Early (~10%–23%)**: Dives into embeddings in depth—static vs. contextual, word-level vs. sentence-level—and transitions into LLM architecture. Explains sequence-to-sequence models, encoder-decoder designs, and transformer fundamentals with concrete code examples.
- **Early (~23%–32%)**: Covers LLM training objectives (causal vs. masked language modeling), training datasets, benchmarking, small language models, and multimodal models. Explains practical usage concerns: context windows, sampling/randomness, and hallucinations.
- **Middle (~32%–48%)**: Moves into prompt engineering—basic and advanced techniques, few-shot learning with example selection, and classifier-based example routing (e.g., NL2SQL categorization). Bridges model understanding to practical application design.
- **Late (~48%–100%)**: Progresses through RAG, fine-tuning, and AI agent orchestration for production. Includes evaluation strategies, jailbreak/adversarial prompt testing, and production deployment considerations. (Note: excerpts thin out here; later chapters are summarized from TOC and early references.)
## 【Key Takeaways】
- **Supervised vs. unsupervised vs. reinforcement learning form the conceptual bedrock** (Early): The book uses intuitive analogies—a mother teaching a child animal names (supervised) vs. an alien grouping creatures by similarity (unsupervised)—to make ML paradigms accessible before diving into LLM specifics.
- **Static embeddings are efficient but context-blind** (Early): Words like "bass" (fish vs. instrument) share the same vector in static embeddings, which are precomputed look-up tables. This limitation motivates contextual embeddings, where word representations shift based on surrounding text.
- **Contextual embeddings are trained as part of the model** (Early): Unlike static embeddings, contextual embeddings are generated dynamically at runtime and optimized alongside other model parameters—a key distinction for understanding how modern LLMs represent meaning.
- **Sentence-level embeddings enable semantic search and RAG** (Early): Mapping entire sentences to fixed-size vectors unlocks practical tasks like semantic similarity comparison, document classification, and retrieval-augmented generation—a foundation for later chapters.
- **Causal vs. masked language modeling serve different purposes** (Early): CLM (used by GPT, LLaMA, Mistral) predicts the next token with unidirectional attention, ideal for generation. MLM (used by BERT) predicts masked tokens from bidirectional context, traditionally better for understanding tasks—though large CLM models now rival MLM on many benchmarks.
- **Hallucinations stem from multiple, compounding causes** (Middle): Training data errors, sampling randomness (temperature, top-k, top-p), ambiguous prompts, and conflicts between prompt and internal knowledge all contribute. The book also notes the term's contested history and suggests alternatives like "fabrication" or "confabulation."
- **Few-shot learning works by showing input-output relationships** (Middle): Examples teach the LLM expected input structure, output format, and—most critically—the mapping between them. This mapping inference is what enables the model to generalize to new queries.
- **Classifiers can route prompts to specialized example groups** (Middle): For tasks like NL2SQL, categorizing prompts by complexity (simple, nested, joins) before calling the LLM ensures the model receives the most relevant examples, improving output quality.
## 【Reading Tips】
- **Skim Chapter 1 if you're a data scientist**: The opening chapter is explicitly designed as a refresher for ML practitioners—skip ahead if you're comfortable with supervised/unsupervised learning, tokenization, and basic embeddings.
- **Deep-read the embedding sections (Early)**: Static vs. contextual and word-level vs. sentence-level embeddings are foundational for understanding RAG and semantic search later. These distinctions recur throughout the book.
- **Work through the encoder-decoder code example (~29%)**: The Spanish translation example with token IDs and logits is concrete and walkable—it demystifies how sequence-to-sequence models actually produce output step by step.
- **Pay attention to the hallucination causes list (Middle)**: This is practical knowledge for production—understanding why models fabricate helps you design prompts, choose sampling parameters, and set user expectations.
- **Note the NL2SQL classifier example (Middle)**: It's a template for a general pattern—using lightweight classifiers to route prompts to specialized few-shot examples—that you can adapt to many domains.
## 【Coverage Limits】
This guide covers the first half of the book in detail (foundations through prompt engineering). Later chapters on RAG, fine-tuning, agent orchestration, and production evaluation are referenced but not deeply excerpted in the source material—readers should expect those topics to be covered in the full text.
##
Passage locations
Page 18
...................... 424 Appendix 1: Expert Insights 427 Appendix 2: Bibliography 433 Other Books You May Enjoy 442 Index 445 xxv Preface Who this book is...
View in text
Excerpt 2
ec1the correct class. Common idx_90f617d9architectures for idx_dd1f2e73classification include logistic regression, decision trees, random forests, and neural...
View in text
Excerpt 3
larly well-suited for tasks like text generation, including storytelling, creative writing, dialog systems (chatbots), code generation, and summarization. Be...
View in text
Excerpt 4
ng pattern between input and output to generate a response. Most LLMs do not offer a dedicated API for providing examples. Instead, examples can be included...
View in text
Recommended for You
{{#thumbnailUrl}}
{{/thumbnailUrl}}
{{^thumbnailUrl}}
{{/thumbnailUrl}}
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