Skip to content
ImagineWorld

Creating end-to-end LLM applications

node_idnode-book_build-small-language-model_chapter-13-creating-end-to-end-llm-applications
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num13
chapter_titleCreating end-to-end LLM applications
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 13 — Creating end-to-end LLM applications

Section titled “Chapter 13 — Creating end-to-end LLM applications”

Creating end-to-end LLM applications

This chapter covers

  • Why standalone SLMs/LLMs aren’t always enough
  • Building a RAG system that uses only SLMs
  • Building an agentic AI with SLMs

So far, we’ve looked at strategies for optimizing small language models (SLMs) to run on available hardware while maintaining acceptable quality. Throughout, we have focused on a common pattern: an SLM receives a prompt, generates task-specific output, and returns a result to the client application or user. This is a frequent scenario, but it’s not the only way to use language models. They often deliver more business value as part of a larger system.

In this chapter, we’ll explore two popular LLM-based system paradigms: retrieval-augmented generation (RAG) and agentic AI. The difference here is that we’ll build on domain-specific small models only, which offers benefits for privacy, safety, security , specificity, and cost savings.

In early 2023, large tech organizations started rushing to “win” the LLM race and rea so-called AGI (artificial general intelligence), fueled by daily hype. That push continued through 2024 and early 2025 and led to larger and larger language models, based on the assumption that more data and more compute (and lately also time-scale compute ) would make these models reason like humans across a wide range of tasks, rather than excel at a single narrow task (or a small set), as with today’s ML/AI. The reality is that, because of their architecture, language models based on Transformer variants won’t converge to AGI. They are, however, useful for narrow but nontrivial tasks when tuned on high-quality domain-specific datasets or integrated into a broader system.

For example, imagine we are a Formula 1 racing team. Our goal is to design and build a car that can compete in the Formula 1 World Championship, win races, and possibly win the drivers’ or constructors’ title. The engine is a core component, but at design time, we don’t try to build the best engine possible; we choose the best fit for the car we have in mind. We need to consider many other factors, such as the mechanical parts, electronics, and tires, because how well these work together is key to success (see figure 13.1). We also need to follow the official rules established by the FIA (Fédération Internationale de l’Automobile) for Formula 1 constructors.

NOTE Figures 13.1 and 13.2 were generated using the Ikea Instructions LoRA for the Stable Diffusion XL Base model. The LoRA weights are available in Hugging Face Hub at https://huggingface.co/ostris/ikea-instructions-lora-sdxl.

dslm-fig-13.1-formula1-business-goal.png

[!visual-conversion] Figure 13.1 — A sample business goal for our imaginary Formula 1 racing team: build a competitive car, where the engine is important but not the only component (p. 271)

Now think of the engine as a language model and the car as the final system built around it to meet a business goal. The model takes user inputs through an interface (web or desktop). Those inputs are often enriched with data from other sources (for example, a database or document management system) to provide context. The model then generates content that may need postprocessing with external tools so it can be formatted and delivered to users or downstream systems. When designing such a system, we’ll also consider scalability, reliability, and security. The business value doesn’t come from the model alone, but from the system as a whole. That’s one reason to choose smaller models that can be specialized for the goal and work well with the other components. In many industries, as in Formula 1, real-world tech projects (including those with ML/AI components) must meet regulations. Compliance is easier when we control the full stack, including a tailored SLM bundled into the system.

The preceding scenario resonates with professionals in any industry, not just technology. Since ChatGPT’s release, companies such as OpenAI, Google, Anthropic, xAI, and Meta have followed a pattern that, to continue the Formula 1 analogy, resembles the one shown in figure 13.2.

dslm-fig-13.2-formula1-failure-pattern.png

[!visual-conversion] Figure 13.2 — A pattern that’s sure to fail in Formula 1: building a mammoth engine, putting it on wheels, and ignoring integration with other components and the team’s core scope (p. 272)

In this scenario, the Formula 1 team focuses only on the engine and may even source its design to an organization that ignores the rest of the car. It delivers a powerful engine that doesn’t fit, and integration with the other components becomes a nightmare. This car will not compete for the world championship, and you blame FIA regulations for the failure. This is what many big tech companies have (and are still doing): training ever-larger models, pouring money and compute in race toward AGI on the wrong architecture.

Don’t get me wrong: large models work well for general-domain, routine tasks as text classification and summarization. But to improve performance, prompt engineering can’t be the only answer. We also need to integrate external knowledge, and that integration can be costly and difficult because of safety, privacy, security, and other industry-specific regulations, even for trivial tasks.

13.2 Combining a domain-specific SLM with RAG

Section titled “13.2 Combining a domain-specific SLM with RAG”

I briefly introduced retrieval-augmented generation (RAG) in chapter 2, but in this section (and the next chapter), we’ll go deeper, looking at it from different angles and seeing how we can avoid common pitfalls. All the examples in this section will use open source SLMs for both retrieval and generation.

More than one Python framework is available for implementing RAG. In this first example, we’ll implement it using specific packages for different tasks (PDF parsing and content extraction, embedding and generator model handling, vector storage, etc.) without a dedicated RAG framework, so we can focus on understanding the various steps and their challenges. We’ll make things more complex in later examples.

RAG enhances language models by integrating external knowledge bases. Although large models are powerful, they bring significant cost and integration challenges. SLMs are a more resource-efficient alternative, especially for industry-specific tasks. In a RAG system, language models not only generate content but also convert large volumes of unstructured text and user prompts into embeddings (see figure 13.3). Using smaller models drastically reduces the cost of these conversions.

In figure 13.3, we can see two phases in a RAG system: offline and online. Offline, the raw document corpus is chunked into smaller text segments and transformed into embeddings by an embedding model. Those embeddings are stored in a vector database, with indexes built on top to speed up search. This phase runs when you first set up the RAG system and whenever documents are added, removed, or updated in the knowledge base. Online, whenever a user submits a query, the query is embedded and used to look up semantically similar document chunks in the vector database. The retrieved chunks add context to the query and are passed to the generator model, which produces an answer.

Let’s start with a simple use case where we have a single PDF document to query. To extract content from the PDF, we’ll use PyMuPDF (https://github.com/pymupdf/PyMuPDF), an open source Python library for extracting data from PDF documents as well as analyzing, converting, and manipulating them (recent versions also handle

graph TD
    subgraph Offline
        Docs[("Offline documents")]
        Chunk["Document chunking"]
        Emb["Embeddings"]
        Docs --> Chunk
        Chunk --> EM1["Embedding model"]
        EM1 --> Emb
        Emb -->|Store| VS[("Vector store")]
    end
    subgraph Online
        User(["User"])
        User -->|Query| EM2["Embedding model"]
        EM2 --> QE["Query embeddings"]
        QE -->|Retrieve| VS
        VS --> Ctx["Enriched context (query + retrieved chunks)"]
        Ctx --> Gen["Generator model"]
        Gen --> Resp["Response"]
        Resp --> User
    end

[!visual-conversion] Figure 13.3 — The generic workflow of a RAG system (p. 274)

some other document types). The complete code for the examples in this section is available in a companion Colab notebook.

Keeping scalability in mind, let’s define a couple of utility functions for extracting document content that work regardless of how many PDF documents we need to process. The first function will remove newline characters from each extracted text chunk, but we can add other formatting rules later within its body:

def text_formatter(text: str):
cleaned_text = text.replace("\n", " ").strip()
return cleaned_text

The second function opens a PDF document, reads it page by page, extracts the text, and collects some statistics:

import fitz
def open_and_read_pdf(pdf_path: str) -> list[dict]:
doc = fitz.open(pdf_path)
pages_and_texts = []
for page_number, page in tqdm(enumerate(doc)):
text = page.get_text()
text = text_formatter(text)
pages_and_texts.append({"page_number": page_number + 1,
"page_char_count": len(text),
"page_word_count": len(text.split(" ")),
"page_sentence_count_raw":
len(text.split(". ")),
"page_token_count": len(text) / 4,
"text": text})
return pages_and_texts

The open_and_read_pdf function takes the path to a PDF as input. It returns a list of dictionaries, each with stats (page number, character count, word count, sentence count, and token count) and the extracted text. The text_formatter function formats each page’s raw text.

We’ll apply open_and_read_pdf to our PDF document (in this example, the “DeepSpeed-FastGen: High-throughput Text Generation for LLMs via MII and DeepSpeed-Inference” paper, https://arxiv.org/abs/2401.08671):

pdf_path = "2401.08671.pdf"
pages_and_texts = open_and_read_pdf(pdf_path)

The returned list contains 14 items—one dictionary for each page of the original document. Here’s a sample:

{'page_number': 1,
'page_char_count': 2979,
'page_word_count': 410,
'page_sentence_count_raw': 15,
'page_token_count': 744.75,
'text': 'DeepSpeed-FastGen: High-throughput Text Generation for LLMs via MII and DeepSpeed-Inference Connor Holmes, Masahiro Tanaka, Michael Wyatt, Ammar Ahmad Awan, Jeff Rasley, Samyam Rajbhandari, Reza Yazdani Aminabadi, Heyang Qin, Arash Bakhtiari, Lev Kurilenko, Yuxiong He Microsoft DeepSpeed (www.deepspeed.ai) Abstract The deployment and scaling of large language models (LLMs) have become critical as they permeate various applications, demanding high-throughput and low-latency serving systems. Existing frameworks struggle to balance these requirements, especially for workloads with long prompts. This paper introduces DeepSpeed-FastGen, a system that employs Dynamic SplitFuse, a novel prompt and generation composition strategy, to deliver up to 2.3x higher effective throughput, 2x lower latency on average, and up to 3.7x lower (token-level) tail latency, compared to state-of-the-art systems like vLLM. We leverage a synergistic combination of DeepSpeed-MII and DeepSpeed-Inference to provide an efficient and easy-to-use serving system for LLMs. DeepSpeed-FastGen's
advanced implementation supports a range of models and offers both non-persistent
and persistent deployment op- tions, catering to diverse user
scenarios from interactive sessions to long-running applica- tions. We
present a detailed benchmarking methodology, analyze the performance
through latency-throughput curves, and investigate scalability via load
balancing. Our evaluations demonstrate substantial improvements in
throughput and latency across various models and hardware configurations.
We discuss our roadmap for future enhancements, includ- ing broader model
support and new hardware backends. The DeepSpeed-FastGen code is readily
available for community engagement and contribution. 1 Introduction Large
language models (LLMs) like GPT-4 [1] and LLaMA [2] have emerged as a
dominant workload in serving a wide range of applications infused with AI
at every level. From general chat models to document summarization, and
from autonomous driving to copilots at every layer of the software stack,
the demand to deploy and serve these models at scale has skyrock- eted.
While frameworks like DeepSpeed, PyTorch [3], and several others can
regularly achieve good hardware utilization during LLM training, the
interactive nature of these applications and the poor arithmetic intensity
of tasks like open-ended text generation have become the bottleneck for
inference throughput in existing systems. To this end, frameworks like vLLM
[4] powered by PagedAttention and research systems like Orca [5] have
significantly improved the performance of inference for LLMs. However,
these systems still struggle to provide consistent quality of service,
particularly for workloads with longer prompts. These long prompt workloads
are becoming increasingly important as more and more models, like MPTStoryWriter
[6], and systems, such as DeepSpeed Ulysses [7], 1
arXiv:2401.08671v1 [cs.PF] 9 Jan 2024'

That is just the first step in our document preprocessing. Next, we’ll split the pages into sentences to make it easier to work with longer pages, especially those densely filled with text. We’ll use spaCy (https://github.com/explosion/spaCy), a fast, open source Python library for advanced NLP tasks. We must specify the document language (English, in this example), since spaCy supports more than 75 languages:

from spacy.lang.en import English
nlp = English()

We’ll also add a sentencizer pipeline (spaCy’s rule-based sentence boundary detector):

nlp.add_pipe("sentencizer")

Now we’ll apply the pipeline to text extracted from the original PDF:

for item in tqdm(pages_and_texts):
item["sentences"] = list(nlp(item["text"]).sents)
item["sentences"] = [str(sentence) for sentence in item["sentences"]]
item["page_sentence_count_spacy"] = len(item["sentences"])

In the preceding code snippet, we convert all text chunks to strings before spl them into sentences. We then add two keys to each dictionary in the list: sentence list of all the page’s sentences) and page_sentence_count_spacy (the page’s sent count).

Next, we need to split the sentences into smaller chunks to avoid exceedin embedding model’s token limit and the generator model’s context window. To that, we’ll define a function that splits a list into sublists of a target size (or as close possible):

def split_list(input_list: list, slice_size: int):
return [input_list[i:i + slice_size] for i in range(0,
len(input_list), slice_size)]

We’ll use it while looping through pages and texts, splitting sentences into chunks:

num_sentence_chunk_size = 10
for item in tqdm(pages_and_texts):
item["sentence_chunks"] = split_list(input_list=item["sentences"],
slice_size=num_sentence_chunk_size)
item["num_chunks"] = len(item["sentence_chunks"])

Now that the dictionaries contain the sentence chunks, we can build the chunks we’ll convert into embeddings. Let’s create a new list of dictionaries, each containing a single chunk of sentences along with the related metadata (page number and chunk statistics):

import re
import tqdm
pages_and_chunks = []
for item in tqdm(pages_and_texts):
for sentence_chunk in item["sentence_chunks"]:
chunk_dict = {}
chunk_dict["page_number"] = item["page_number"]
joined_sentence_chunk = "".join(sentence_chunk).replace(" ", " ").strip()
joined_sentence_chunk = re.sub(r'\.([A-Z])', r'. \1',
joined_sentence_chunk)
chunk_dict["sentence_chunk"] = joined_sentence_chunk
chunk_dict["chunk_char_count"] = len(joined_sentence_chunk)
chunk_dict["chunk_word_count"] = len([word for word in
joined_sentence_chunk.split(" ")])
chunk_dict["chunk_token_count"] = len(joined_sentence_chunk) / 4
pages_and_chunks.append(chunk_dict)

The sentences in each dictionary are combined into a paragraph-like chunk, and basic stats are collected for each chunk (sentence count, character count, and word count).

The resulting list is what we submit to the embedding model. This is the document chunking process that was illustrated in figure 13.3.

In this example, it produces 30 chunks. Here are two sample dictionaries after the document preprocessing step:

[{'page_number': 1,
'sentence_chunk': 'DeepSpeed-FastGen: High-throughput Text Generation for
LLMs via MII and DeepSpeed-Inference Connor Holmes, Masahiro Tanaka,
Michael Wyatt, Ammar Ahmad Awan, Jeff Rasley, Samyam Rajbhandari, Reza
Yazdani Aminabadi, Heyang Qin, Arash Bakhtiari, Lev Kurilenko, Yuxiong He
Microsoft DeepSpeed (www.deepspeed.ai) Abstract The deployment and scaling
of large language models (LLMs) have become critical as they permeate
various applications, demanding high-throughput and low-latency serving
systems. Existing frameworks struggle to balance these requirements,
especially for work- loads with long prompts. This paper introduces
DeepSpeed-FastGen, a system that em- ploys Dynamic SplitFuse, a novel
prompt and generation composition strategy, to deliver up to 2.3x higher
effective throughput, 2x lower latency on average, and up to 3.7x lower
(token-level) tail latency, compared to state-of-the-art systems like vLLM.
We leverage a synergistic combination of DeepSpeed-MII and DeepSpeed-Inference
to provide an efficient and easy-to-use serving system for LLMs.
DeepSpeed-FastGen's advanced implementation supports a range of models and
offers both non-persistent and persistent deployment op- tions, catering to
diverse user scenarios from interactive sessions to long-running applications
. We present a detailed benchmarking methodology, analyze the
performance through latency-throughput curves, and investigate scalability
via load balancing. Our evaluations demonstrate substantial improvements in
throughput and latency across various models and hardware configurations.
We discuss our roadmap for future enhancements, includ- ing broader model
support and new hardware backends. The DeepSpeed-FastGen code is readily
available for community engagement and contribution.1 Introduction Large
language models (LLMs) like GPT-4 [1] and LLaMA [2] have emerged as a
dominant workload in serving a wide range of applications infused with AI
at every level.',
'chunk_char_count': 1954,
'chunk_word_count': 258,
'chunk_token_count': 488.5},
{'page_number': 1,
'sentence_chunk': 'From general chat models to document summarization,
and from autonomous driving to copilots at every layer of the software
stack, the demand to deploy and serve these models at scale has skyrocketed
. While frameworks like DeepSpeed, PyTorch [3], and several others can
regularly achieve good hardware utilization during LLM training, the
interactive nature of these applications and the poor arithmetic intensity
of tasks like open-ended text generation have become the bottleneck for
inference throughput in existing systems. To this end, frameworks like vLLM
[4] powered by PagedAttention and research systems like Orca [5] have
significantly improved the performance of inference for LLMs. However,
these systems still struggle to provide consistent quality of service,
particularly for workloads with longer prompts. These long prompt workloads
are becoming increasingly important as more and more models, like MPTStoryWriter
[6], and systems, such as DeepSpeed Ulysses [7], 1
arXiv:2401.08671v1 [cs. PF] 9 Jan 2024',
'chunk_char_count': 1022,
'chunk_word_count': 150,
'chunk_token_count': 255.5]

The embedding process (shown in figure 13.3) uses sentence-transformers (https://github.com/UKPLab/sentence-transformers/), a Python open source library that computes dense vector representations for sentences, paragraphs, and images. It provides BERT-family models (encoder-only Transformer architecture) hosted on the Hugging Face Hub. The model embeds text into a vector space so that similar texts are close together, which makes retrieval more efficient using cosine similarity or another metric.

First, we need to download the chosen embedding model:

from sentence_transformers import SentenceTransformer
embedding_model = SentenceTransformer(
model_name_or_path="all-mpnet-base-v2",
device="cpu")

In this example, we’ve selected all-mpnet-base-v2 (https://huggingface.co/sentence-transformers/all-mpnet-base-v2), a sentence-embedding model that maps sentences and paragraphs to a 768-dimensional vector space. The model is fine-tuned on a 1B sentence-pair dataset using a contrastive learning objective for tasks such as clustering and semantic search. If they aren’t already on disk, the model checkpoints are downloaded from the Hugging Face Hub and loaded into memory; this code example doesn’t require hardware acceleration.

NOTE With contrastive learning, the model is trained to maximize the similarity between positive pairs and minimize it between negative pairs. Positive pairs are two different views of the same instance, while negative pairs are views from different instances. This is becoming a new trend for specializing small embedding models used in RAG systems.

Finally, we can apply the model to each chunk to generate embeddings (the embeddings block in figure 13.3) and store them under a new dictionary key named embedding:

embedding_model.to("cpu")
for item in tqdm(pages_and_chunks):
item["embedding"] = embedding_model.encode(item["sentence_chunk"])

A RAG system typically uses a vector database (the vector store in figure 13.3) to store and index document embeddings for faster, scalable search. We’ll cover vector storage later in this section.

For a local deployment, a vector store may be overkill. For now, to see how embedding search works under the hood, we’ll implement it without one. We’ll create a pandas DataFrame from the embedding list and save it as a CSV file:

import pandas as pd
text_chunks_and_embeddings_df = pd.DataFrame(pages_and_chunks)
embeddings_df_save_path = "text_chunks_and_embeddings_df.csv"
text_chunks_and_embeddings_df.to_csv(embeddings_df_save_path, index=False)

Now let’s look at how search works on these embeddings. We’re emulating what happens when you use a vector database. First, we’ll load the embeddings and their corresponding texts into a DataFrame:

text_chunks_and_embedding_df =
pd.read_csv("text_chunks_and_embeddings_df.csv")

We’ll convert the embedding column from a string back to a NumPy array

import numpy as np
text_chunks_and_embedding_df["embedding"] =
text_chunks_and_embedding_df["embedding"].apply(
lambda x: np.fromstring(x.strip("[]"),
sep=" ")

and we’ll convert the DataFrame to a list of dictionaries:

pages_and_chunks = text_chunks_and_embedding_df.to_dict(orient="records")

Finally, we’ll convert the embeddings to Torch tensors and move them to the device (the CPU in this example):

device = "cpu"
embeddings = torch.tensor(np.array(
text_chunks_and_embedding_df["embedding"].tolist()
),
dtype=torch.float32
).to(device)

With the embeddings in memory, we can start querying. Let’s search for a general topic, “blocked KV-cache,” mentioned in the original paper, whose text we converted into embeddings:

query = "blocked KV-cache"

We’ll use the all-mpnet-base-v2 embedding model to embed the query in the sar vector space as the document text (see the query embedding block in figure 13.3). V must embed the prompts with the same model we used to build the knowledge base:

query_embedding = embedding_model.encode(query, convert_to_tensor=True)

Given this query, the ideal results should include information about the blocked KV-caching strategy described in the original paper. We’ll use similarity search. Unlike keyword-based text search, similarity search compares vectors, so the final results include not only the words in the query string but also other text that matches the query’s meaning. Both the Sentence Transformers library and the PyTorch framework include built-in methods for finding similar vectors.

In this example, we’ll use the Sentence Transformers API, since we’re already using this library for embedding text. The most popular algorithms for this type of search (also built into most vector databases) are

  • Dot product—The dot product measures the magnitude and direction between two vectors. Vectors aligned in direction and magnitude have a higher positive value, while opposite vectors have a higher negative value.
  • Cosine similarity—With cosine similarity, vectors are normalized by magnitude, Euclidean norm, or L2 norm, so that they have unit length, and they are compared by direction. Vectors aligned in direction score close to 1, while vectors in opposite directions score close to -1.

Cosine similarity is typically used for text similarity because it measures semantic similarity (via direction). But because we embedded our document with the all-mpnet-base-v2 model, which always returns normalized outputs, cosine similarity and dot product return the same results.

Let’s try cosine similarity and take the top five scores:

import torch
from sentence_transformers import util
cosine_scores = util.cos_sim(a=query_embedding, b=embeddings)[0]
top_results_cosine_sim = torch.topk(cosine_scores, k=5)

This query returns the following results:

torch.return_types.topk(
values=tensor([0.2963, 0.1960, 0.1868, 0.1395, 0.1132]),
indices=tensor([ 3, 5, 11, 13, 27]))

The values here are relevance scores, and the indices are the page numbers for the top five returned chunks. The top two results (the highest-scoring ones) relate directly to the blocked KV-caching strategy:

Query: ‘blocked KV-cache’

Results:
Score: 0.2963
Text:
The blocked KV-cache increases system throughput by increasing the amount of potential sequence concurrency by eliminating KV-cache induced memory fragmentation. Non-contiguous KV cache implementations are also included in Hugging
Face TGI [9] and NVIDIA TensorRT-LLM [10].2.2 Continuous Batching In
the
past, dynamic batching, in which a server would wait for multiple requests to process in phase with each other, was used to improve GPU utilization. However, this approach has drawbacks, as it typically requires padding inputs to identical lengths or stalling the system to wait to construct a larger batch. Recent advancement in large language model (LLM) inference and serving has been fo- cusing on fine granularity scheduling and optimizing memory efficiency. For instance, Orca proposes iteration-level scheduling (also known as continuous batching) which makes distinct scheduling decisions at each forward pass of the model. This allows requests to join/leave the batch as needed, eliminating the need for padding requests thus improving the overall through- put. In addition to Orca, continuous batching has been implemented in NVIDIA TRT-LLM, HuggingFace TGI, and vLLM. In current systems, there are two primary approaches to implement continuous batching. In TGI and vLLM, the generation phase is preempted to perform prompt processing (called infill in TGI) before continuing with generation. Page number: 2
Score: 0.1960
Text:
doesn't reach a fixed bound. These approaches to varying degrees need to stall generation to process long prompts (see Section 3.2). We propose a novel prompt and generation composition strategy, Dynamic SplitFuse dis- cussed at length in the next section.3 Dynamic SplitFuse: A Novel Prompt and Generation Composition Strategy DeepSpeed-FastGen is built to leverage continuous batching and non-contiguous KV caches to enable increased occupancy and higher responsiveness for serving LLMs in the data center, similar to existing frameworks such as TRT-LLM,

TGI, and vLLM. In order to achieve a new level of performance, DeepSpeed-FastGen introduces SplitFuse which leverages dynamic prompt and generation decomposition and unification to further improve continuous batching and system throughput.3.1 Three Performance Insights Before describing Dynamic SplitFuse, we answer three key performance questions that together motivate its design.3.1.1 What factors impact the forward pass of a single LLM? In order to effectively schedule, it is necessary to understand what are the relevant independent variables the scheduling loop should control. We observe below that the composition of sequences in a forward pass (the batch size in sequences) has a negligible impact on performance compared to the raw number of tokens in the forward pass. This means an effective scheduler can be built around a single signal, the number of tokens in the forward pass. Page number: 3

Let’s now run the same search with the dot product algorithm:

dot_scores = util.dot_score(a=query_embedding, b=embeddings)[0]

We can observe the same results, as expected:

torch.return_types.topk(
values=tensor([0.2963, 0.1960, 0.1868, 0.1395, 0.1132]),
indices=tensor([ 3, 5, 11, 13, 27]))

As you can see in figure 13.4 (shown earlier in figure 13.3), the retrieval and the generation are done by two distinct LLMs: the embedding model and the generator model. So far, we have discussed only the retrieval phase. Let’s look at how we can do local generation by enriching the user query with retrieved content.

The Hugging Face Hub hosts many small models that can generate high-quality answers. The choice of generation model and precision format mainly depends on your available local hardware. Because this example runs on a free-tier Colab VM without hardware acceleration, a GGUF model (a 4-bit quantized version of the original) is a good fit. We’ll use microsoft/Phi-3-mini-4k-instruct-gguf, which we used in section 11.1.1 and which is available on the Hugging Face Hub (https://huggingface.co/microsoft/Phi-3-mini-4k-instruct-gguf). To keep the end-to-end solution in Python, we’ll download and run the GGUF model with the Python bindings for llama.cpp, llama-cpp-python (https://github.com/abetlen/llama-cpp-python), which you can install on any OS via PyPI.

[!visual-conversion] Figure 13.4 — The generic workflow of a RAG system (same diagram as Figure 13.3) (p. 284)

Downloading the model from the Hugging Face Hub is as simple as with the Transformers API:

from llama_cpp import Llama
llm = Llama.from_pretrained(
repo_id="microsoft/Phi-3-mini-4k-instruct-gguf",
filename="*-q4.gguf",
verbose=False,
n_ctx=1024
)

We are using the from_pretrained method of the Llama class, which requires the model ID from the Hugging Face Hub and the checkpoint filename you want to download. We’ve also set the context-window size: the original model uses 4,096 tokens, but from_pretrained defaults to 512. This method returns a model loaded into memory and ready for inference.

We’ll now use the same query as in the previous example and run the same retrieval on our knowledge base, requesting the top two results, because we’ve already verified that those are the most relevant for this query:

query = "blocked KV-cache"
query_embedding = embedding_model.encode(query, convert_to_tensor=True)
cosine_scores = util.cos_sim(a=query_embedding, b=embeddings)[0]
scores, indices = torch.topk(cosine_scores, k=2)

Next, we’ll create a list of context items to enrich the generation prompt:

context_items = [pages_and_chunks[i] for i in indices]

Now we need to implement a custom function that formats the prompt for the generator model during the generation phase, augmenting the user query with the retrieved context items:

def prompt_formatter(query: str,
context_items: list[dict],
tokenizer):
context = "- " + "\n- ".join([item["sentence_chunk"]
for item in context_items])
base_prompt = """Based on the following context items, please answer the query.
Make sure your answers are as explanatory as possible.
\nUse the following context items to answer the user query:
{context}
\nRelevant passages: <extract relevant passages from the context here>
User query: {query}
Answer:"""
base_prompt = base_prompt.format(context=context, query=query)
dialogue_template = [
{"role": "user",
"content": base_prompt}
]
prompt = tokenizer.apply_chat_template(conversation=dialogue_template,
tokenize=False,
add_generation_prompt=True)
return prompt

The prompt_formatter function takes as input the user prompt, the retrieved context items, and the generator’s tokenizer. It joins the retrieved chunks together, merges them into the base prompt with the user query, applies the model’s chat template, and returns the result. The base prompt shown here is tuned for Phi-3 Mini 4k Instruct; it might need adjustments for other generator models.

We’ll use the Phi-3 Mini 4k Instruct model’s tokenizer to format the prompt for the generator:

from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained(
"microsoft/Phi-3-mini-4k-instruct")

Let’s format the generator prompt using the function we implemented:

prompt = prompt_formatter(query=query,
context_items=context_items,
tokenizer=tokenizer)

The formatted prompt looks like this:

<|user|>
Based on the following context items, please answer the query.
Make sure your answers are as explanatory as possible.
Use the following context items to answer the user query:
- The blocked KV-cache increases system throughput by increasing the amount of potential sequence concurrency by eliminating KV-cache induced memory fragmentation. Non-contiguous KV cache implementations are also included in Hug- gingFace TGI [9] and NVIDIA TensorRT-LLM [10].2.2 Continuous Batching In the past, dynamic batching, in which a server would wait for multiple requests to process in phase with each other, was used to improve GPU utilization. However, this approach has drawbacks, as it typically requires padding inputs to identical lengths or stalling the system to wait to construct a larger batch. Recent advancement in large language model (LLM) inference and serving has been fo- cusing on fine granularity scheduling and optimizing memory efficiency. For instance, Orca proposes iteration- level scheduling (also known as continuous batching) which makes distinct scheduling decisions at each forward pass of the model. This allows requests to join/leave the batch as needed, eliminating the need for padding requests thus improving the overall through- put. In addition to Orca, continuous batching has been implemented in NVIDIA TRT-LLM, HuggingFace TGI, and vLLM. In current systems, there are two primary approaches to implement continuous batching. In TGI and vLLM, the generation phase is preempted to perform prompt processing (called infill in TGI) before continuing with generation.
- doesn't reach a fixed bound. These approaches to varying degrees need to stall generation to process long prompts (see Section 3.2). We propose a novel prompt and generation composition strategy, Dynamic SplitFuse dis- cussed at length in the next section.3 Dynamic SplitFuse: A Novel Prompt and Generation Composition Strategy DeepSpeed-FastGen is built to leverage continuous batching and non-contiguous KV caches to enable increased occupancy and higher responsivity for serving LLMs in the data center, similar to existing frameworks such as TRT-LLM, TGI, and vLLM.iIn order to achieve a new level of performance, DeepSpeed-FastGen introduces SplitFuse
which leverages dynamic prompt and generation decomposition and unification
to further improve continuous batching and system throughput.3.1 Three
Performance Insights Before describing Dynamic SplitFuse, we answer three
key performance questions that together motivate its design.3.1.1 What
factors impact the forward pass of a single LLM?In order to effectively
schedule, it is necessary to understand what are the relevant independent
variables the scheduling loop should control. We observe below that the
composition of se-quences in a forward pass (the batch size in sequences)
has a negligible impact on performance compared to the raw number of tokens
in the forward pass. This means an effective scheduler can be built around
a single signal, the number of tokens in the forward pass.
Relevant passages: <extract relevant passages from the context here>
User query: blocked KV-cache
Answer: <end>
<|assistant|>

Finally, we’ll run the generation with the GGUF model, using the enriched prompt:

output = llm(
prompt,
max_tokens=None,
stop=["Q:", "\n"],
echo=True
)

We’ll then get the model’s answer:

From the provided context, it can be understood that a blocked KV-cache increases system throughput by eliminating KV-cache induced memory fragmentation. This is achieved by increasing the amount of potential sequence concurrency. Non-contiguous KV cache implementations are also included in HuggingFace TGI [9] and NVIDIA TensorRT-LLM [10].

In the previous section, we explored a RAG example in which the knowledge base was built from a single PDF. In local deployments, where you typically have only a few documents—represented by at most a few hundred thousand embeddings—it’s fine to persist the embeddings to disk. But to scale up, you’ll want a vector database (often called a vector store).

A vector database stores vectors (fixed-length lists of numbers) along with other data. It typically implements one or more approximate nearest neighbor (ANN) algorithms, enabling you to search with a query vector and retrieve the closest-matching records. These databases have many applications, but since 2024, they’ve become a key component of most RAG systems.

Many implementations are available, both open source and commercial. These are some popular open source vector databases:

For the examples in this section, we’ll use LanceDB because it’s easy to set up and maintain locally, and it scales well when you move to a distributed environment. It’s a serverless vector search database with persistent storage that simplifies retrieval, filtering, and embedding management. It supports vector similarity search, full-text search, and SQL, with native Python and JavaScript/TypeScript support. It also supports zero-copy data access and automatic versioning without extra infrastructure, and it integrates with popular LLM frameworks like LangChain and LlamaIndex, as well as data libraries such as Apache Arrow, pandas, and Polars.

Let’s return to the previous section’s example to see how we can integrate a LanceDB database into it. First, we’ll install the LanceDB library with pip:

Terminal window
pip install lancedb

We can now create an empty local database instance:

import lancedb
db = lancedb.connect("paperdb")

Our approach for preparing the embeddings and related metadata earlier in section 13.2 is still valid. The only change needed to allow for proper ingestion into a LanceDB table is to convert the embedding column from arrays to strings and then to NumPy arrays:

import numpy as np
text_chunks_and_embeddings_df['embedding_str'] = \
text_chunks_and_embeddings_df['embedding'].apply(
lambda x: np.array2string(x, separator=',')[1:-1]
)
text_chunks_and_embedding_df['embedding_final'] = \
text_chunks_and_embedding_df['embedding_str'].apply(
lambda x: np.fromstring(x, sep=',')
)

We now need to prepare the data as a list of dictionaries—the format LanceDB expects when ingesting a table.

Listing 13.1 Preparing data for ingestion into LanceDB

final_data = []
for row in text_chunks_and_embedding_df_load.itertuples(index=False): temp = {}
temp["page_number"] = row.page_number
temp["chunk_char_count"] = row.chunk_char_count
temp["chunk_word_count"] = row.chunk_word_count
temp["chunk_token_count"] = row.chunk_token_count
temp["sentence_chunk"] = row.sentence_chunk
temp["embedding"] = np.array(row.embedding_final)
final_data.append(temp)
data_dict = {}
for key in final_data[0].keys():
data_dict[key] = [d[key] for d in final_data]

Listing 13.1 annotations (printed as margin callouts beside the code):

  1. Get column names from the first dictionary — for key in final_data[0].keys():

Let’s create and populate a table, paper_embeddings_table, following a custom schema, indicated in the following table-creation code.

Listing 13.2 Definition of the schema for the embedding table in the LanceDB database

import pyarrow as pa
table = db.create_table(
"paper_embeddings_table",
data=pa.Table.from_pydict(data_dict),
mode="overwrite",
schema=pa.schema([
("page_number", pa.int64()),
("chunk_char_count", pa.int64()),
("chunk_word_count", pa.int64()),
("chunk_token_count", pa.float64()),
("sentence_chunk", pa.string()),
("embedding", pa.list_(pa.float32(), list_size=768)),
]),
)

The dataset is converted to a PyArrow table before being passed to the data attribute.

Finally, we’ll create an ANN index on the embedding column to speed up searches by avoiding brute-force scans of the vector space. We’ll also specify the similarity algorithm (cosine similarity in this case):

db["paper_embeddings_table"].create_index(
metric="cosine",
vector_column_name="embedding",
index_type="IVF_FLAT",
)

We’ll run the same prompt as in the earlier examples, but search the LanceDB table this time and limit the results to three:

query = "blocked KV-cache"
query_embedding = embedding_model.encode(query, convert_to_tensor=False)
results = db["paper_embeddings_table"].search(
query_embedding,
vector_column_name="embedding"
).limit(3).to_list()

This yields the following results:

Search results:
Score = 0.7036938667297363
The blocked KV-cache increases system throughput by increasing the amount
of potential sequence concurrency by eliminating KV-cache induced memory
fragmentation. Non-contiguous KV cache implementations are also included in
Hug- gingFace TGI [9] and NVIDIA TensorRT-LLM [10].2.2 Continuous Batching
In the past, dynamic batching, in which a server would wait for multiple
requests to process in phase with each other, was used to improve GPU
utilization. However, this approach has drawbacks, as it typically requires
padding inputs to identical lengths or stalling the system to wait to
construct a larger batch. Recent advancement in large language model (LLM)
inference and serving has been fo- cusing on fine granularity scheduling
and optimizing memory efficiency. For instance, Orca proposes iteration-level
scheduling (also known as continuous batching) which makes distinct
scheduling decisions at each forward pass of the model. This allows
requests to join/leave the batch as needed, eliminating the need for
padding requests thus improving the overall throughput. In addition to
Orca, continuous batching has been implemented in NVIDIA TRT-LLM,
HuggingFace TGI, and vLLM. In current systems, there are two primary
approaches to implement continuous batching. In TGI and vLLM, the
generation phase is preempted to perform prompt processing (called infill
in TGI) before continuing with generation.
Page = 2
Score = 0.8040012121200562
doesn't reach a fixed bound. These approaches to varying degrees need to
stall generation to process long prompts (see Section 3.2). We propose a
novel prompt and generation composition strategy, Dynamic SplitFuse discussed
at length in the next section.3 Dynamic SplitFuse: A Novel Prompt
and Generation Composition Strategy DeepSpeed-FastGen is built to leverage
continuous batching and non-contiguous KV caches to enable increased
occupancy and higher responsiveness for serving LLMs in the data center,
similar to existing frameworks such as TRT-LLM, TGI, and vLLM.iIn order to
achieve a new level of performance, DeepSpeed-FastGen introduces SplitFuse
which leverages dynamic prompt and generation decomposition and unification
to further improve continuous batching and system throughput.3.1 Three
Performance Insights Before describing Dynamic SplitFuse, we answer three
key performance questions that together motivate its design.3.1.1 What
factors impact the forward pass of a single LLM?In order to effectively
schedule, it is necessary to understand what are the relevant independent
variables the scheduling loop should control. We observe below that the
composition of se- quences in a forward pass (the batch size in sequences)
has a negligible impact on performance compared to the raw number of tokens
in the forward pass. This means an effective scheduler can be built around
a single signal, the number of tokens in the forward pass.
Page = 3
Score = 0.8131694793701172
Consequently, DeepSpeed-FastGen will consume tokens from incoming prompts
at a rate that permits fast ongoing generation while adding tokens to the
system that increase system utilization, providing lower latency and higher
throughput streaming generation to all clients as compared to other state-of
-the-art serving systems.4 Performance Evaluation DeepSpeed-FastGen
provides state-of-the-art LLM serving performance leveraging its blocked KV
cache and Dynamic SplitFuse continuous batching. We evaluate DeepSpeed-FastGen
against vLLM [4] on a range of models and hardware configurations
following the benchmarking methodology discussed below. The evaluation
shows that DeepSpeed-FastGen achieves up to 2.3x higher effective
throughput, 2x lower latency on average, and up to 3.7x lower (token-level)
tail latency, compared to state-of-the-art systems like vLLM.4.1
Benchmarking Methodology We use two primary quantitative schemes for
measuring performance.4.1.1 Throughput-Latency Curves Two key metrics for
production readiness are throughput (measured in requests per second) and
latency (the responsiveness of each request). To measure this, we
instantiate multiple clients (ranging from 1 to 32) concurrently and send
requests (512 in total) to the server. The resulting latency of each
request is measured at the endpoint and throughput is measured by the end-to
-end time to complete the experiment.4.1.2 Effective Throughput
Interactive applications, such as chat applications, can have more
stringent and complex re-quirements than can be captured by top-level
metrics like end-to-end latency. In particular, we focus on the
increasingly popular chat user scenario: 1.
Page = 6

At first glance, comparing the relevance scores, the one for retrieval from a vector store looks higher than the one for naive retrieval in section 13.2.

Let’s see how these retrieved documents affect the generated answer by comparing it with the previous example. Because we’re using the same model (Phi-3 Mini 4k Instruct GGUF), we can reuse the earlier Python generation code. Here’s the generated answer after enriching the user prompt with the top two results from the database:

From the provided context, it can be understood that a blocked KV-cache increases system throughput by eliminating KV-cache induced memory fragmentation. This is achieved by increasing the amount of potential sequence concurrency. Non-contiguous KV cache implementations are also included in HuggingFace TGI [9] and NVIDIA TensorRT-LLM [10].

In this example, the quality is similar to the previous approach. But on a larger, noisier knowledge base with more diverse topics, storing data in a database and using index-based retrieval improves retrieval and answer quality.

In summary, best document-chunking practices and a vector database make a RAG solution more reliable, performant, and scalable. You can improve it further with the advanced RAG strategies we’ll cover in chapter 14.

Agentic AI was 2025’s big buzzword in the generative AI hype, primarily driven by big tech, large consulting firms, and self-proclaimed AI gurus. Although agentic AI is an

important way to use language models, many so-called agentic systems are really just RPA (robotic process automation) applications that use a model in the usual way: a prompt goes in, the model generates output, and the rest of the solution consumes it.

In this section, we’ll clarify the topic and cover the basics of building an agent locally using open source components. Agentic AI is a big subject, so this is a hands-on introduction ; we’ll look at more advanced concepts in the next chapter.

A language model, large or small, predicts the most likely next token for a given prompt. By sampling tokens repeatedly, it can carry on a conversation and handle many tasks, especially when specialized to a narrow domain with high-quality data. Still, this approach has limitations. As a chat continues, the model can lose earlier context because of the limitations of its context window. Language models also often struggle with tasks such as math (even basic multiplication and division) and logic, which is expected given how these models work. In addition, because transformers generate the best next token for the text they are given, if the input has been enriched with outdated or incorrect context, the output may fit that input perfectly while still being wrong for the original question. These limitations highlight the need for short- and long-term memory management, access to external tools, more accurate, up-to-date information (including from the web), and ways to break problems into steps and refine initial answers. This is a scenario that fits the idea of an AI agent.

A software system can be defined as an AI agent when it can autonomously perform tasks and make decisions on a user’s behalf, using AI to learn, adapt, and pursue specific goals. An AI agent must be able to reason (analyze the prompt and related context, if provided, and determine next steps), act (execute tasks by calling external tools or APIs), and interact (communicate with other agents or users to solve problems collaboratively). Agents fall into different categories, but before we get to that classification, we’ll expand on these capabilities and start implementing our first agent system.

Imagine asking a specialized language model to plan a weeklong trip from Dublin to New York. The workflow might look like this:

1 A user asks the model for a list of accommodation options. 2 The model returns a list of options (hotels, B&Bs, and short-stay apartments). 3 The user asks for a list of return flights from Dublin to New York for specific dates. 4 The model returns round-trip flight options from Dublin to New York. 5 The user manages everything using information provided by the model.

Now let’s look at the same scenario in an agentic system:

1 A user gives the model a trip-planning request prompt (Dublin to New York). 2 The agent searches various sites for hotels, B&Bs, and short-stay apartment options in the destination city.

3 The agent queries multiple online sources for return flights from Dublin to New York for the given period.

4 The agent determines the best combination of flights and accommodations.

5 The agent also suggests other trip options, such as car rentals, local travel cards, and places to visit.

6 The agent listens to the user’s feedback.

7 Once the user is satisfied with the agent’s suggestions, the agent makes the bookings.

Comparing the two systems highlights the agents’ reasoning, action, and interaction capabilities. In the agentic scenario, we can see the core traits of agentic AI: a plan (the user prompt to organize a trip), reasoning that breaks the plan into steps, tool selections (such as a web browser and an online booking system), and actions (using those tools and their outputs).

Implementing an AI agent doesn’t require coding everything from scratch because many open-source frameworks are already available. In this section, we’ll use Hugging Face’s smolagents (https://github.com/huggingface/smolagents). It’s a small library (just over 1,000 lines of code at the time of writing), and its API is easy to learn and use.

smolagents integrates with other Hugging Face libraries we’ve used in this book, such as Transformers. It’s not limited to models hosted on the Hugging Face Hub or Hugging Face endpoints; it also supports OpenAI, Azure OpenAI, and Together AI endpoints; OpenAI-compatible servers; and LiteLLM and Ollama servers. smolagents supports models that handle multiple types of content (text, images, video, and audio), but we’ll focus on text only. Implemented in Python, smolagents also integrates easily with other LLM frameworks such as LangChain, LangGraph, and Anthropic’s MCP.

smolagents comes with two built-in agent implementations: CodeAgent and ToolCallingAgent. CodeAgent is the default and is recommended by the framework’s authors. At each step, it writes and executes Python snippets. By default, execution happens in your local environment. This is generally safe because the agent can call only its configured tools plus a predefined set of safe functions from native modules, and the Python interpreter blocks imports by default except from a safe list. For production (anything beyond your laptop or phone), smolagents supports safer execution in Docker or E2B (https://github.com/e2b-dev) sandboxes.

CodeAgent largely follows the classic ReAct (reasoning and acting) pattern, a framework for building AI agents that interleave reasoning and tool use to execute tasks (matching the definition of an agent introduced earlier in this section). ReAct agents use LLMs to analyze problems, choose tools, and iterate toward a solution. In CodeAgent, the model expresses its actions as Python code snippets.

Figure 13.5 shows the CodeAgent workflow. As you can see, building an agent requires at least one LLM, a memory manager, and a set of tools.

graph TD
    Task(["(task)"]) --> Add["Add task to agent memory"]
    Add --> Mem["Agent memory"]
    subgraph The ReAct loop
        Mem --> Chat["Memory as chat messages"]
        Chat --> Gen["Generate from agent's LLM"]
        Gen --> Parse["Parse output to extract code action"]
        Parse --> Exec["Execute code (tool calls are written as functions)"]
        Exec -->|"No call to the final answer tool; execution logs are stored in memory and the agent keeps running"| Mem
    end
    Exec -->|Call to the final answer tool| Final["Return the final answer"]

[!visual-conversion] Figure 13.5 — The logical workflow of CodeAgent (p. 294)

Let’s configure these components and build a CodeAgent programmatically. First, we’ll install the smolagents package:

Terminal window
pip install smolagents

In its simplest form, a CodeAgent looks like this:

from smolagents import CodeAgent, HfApiModel
model_id = "<model_id>"
model = HfApiModel(model_id=model_id, token="<huggingface_api_token>")
agent = CodeAgent(tools=[], model=model, add_base_tools=True)

The HfApiModel class indicates that the LLM is served through a Hugging Face endpoint. We pass the model ID from the Hugging Face Hub and the Hugging Face API token for authentication. We then define the agent with the CodeAgent class, providing the model and the list of tools the agent is allowed to use. Setting add_base_tools to True adds the default toolbox on top of the tools listed in tools.

To start the agent, we call the run method on the CodeAgent instance:

agent.run("<user_task>")

Execution stops if the agent generates code that attempts an illegal operation, tries to install an unauthorized package, or triggers a Python error.

The framework provides a default toolbox, which we added at initialization using the add_base_tools argument. It includes the following tools:

  • DuckDuckGo web search—Performs web searches with DuckDuckGo (https://duckduckgo.com/).
  • Google web search—Performs web searches using the Google Search API.
  • Python code interpreter—Runs LLM-generated Python code in a secure environment. Add this tool only to the ToolCallingAgent, since code-based agents can execute Python natively.
  • Speech-to-text—A Whisper-Turbo–based pipeline that transcribes audio to text.
  • User input—Asks for user input on a specific question.
  • Visit web page—Visits a URL and returns the web page content as a Markdown string.
  • Final answer—Called by an agent to return the final answer after it completes planning and execution.

smolagents agents aren’t limited to using the default tool set. You can add new tools programmatically in two ways. First, you can use the @tool function decorator:

from smolagents import tool
@tool
def find_acomodation_options(query: str):
...

You can also implement them as Python classes:

from smolagents import Tool
class FindAccomodationoptionsTool(Tool):
...

Before we get hands-on with agents, let’s first look at the other built-in agent class, ToolCallingAgent. This implementation writes actions as JSON-like blobs. That was the original approach in early LLM-based agents: they were prompted to generate actions as JSON (or other predefined text formats). The downside is a constrained action space (the set of predefined tools) and limited flexibility. The paper “Executable Code Actions Elicit Better LLM Agents” (https://arxiv.org/abs/2402.0130) was the first to propose using executable Python code to unify an agent’s action space. Its experiments suggest that when agents act by executing interpretable code and collaborate with users in natural language, they can address these limits and perform better (see figure 13.6, from the paper). This is a valid reason to follow Hugging Face’s recommendation to use CodeAgent rather than ToolCallingAgent for your custom agent implementations.

dslm-fig-13.6-comparing-text-json-and-a.png

[!visual-conversion] Figure 13.6 — Comparing text, JSON, and a code interpreter as actions on the same example task. At the top are the generated steps, and below are the quantitative results across LLMs. (p. 296)

Let’s now build a custom local agent and tools with this framework. A companion Colab notebook includes the full code. To run it on Colab’s free-tier VM, you’ll need GPU acceleration.

We’ll build an agent that can book flights, managing the full flow from a single prompt. Because we’re using a small local model, we’ll use smolagents’ Transformers-Model class to download models from the Hugging Face Hub and run them locally:

import torch
from smolagents import TransformersModel
model = TransformersModel("HuggingFaceTB/SmolLM2-1.7B-Instruct",
device_map="auto",
max_new_tokens=1000,
torch_dtype=torch.float16)

In this example, we’ll use SmoLLM2 1.7B Instruct (https://huggingface.co/HuggingFaceTB/SmolLM2-1.7B-Instruct), the largest model in the SmoLLM2 family pretrained by Hugging Face for the smolagents framework. The first time you run the preceding code snippet, it will download the model checkpoints, the tokenizer, and the configuration files. Note that you don’t have to choose a SmoLLM2 model when implementing custom agents with the framework’s TransformerModel class; any instruction-tuned model hosted on the Hub will work.

Now that we have the model, we can start implementing the tools we’ll add to the agent toolbox so it can complete its assigned tasks. In this example, we’ll implement tools as functions and decorate them with @tool.

The first function, search_for_flights, will search for and select a flight between the origin and destination airports. It will parse a mock web page to find flights that match the user-provided origin and destination, though you could adapt it to browse a real web page. Since this function only mocks a real search, and our goal is to understand the workflow of agents in smolagents, I won’t reproduce the code here. The companion notebook includes the full implementation along with a mock website (a multiline string) that lists flight information in the following schema:

1. Flight DUB-BOS123
- Price: $350
- Origin: Dublin Airport (DUB)
- Destination: Boston Logan International Airport (BOS)
- Date: January 10, 2025
2. Flight DUB-EWR456
- Price: $370
- Origin: Dublin Airport (DUB)
- Destination: Newark Liberty International Airport (EWR)
- Date: January 10, 2025
...

Next, we’ll implement a function that selects a seat for a given flight.

Listing 13.3 Tool for finding a seat for a flight

import random
@tool
def find_seat(flight: str, seat_class: str='Economy') -> str:
"""Finds a seat within a given flight.
Args:
flight: The flight code.
seat_class: The desired seat class.
Returns:
The seat number.
"""
if seat_class not in ['Business', 'Economy']:
raise ValueError("ticket_type must be either 'Business' or 'Economy'")
seat_type = random.choice(['A', 'B', 'C', 'D', 'E', 'F'])
if seat_class == 'Business':
seat_number = random.randint(1, 3)
else:
seat_number = random.randint(4, 32)
selected_seat = f"{seat_type}{seat_number}"
return selected_seat

The preceding function can pick a seat based on the specified class (business or economy); for simplicity, it generates a seat number at random. Each custom function you define as a tool must include a docstring describing what it does plus its inputs, outputs, and type hints, which the decorator uses to convert the function into a usable tool for an agent.

With our model and custom tools in place, we can build our flight-booking agent:

from smolagents import CodeAgent
custom_tools = [search_for_flights, find_seat]
agent = CodeAgent(tools=custom_tools, model=model,
verbosity_level=2, max_steps=2)

The preceding code is a CodeAgent. We’ve added tools to its default toolbox, selected the local SLM, set verbosity to 2 (info), and limited it to two steps (for now). We can provide a task and have the agent do the rest:

user_task = "Find a flight from Dublin to New York and then select a seat."
agent.run(user_task)

The agent first reasons about the assigned task and then splits it into steps. For each step, the agent selects the appropriate tool to search for a flight from Dublin to New York and choose a seat. It then generates Python code to execute each step and returns the results to the user. The logs from this run show the following two steps:

  • I will use the search_for_flights tool to find a flight from Dublin to New York.
  • I will use the find_seat tool to find a seat on the flight from Dublin to New York.

These steps include the tool that the agent has identified as the best fit for the ac In the first step, it generated the following Python code using the SLM:

origin = 'DUB'
destination = 'JFK'
date = '2023-01-01'
web_page = 'https://www.google.com/search?q =flights+from+Dublin+to+New+York+on+2023-01-01'
answer = search_for_flights(origin=origin, destination=destination,
date=date, web_page=web_page)
print(answer)

It calls the search_for_flights tool, passes the Dublin and JFK IATA codes (derived from the origin and destination city names), and attempts a web search (which won’t run here because the tool is restricted to a mock web page). This step returns two results because the page lists two flights for the same route on different dates:

[{'Flight Code': 'DUB-JFK789', 'Price': '400', 'Origin': 'dublin airport
(dub)', 'Destination': 'john f. kennedy
international airport (jfk)', 'Date': 'January 20, 2025'}, {'Flight Code':
'DUB-JFK101', 'Price': '450', 'Origin':
'dublin airport (dub)', 'Destination': 'john f. kennedy international
airport (jfk)', 'Date': 'January 10, 2025'}]

Because the task doesn’t specify which flight to choose, the agent selects the first result returned by the search.

Here’s the Python code generated for the second step:

flight_code = 'DUB-JFK789'
answer = find_seat(flight=flight_code)
print(answer)

The agent calls the find_seat tool using the code for the first flight returned in the previous step. Since the user didn’t specify a class, the agent defaults to economy. In this run, the tool returned seat D24.

Let’s make things a bit more complicated for the agent. We’ll add a third tool and see whether it affects the planning phase. The agent is still responsible for booking flights, but we’re introducing fibonacci, a tool unrelated to its main duties. It returns the n^th Fibonacci number (a sequence in which each number is the sum of the two preceding numbers, starting with 0 and 1). You can find the full code in the notebook. Let’s add it to the agent’s tool list:

custom_tools = [search_for_flights, find_seat, fibonacci]
agent = CodeAgent(tools=custom_tools, model=model,
verbosity_level=2, max_steps=2)

Now we’ll run the previous task again. When the agent receives the task, it identifies the same steps as it did when no fibonacci tool was available, and it produces the same Python code to execute them. Here we added only one unnecessary, task-unrelated tool for readability, but you should see the same behavior with a larger tool pool, where only a few tools are pertinent (assuming you’ve applied the tool-naming and typing guidance discussed earlier in this section).

We can extend this custom agent’s workflow by adding a tool that books the selected flight ticket (it’s a mock booking for now, but it will let us test how the agent plans a task).

Listing 13.4 Tool for mocking the flight ticket booking

@tool
def book_flight_ticket(flight: str, seat: str) -> str:
"""Books a flight ticket.
Args:
flight: The flight code.
seat: The seat number.
Returns:
The ticket number.
"""
ticket_number = random.randint(100000, 999999)
return f"Ticket booked for flight {flight} and seat {seat}\
. Ticket number: {ticket_number}"

We’ll add this tool to the agent’s toolbox and set the maximum number of steps to 3:

custom_tools = [search_for_flights, find_seat, book_flight_ticket]
agent = CodeAgent(tools=custom_tools, model=model,
verbosity_level=2, max_steps=3)

Now we’ll run the same tasks as in the previous examples:

user_task = "Find a flight from Dublin to New York and then select a seat."
agent.run(user_task)

The agent autonomously identifies three steps—searching for the ticket, selecting a seat, and booking the flight—even though the user doesn’t explicitly ask for these tasks. This is the final output from the model for this run:

Out: Ticket booked for flight DUB-JFK789 and seat B26. Ticket number: 798158

In this section, we’ve built a single agent that can use multiple tools. smolagents also supports multi-agent systems, where multiple agents interact and collaborate to solve more complex tasks. We’ll cover this in chapter 14.

Note that when implementing a local custom agent with smolagents, TransformersModel isn’t your only option for loading SLMs. You can also use models hosted on an Ollama server (covered in chapter 12). The overall workflow is the same.

In our flight-booking example, almost everything stays the same except for the model serving. First, we install a local Ollama server and start it running:

Terminal window
ollama serve

We can now download a quantized Phi-3 Mini 4K Instruct model:

Terminal window
ollama pull phi3:mini

The only code change required to switch the agent to this model is as follows:

from smolagents import LiteLLMModel
model = LiteLLMModel(
model_id="phi3:mini",
api_base="http://localhost:11434",
api_key="<your-api-key>",
num_ctx=4096
)

We’ll use the LiteLLMModel class, which requires the model ID from the Ollama server, the base URL (specifying the correct port if we are not using the default), the local API key, and the context size. Then we pass this model when creating the CodeAgent, as usual:

custom_tools = [search_for_flights, find_seat, book_flight_ticket]
agent = CodeAgent(tools=custom_tools, model=model,
verbosity_level=2, max_steps=3)

Here are a few best practices for building higher-quality agents with this framework; many of them apply to agentic AI development in general:

  • Use only instructed models.
  • Performance often depends on model size. For agentic API applications, very small models tend to underperform, unlike what we see in other applications. That doesn’t mean you can’t use SLMs, but models under 3 billion parameters may not deliver satisfactory results. Use an evaluation strategy appropriate for your chosen models.
  • Keep your agentic AI workflow design as simple as possible to reduce risk, cost, and latency.
  • Agentic systems combine deterministic components with probabilistic ones (the SLMs). Although these models can self-correct, a best practice is to make the system as deterministic as possible: give the model only tasks it can reliably complete, and shift any deterministic work to other parts of the architecture.
  • Whenever possible, combine two or more tools into one. This reduces the number of calls to SLMs, which lowers costs.
  • Keep tasks for SLMs simple and clear.
  • Ensure that for any data types the model handles through custom tools, you validate formats and value ranges. This reduces the chance of errors and simplifies your fallback strategy implementation.

In the next chapter, we’ll explore advanced RAG and AI agent concepts for SLM scenarios and look at how we can combine them.

  • Language models alone provide limited business value without being integrated into complex systems that add external knowledge and tools.
  • RAG systems enhance language models by retrieving information from external knowledge bases and generating text.
  • Document chunking splits large texts into smaller segments to avoid exceeding embedding and generator model capacity limits.
  • PyMuPDF extracts PDF content, and spaCy detects sentence boundaries for preprocessing.
  • The Sentence Transformers library converts text into dense vectors using encoder-only Transformer architectures.
  • Cosine similarity measures semantic relationships between query and document embeddings to retrieve relevant content.
  • Vector databases such as LanceDB store embeddings and use approximate nearest neighbor algorithms for fast similarity search.
  • LanceDB offers serverless vector storage with automatic versioning and zero-copy embedding management.
  • Embedding models must be identical for both creating a knowledge base and processing queries so the vectors share a consistent space.
  • Generator models receive enriched prompts containing user queries and retrieved context to produce informed responses.
  • Prompt-formatting functions combine user queries with retrieved context using model-specific chat templates.
  • AI agents autonomously perform tasks and make decisions by reasoning about problems and acting through external tools.
  • The smolagents framework lets you build local agents using small language models and Python-based tools.
  • CodeAgent writes and runs Python snippets for each step instead of generating JSON instructions.
  • Tool functions need docstrings and type hints so they’re automatically available as agent-usable capabilities.
  • ReAct agents integrate reasoning and acting by iteratively analyzing problems and using available tools to reach solutions.
  • Custom tools extend agent capabilities beyond default toolsets for domain-specific automation.
  • Agent planning involves breaking complex tasks into steps and selecting the right tools to execute them.
  • Multistep workflows let agents chain tool outputs together to complete complex tasks.