GNGiseldo Neo and Alana NeoBooks
Building Chatbots7 / 9

Large Language Models (LLMs)

“The intelligence of these systems is an illusion — what is seen is not understanding, but a statistical adjustment of patterns.”

Emily Bender

Objective

Discuss the architecture of Transformers, models such as BERT, GPT, and LLaMA, Fine-Tuning, and RAG, demonstrating how these techniques are applied in the construction of modern chatbots.

4.1 Introduction

A large language model (LLM) is a machine learning system that can generate text in response to an input sequence. The input text is the prompt, and the generated response is the output. Figure 4.1 illustrates this process.

LLM input and output flow.

Figure 4.1. LLM input and output flow.

An LLM is nothing more than a specific type of artificial neural network (a deep neural network) trained with textual data. In other words, a large neural network trained with a lot of data. The concept of “large neural network” relates to the number of parameters that make up the network, in the millions and beyond; as for “a lot of data,” it refers to tens of gigabytes and beyond, encompassing raw datasets that may include books, articles, web pages, technical documents, and other written materials.

The training process involves two stages (see Figure 4.2): (i) training with raw textual data and (ii) training with annotated textual data (i.e., more tailored) to the needs of an LLM (Raschka 2024).

Overview of the LLM training process.

Figure 4.2. Overview of the LLM training process.

When an LLM is trained with raw data, it is referred to as a “base” model and aims to predict the next sequence of words from the input prompt. For example, for the prompt: The “book is,” the response of a base model could be: “The book is on the table.” Following this, Example 1 presents an illustrative set of training textual data.

"For some time I hesitated over whether to open these memoirs at the beginning or at the end, that is, whether to put my birth or my death first. Although the usual practice is to begin with one's birth, two considerations led me to adopt a different method. The first is that I am not exactly a deceased author but a dead man turned author, for whom the grave was a second cradle. The second is that the writing would be more engaging and more novel this way. Moses, who also recounted his death, placed it at the end rather than at the beginning. That is the fundamental difference between this book and the Pentateuch."
Translated excerpt from Machado de Assis, Todos os Romances (Portuguese Edition), p. 226, Kindle edition.

In the second stage, the base model is retrained, but now with annotated text data (often by humans), which allows the model to learn not only general linguistic patterns but also explicit interaction instructions. See the training textual data example in Example 2.

user: "Who discovered Brazil?"
bot: "Good question. Pedro Álvares Cabral discovered Brazil. Would you like to learn more about Brazil?"
user: "Translate The book is on the table into Portuguese."
bot: "The translation is: O livro está na mesa. Is there anything else you would like to know?"

Examples 1 and 2 were constructed solely for didactic purposes, with the aim of illustrating, in a simplified manner, how textual excerpts can be used in the training of a language model. In real-world applications, however, the process is far more complex: it involves massive sets of textual data, often consisting of billions of words from diverse sources and organized with specific formatting. The execution of such large-scale training only became possible thanks to the Transformer architecture, which introduced the attention mechanism capable of handling long-range dependencies in text sequences efficiently and in parallel.

Large-scale language models are trained precisely to predict the next word in a sequence, a skill that serves as the foundation for constructing sophisticated linguistic representations. This process enables models to understand extensive contexts and perform complex natural language processing tasks, such as machine translation, document summarization, and question answering. The ability to capture long-range relationships in text is one of the distinguishing features of these models compared to previous architectures.

The introduction of Transformers, proposed by Vaswani et al. (2017) in the seminal paper “Attention is All You Need” (Vaswani et al. 2017), represented a fundamental shift in the field. The main innovation was the attention mechanism, which assigns different weights to input words according to their context, allowing the model to identify which terms are most relevant in each situation. This characteristic makes it possible to process long sequences in parallel, substantially accelerating training and increasing effectiveness in modeling distant dependencies.

Before this architecture, NLP models were dominated by RNNs (Recurrent Neural Networks) and LSTMs (Long Short-Term Memory Networks). While functional, these methods presented significant limitations: difficulty in capturing long-range dependencies due to the vanishing gradient problem and performance constraints, as they processed text in a strictly sequential manner, reducing the potential for parallelization. The Transformer overcame these limitations by considering all input words simultaneously, weighting their relative importance through attention.

With this, LLMs not only increased accuracy in traditional NLP tasks but also expanded the scope of applications, encompassing creative text generation, contextualized translation, and automatic grammar correction. On the other hand, the advancement of these models also raised questions related to ethics, bias, and responsible use of artificial intelligence, aspects that have been discussed intensively by the scientific community and will be addressed in Chapter 5.

4.2 General Architecture of the Transformer

Modern LLMs are largely based on the Transformer architecture, originally proposed by Vaswani et al. (2017). This architecture has become the foundation for numerous advances in natural language processing because it offers an efficient and scalable way to handle text sequences. Unlike previous approaches, which processed words one by one in order, Transformers allow the entire context to be considered in parallel, making training and inference faster and more flexible.

The general structure of a Transformer consists of repeating blocks, each combining attention mechanisms and fully connected (feedforward) networks. In its original formulation, the architecture has two major components: the encoder, responsible for transforming the input sequence into an internal representation, and the decoder, which uses this representation to generate output, as in the case of machine translation. Although some current models use only the encoder part (such as BERT) or only the decoder part (such as GPT), the fundamental principle remains the same: both rely heavily on the attention mechanism.

Each layer of the encoder and decoder contains three central elements:

  • Multi-Head Attention mechanism: evaluates, in parallel, different ways of relating words to each other.

  • Feedforward networks: transform intermediate representations, allowing for greater modeling capacity.

  • Normalization and residual connections: stabilize training and help preserve information across layers.

The concept of self-attention is one of the most innovative aspects. In this mechanism, each word in the sequence is not processed in isolation, but is compared with all other words in the same sequence. This allows the model to understand long-range dependency relationships, such as between the subject at the beginning of a sentence and the verb that appears much later. The multi-head attention expands on this idea by applying multiple attentions in parallel, each learning to capture a different type of relationship—some heads may identify syntactic proximity, while others capture more distant semantic connections.

A central aspect of the architecture is that all this processing occurs in parallel. Unlike recurrent networks (RNNs) or LSTMs, which analyzed the text word by word in sequence, the Transformer evaluates the entire sentence at once. This paradigm shift allowed models to be trained on massive collections of text, reaching billions of parameters and scaling to unprecedented sizes.

In addition to its structural efficiency, the Transformer is also flexible: it can be adapted to different tasks with minor modifications. Autoregressive models, such as the GPT family, are based only on the decoder and are trained to predict the next word in a sequence in a unidirectional manner. Meanwhile, bidirectional models, such as BERT, explore both left and right context, making them particularly effective for textual understanding tasks.

The impact of the Transformer architecture is broad and extends beyond its most basic form of natural language processing. The combination of parallelism, the ability to capture long-range dependencies, and structural flexibility has paved the way for the creation of entire families of models with different purposes. Some use only the encoder, others only the decoder, and there are even those that combine the two in distinct ways. This diversity has given rise to well-known architectures such as BERT, GPT, T5, and LLaMA, which have become references in the field and will be discussed in greater detail below.

4.2.1 BERT (Bidirectional Encoder Representations from Transformers)

BERT (Bidirectional Encoder Representations from Transformers) introduced a new form of large-scale training in which the model considers both the left context and the right context of a target word. This approach allowed for a richer understanding of language compared to previous models, which were predominantly unidirectional.

BERT is built on the stack of encoders from the Transformer. This means it is not designed to generate text autoregressively, but rather to produce deep contextual representations of words and phrases that can subsequently be used in various natural language processing tasks. This characteristic makes BERT especially suitable for textual understanding problems such as classification, question answering, and information extraction.

The model is pre-trained on a large amount of text using two main tasks:

  • Masked Language Modeling (MLM): Random words in a sequence are replaced by a special mask token, and the model is trained to predict the original words based on the remaining context. This procedure allows BERT to learn bidirectional relationships, as the prediction of a word depends on terms both before and after it in the sentence.

  • Next Sentence Prediction (NSP): The model receives pairs of sentences and must identify whether the second sentence logically follows the first. This task helps BERT capture discourse relationships between sentences, which is essential in applications such as question answering and textual inference.

After pre-training, BERT can be fine-tuned (Fine-Tuning) for specific tasks, often with datasets much smaller than those used for pre-training. This adaptation process is what allows a single model, previously trained in a generic manner, to be applied to a wide range of problems.

from transformers import BertTokenizer, BertForSequenceClassification
from torch.nn.functional import softmax

# Load the tokenizer and the BERT model
tokenizer = BertTokenizer.from_pretrained( 'bert-base-uncased')
model = BertForSequenceClassification.from_pretrained( 'bert-base-uncased')

# Example input
input_text = "Chatbots são muito úteis para automação."

# Tokenize the input
input_ids = tokenizer(input_text, return_tensors='pt')

# Make predictions
outputs = model(**input_ids)
probs = softmax(outputs.logits, dim=-1)

print("Class probabilities:", probs)
Class probabilities: tensor([[0.7097, 0.2903]], grad_fn=<SoftmaxBackward0>)

BERT quickly established new benchmarks in NLP benchmarks, such as GLUE (General Language Understanding Evaluation) and SQuAD (Stanford Question Answering Dataset). Its efficacy has driven the development of a series of variations and improvements, such as RoBERTa, DistilBERT, and ALBERT, which aim to improve performance, efficiency, or reduce training costs.

BERT is widely used in:

  • Text Classification: Sentiment analysis, spam detection, document categorization.

  • Question Answering: Models that identify relevant passages in a text to answer questions formulated in natural language.

  • Information Extraction: Identification of named entities (people, places, organizations) and relationships between them.

Despite its impact, BERT presents relevant limitations. The model is computationally heavy, requiring significant processing capacity for training and even for inference in practical applications. Furthermore, its context window is limited, which makes processing very long documents difficult without additional segmentation strategies.

from transformers import BertTokenizer, BertModel

# Load the tokenizer and the pretrained BERT model
tokenizer = BertTokenizer.from_pretrained( 'bert-base-uncased')
model = BertModel.from_pretrained( 'bert-base-uncased')

# Example text
texto = "Machine learning is fascinating."

# Tokenize the input
input_ids = tokenizer(texto, return_tensors='pt')['input_ids']

# Get representations from the BERT model
outputs = model(input_ids)
last_hidden_states = outputs.last_hidden_state

print("BERT representations:", last_hidden_states)
BERT representations: tensor([[[ 0.0836,  0.0931, -0.2452,  ..., -0.3743,  0.0502,  0.5606],
[ 0.2351,  0.0642, -0.1859,  ..., -0.1147,  0.5381,  0.5704],
...,
[ 0.8129,  0.1013, -0.2131,  ...,  0.0133, -0.6965, -0.0085]]],
grad_fn=<NativeLayerNormBackward0>)

4.2.2 GPT (Generative Pre-trained Transformer)

The Generative Pre-trained Transformer (GPT) is one of the most well-known LLMs. It is trained in an autoregressive manner, meaning it predicts the next word in a sequence given the previous input. This makes it excellent for text generation tasks. GPT-2 was an initial version of GPT, containing 1.5 billion parameters. It demonstrated that, when trained on large quantities of text, it could generate coherent and complex content. GPT-3 is an even greater evolution, with 175 billion parameters. This model can perform a wide range of NLP tasks without the need for specific fine-tuning, simply by receiving examples of how the task should be executed (few-shot learning).

from transformers import GPT2Tokenizer, GPT2LMHeadModel

# Load the tokenizer and the GPT-2 model
tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
model = GPT2LMHeadModel.from_pretrained('gpt2')

# Example input
input_text = "Chatbots modernos podem"

# Tokenize the input
input_ids = tokenizer.encode(input_text, return_tensors='pt')

# Generate text
outputs = model.generate(input_ids, max_length=50, num_return_sequences=1)

# Decode and display the generated text
generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
print("Generated text:", generated_text)
Generated text: Chatbots modernos podemodel.com The following is a list of all the bots that have been added to the podemodel.com community. Bot Name Description bot_bot_name_id bot_

GPT has been applied in various areas, including:

  • Text Generation: Creation of content, stories, articles, etc.

  • Virtual Assistants: Implementation of AI-based dialogue systems.

  • Automatic Translation: Use of broad context to improve translation between languages.

GPT is an autoregressive model focused on text generation. It is trained to predict the next word in a sequence, making it excellent for text generation tasks such as chatbots.

from transformers import GPT2Tokenizer, GPT2LMHeadModel

# Load the tokenizer and the pretrained GPT-2 model
tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
model = GPT2LMHeadModel.from_pretrained('gpt2')

# Example text
input_text = "In the future, artificial intelligence will"

# Tokenize the input
input_ids = tokenizer.encode(input_text, return_tensors='pt')

# Generate text
outputs = model.generate(input_ids, max_length=50, num_return_sequences=1)

# Decode and display the generated text
generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
print("Generated text:", generated_text)
Generated text: In the future, artificial intelligence will be able to do things like search for information about people, and to do things like search for information about people. We're going to see a lot of things that are going to be very interesting in

In addition to BERT and GPT, there are many other Transformer-based models designed for specific tasks. Some examples include T5 (Text-To-Text Transfer Transformer), which converts any NLP task into a translation problem; XLNet, which combines ideas from BERT and autoregressive Transformers to improve long-range dependency modeling; RoBERTa (A Robustly Optimized BERT Pretraining Approach), which is a BERT variation with enhanced training, as well as DistilBERT.

T5 transforms any NLP task into a translation problem, where input and output are treated as text. This simplifies Fine-Tuning for different tasks.

# pip install transformers[torch]
# pip install sentencepiece

from transformers import T5Tokenizer, T5ForConditionalGeneration

# Load the tokenizer and the T5 model
tokenizer = T5Tokenizer.from_pretrained( 't5-small')
model = T5ForConditionalGeneration.from_pretrained( 't5-small')

# Example input
input_text = "translate English to German: The weather is nice today."

# Tokenize the input
input_ids = tokenizer.encode(input_text, return_tensors='pt')

# Generate text
outputs = model.generate(input_ids)

# Decode and display the generated text
generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
print("Generated translation:", generated_text)
Generated translation: Das Wetter ist heute schon.

It is also worth highlighting XLNet and DistilBERT. XLNet combines the advantages of autoregressive and bidirectional models, such as GPT and BERT, to capture long-range dependencies more efficiently. DistilBERT is a reduced version of BERT with fewer parameters but maintains high performance, making it more efficient for production use.

from transformers import XLNetTokenizer, XLNetLMHeadModel

# Load the tokenizer and the XLNet model
tokenizer = XLNetTokenizer.from_pretrained( 'xlnet-base-cased')
model = XLNetLMHeadModel.from_pretrained( 'xlnet-base-cased')

# Example input
input_text = "Natural Language Processing is"

# Tokenize the input
input_ids = tokenizer.encode(input_text, return_tensors='pt')

# Generate text
outputs = model.generate(input_ids, max_length=50, num_return_sequences=1)

# Decode and display the generated text
generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
print("Text generated with XLNet:", generated_text)
Text generated with XLNet: Natural Language Processing is and in and in [...]

4.2.3 distilbert-base-uncased

The distilbert-base-uncased model (Akhila et al. 2023) was released in 2019, being smaller and faster than BERT and optimized for tasks that process phrases or sentences. Its uncased version is useful for code descriptions and problems, as it does not consider case differences. It is pre-trained on a large corpus, which aids in generalization, and has a good architecture for this type of task, in addition to requiring accessible hardware.

The distilbert results from a knowledge distillation process that reduces the number of parameters by approximately 40% and accelerates inference by about 60%, preserving 95–97% of the BERT-base (original) accuracy on natural language understanding benchmarks (Sanh et al. 2019). This compactness of providing rich representations with lower computational cost is particularly advantageous in moderate hardware environments. With only 67M parameters (Sanh et al. 2019), the uncased variant fits into a modest GPU (for example, 6 GB of video card RAM), enabling fine-tuning and inference within restricted computational resources. Thus, it becomes feasible to re-train the model as new project data accumulates, maintaining accuracy without investing in expensive infrastructure.

Finally, the broad support in the Hugging Face ecosystem for BERT-type models and other models simplifies reproducibility and integration into natural language processing task pipelines.

4.3 Fine-Tuning of Pre-trained Models

Pre-trained models such as BERT and GPT have demonstrated the ability to comprehend semantic nuances in text and transfer this knowledge to various specific tasks through Fine-Tuning. (Minaee et al. 2025).

The Fine-Tuning of pre-trained models is a fundamental technique in modern Natural Language Processing (NLP), especially when working with Large Language Models (LLMs). Fine-Tuning allows adapting a general model to specific tasks, such as text classification, sentiment analysis, or language generation, using a smaller and specific dataset.

Fine-Tuning is the process of taking a pre-trained model on a large amount of general data and adapting it to a specific task. This process involves adjusting the model’s weights, but with a lower learning rate to not “forget” what was learned during pre-training. Models such as BERT (Devlin et al. 2019), GPT (Radford et al. 2019), and T5 (Raffel et al. 2020) are commonly fine-tuned for specific tasks.

An efficient alternative to full Fine-Tuning is the use of low-parameter adaptation methods, such as LoRA (Low-Rank Adaptation). Instead of updating all weights of the pre-trained model, LoRA introduces additional small low-dimensional matrices that are adjusted during training, while the original weights remain frozen. This technique drastically reduces the number of parameters that need to be trained, reducing computational and storage costs. In practice, this makes it feasible to apply Fine-Tuning on very large LLMs, even in environments with limited resources, preserving a good portion of the performance obtained from full fine-tuning.

The main advantage of Fine-Tuning is efficiency, as it allows models to quickly learn a new task using relatively few data points. Furthermore, pre-trained models already capture general linguistic patterns, making Fine-Tuning a useful approach for solving specific problems without the need to train a model from scratch. The Fine-Tuning process generally involves the following steps:

  • Model Selection: Select an appropriate pre-trained model for the task. Models such as BERT and GPT are popular due to their versatility.

  • Data Preparation: The data must be formatted to be compatible with the specific task, such as text classification or question answering.

  • Training Configuration: Adjust hyperparameters such as learning rate, number of epochs, and batch size.

  • Training: Execute the model training on the specific dataset.

  • Evaluation: Evaluate the performance of the fine-tuned model on a validation or test set.

Let us perform the Fine-Tuning of a BERT model for a sentiment classification task using the IMDb dataset.

It is worth noting that the transformers library from Hugging Face, used in this example, has become the reference tool for working with Transformers-based models. It offers a wide range of pre-trained models that can be easily integrated into NLP pipelines.

The following code may take between 30 minutes and 2 hours to complete on a computer with a good GPU. On CPU, it may take several hours or even more than a day. A suggestion is to use Google Colab.

# pip install datasets
# pip install transformers[torch]

from transformers import BertTokenizer, BertForSequenceClassification, Trainer, TrainingArguments
from datasets import load_dataset

import os
os.environ["WANDB_DISABLED"] = "true"

# Load the IMDb dataset
dataset = load_dataset("imdb")

# Load the tokenizer and the BERT model
tokenizer = BertTokenizer.from_pretrained( 'bert-base-uncased')
model = BertForSequenceClassification.from_pretrained( 'bert-base-uncased')

# Tokenize the dataset
def tokenize_function(examples):
return tokenizer(examples['text'], padding='max_length', truncation=True)

tokenized_datasets = dataset.map(tokenize_function, batched=True)

# Define the training arguments
training_args = TrainingArguments(
    output_dir='./results',
    learning_rate=2e-5,
    report_to="none",
    per_device_train_batch_size=16,
    per_device_eval_batch_size=16,
    num_train_epochs=3,
    weight_decay=0.01,
)

# Create the Trainer
trainer = Trainer(
model=model,
args=training_args,
train_dataset=tokenized_datasets['train'],
eval_dataset=tokenized_datasets['test'],
)

# Train the model
trainer.train()

# Evaluate the model
eval_result = trainer.evaluate()
print(f"Evaluation results: {eval_result}")
Evaluation results: {'eval_loss': 0.2594565749168396, 'eval_runtime': 172.544, 'eval_samples_per_second': 144.891, 'eval_steps_per_second': 9.059, 'epoch': 3.0}

In this example, we use the BERT model and the datasets library from Hugging Face to load the IMDb dataset, which is used for sentiment classification tasks. The tokenization process is performed using the BertTokenizer, followed by training the model using the Trainer, which automates the Fine-Tuning process.

Although Fine-Tuning is a technique with potential, it is important to consider some challenges:

  • Overfitting: Adjusting the model too much for specific training data can reduce generalization to new data.

  • Inherent Biases: If the pre-trained model already contains biases, Fine-Tuning can reinforce them, especially if the training data is limited or biased.

  • Computational Requirements: Fine-Tuning of LLMs can be computationally intensive, especially for larger models like GPT-3.

Additionally, some advanced approaches to improve the Fine-Tuning process include:

  • Learning Rate Warmup: Gradually increasing the learning rate at the beginning of training to avoid large weight updates that could destabilize the model.

  • Layer-Wise Learning Rate Decay: Applying different learning rates for different layers of the model, with lower layers learning more slowly.

  • Data Augmentation: Increasing the diversity of the training dataset to improve model robustness.

Fine-Tuning has a vast range of applications in NLP, including:

  • Text Classification: Sentiment analysis, spam detection, news categorization.

  • Question Answering: Models that answer questions based on a specific textual context.

  • Text Generation: Fine-Tuning of models like GPT to generate specific texts for a domain, such as writing scientific articles.

  • Automatic Translation: Adapting translation models for dialects or specific languages.

4.4 Few-Shot and Zero-Shot Learning

Zero Shot: The LLM zero-shot learning approach refers to the ability of LLMs to solve tasks without the need for explicit examples provided during inference. In this context, the natural language processing text classification task is specified solely through a textual instruction (prompt), and the model must infer the expected action based on its prior knowledge acquired during pre-training (Radford et al. 2019).

Few Shot: In contrast, few-shot learning is characterized by the inclusion of a small set of task examples directly in the prompt, with the aim of guiding model generation during inference. This technique allows the model to identify desired patterns based on the provided examples and apply them to new cases, even without reconfiguration or parameter adjustment. It is an intermediate approach between zero-shot and traditional supervised training, being especially effective in classification tasks with contextual variations (Raschka 2024). Its main advantage lies in the rapid adaptation to new tasks with reduced computational cost.

4.5 Retrieval-Augmented Generation (RAG)

Retrieval-Augmented Generation (RAG) is an approach that combines two techniques in the field of natural language processing: information retrieval and text generation. The central idea of RAG is to enhance the capabilities of a language model by integrating it with a retrieval system that searches for relevant information in a database or a set of documents.

In practice, RAG operates in two stages. First, when a query or question is made, a retrieval mechanism is triggered to identify and extract pertinent information from a data repository. This can include documents, articles, or any other type of textual content that can provide additional context and details about the topic in question. This phase ensures that the language model has access to up-to-date and specific information, rather than relying solely on the prior knowledge that was incorporated during its training.

Next, in the second stage, the language model uses the retrieved information to generate a richer and more contextualized response. This generation does not merely reproduce the retrieved content, but rather integrates these data points cohesively, creating a response that not only answers the question but also provides a more complete and informative narrative. This results in responses that are more accurate and relevant, as they are grounded in concrete and up-to-date data.

The combination of these two stages allows RAG to overcome some limitations of traditional language models, which may fail to provide accurate or up-to-date information, especially in domains that evolve rapidly. Furthermore, this approach is particularly useful in applications such as virtual assistants, chatbots, and question-and-answer systems, where the accuracy and relevance of information are key factors in the user experience.

Therefore, it is a technique that not only improves the quality of responses generated by language models but also expands the reach and applicability of these models in real-world scenarios where information is dynamic and constantly evolving.

RAG unites two main components: Information Retrieval (Retival), which involves searching for relevant documents, paragraphs, or passages from a large collection of data; and Text Generation (Generation), where, once the relevant information is retrieved, a language model, such as GPT or BART, is used to generate a coherent and informative response based on the retrieved information. In this way, RAG is capable of answering questions and generating content that not only uses the immediate context but also consults an external knowledge base, thereby increasing the accuracy and relevance of the responses.

Let’s implement a simple example of RAG using the Hugging Face libraries, including the DPR model for retrieval and the BART model for text generation.

Passage Retrieval with DPR: First, we need to load and configure the DPR model to retrieve relevant passages from a database. We suggest executing the code below in Google Colab.

from transformers import DPRQuestionEncoder, DPRQuestionEncoderTokenizer
from transformers import DPRContextEncoder, DPRContextEncoderTokenizer
from transformers import BertTokenizer, BertModel
import torch

# Load the tokenizer and model for queries (questions)
question_tokenizer = DPRQuestionEncoderTokenizer.from_pretrained(
"facebook/dpr-question_encoder-single-nq-base")
question_encoder = DPRQuestionEncoder.from_pretrained(
"facebook/dpr-question_encoder-single-nq-base")

# Load the tokenizer and model for contexts (passages)
context_tokenizer = DPRContextEncoderTokenizer.from_pretrained( "facebook/dpr-ctx_encoder-single-nq-base")
context_encoder = DPRContextEncoder.from_pretrained( "facebook/dpr-ctx_encoder-single-nq-base")

# Example query
query = "What is Retrieval-Augmented Generation?"

# Encode the query
query_input = question_tokenizer(query, return_tensors="pt")
query_embedding = question_encoder(**query_input).pooler_output

# Example passages
passages = [
    "Retrieval-Augmented Generation is a technique that combines retrieval of relevant information with text generation.",
    "It allows for more accurate and contextually relevant answers by consulting external knowledge bases.",
    "RAG is particularly useful in scenarios where the information required to answer a query is not present in the training data of the language model."
]

# Encode the passages
passage_inputs = context_tokenizer(passages, padding=True, truncation=True, return_tensors="pt")
passage_embeddings = context_encoder(
    **passage_inputs).pooler_output

# Compute similarity and select the most relevant passage
similarity_scores = torch.matmul(query_embedding, passage_embeddings.T)
best_passage_index = torch.argmax(similarity_scores, dim=1).item()
best_passage = passages[best_passage_index]

print("Most relevant passage:", best_passage)
Most relevant passage: Retrieval-Augmented Generation is a technique that combines retrieval of relevant information with text generation

In this example, we use the DPR model to encode a query and several passages, and then calculate the similarity between the query and the passages to retrieve the most relevant one.

Text Generation with BART: Once the most relevant passage has been retrieved, we use the BART model to generate a coherent response.

# pip install transformers[torch]
from transformers import DPRQuestionEncoder, DPRQuestionEncoderTokenizer
from transformers import DPRContextEncoder, DPRContextEncoderTokenizer
from transformers import BartTokenizer, BartForConditionalGeneration
from transformers import BertTokenizer, BertModel
import torch

# Load the tokenizer and model for queries (questions)
question_tokenizer = DPRQuestionEncoderTokenizer.from_pretrained(
"facebook/dpr-question_encoder-single-nq-base")
question_encoder = DPRQuestionEncoder.from_pretrained(
"facebook/dpr-question_encoder-single-nq-base")

# Load the tokenizer and model for contexts (passages)
context_tokenizer = DPRContextEncoderTokenizer.from_pretrained( "facebook/dpr-ctx_encoder-single-nq-base")
context_encoder = DPRContextEncoder.from_pretrained( "facebook/dpr-ctx_encoder-single-nq-base")

# Example query
query = "What is Retrieval-Augmented Generation?"

# Encode the query
query_input = question_tokenizer(query, return_tensors="pt")
query_embedding = question_encoder(**query_input).pooler_output

# Example passages
passages = [
    "Retrieval-Augmented Generation is a technique that combines retrieval of relevant information with text generation.",
    "It allows for more accurate and contextually relevant answers by consulting external knowledge bases.",
    "RAG is particularly useful in scenarios where the information required to answer a query is not present in the training data of the language model."
]

# Encode the passages
passage_inputs = context_tokenizer(passages, padding=True, truncation=True, return_tensors="pt")
passage_embeddings = context_encoder
   **passage_inputs).pooler_output

# Compute similarity and select the most relevant passage
similarity_scores = torch.matmul(query_embedding, passage_embeddings.T)
best_passage_index = torch.argmax(similarity_scores, dim=1).item()
best_passage = passages[best_passage_index]

# Load the tokenizer and the BART model
bart_tokenizer = BartTokenizer.from_pretrained(
"facebook/bart-large")
bart_model = BartForConditionalGeneration.from_pretrained(
"facebook/bart-large")

# Concatenate the query and the relevant passage
input_text = query + " " + best_passage

# Encode the input and generate a response
input_ids = bart_tokenizer.encode(input_text, return_tensors="pt")
generated_ids = bart_model.generate(input_ids, max_length=50, num_beams=4, early_stopping=True)
generated_text = bart_tokenizer.decode(generated_ids[0], skip_special_tokens=True)

print("Generated response:", generated_text)
Generated response: What is Retrieval-Augmented Generation?Retrieval and Augmented Generation is a technique that combines retrieval of relevant information with text generation.What is retrieval?

This code generates a response based on the retrieved passage, creating an informative response that combines relevant information with fluid text generation.

The RAG technique has several practical applications, including:

  • Question Answering Systems: Systems that need to query extensive knowledge bases to answer questions accurately.

  • Virtual Assistants: Assistants that require access to specific and detailed information, in addition to initial model training.

  • Content Generation: Creation of specialized content that requires external source consultation to ensure accuracy and relevance.

The RAG technique also presents several challenges:

  • Scalability: Information retrieval in very large databases can be computationally intensive.

  • Passage Relevance: The quality of generated responses depends heavily on the relevance of the retrieved passages.

  • Joint Training: Training the retrieval and generation components jointly can be complex and requires large volumes of data.

4.6 LLaMA

LLaMA is a family of large language models (LLMs) that are smaller in size but still retain the capability to perform complex natural language processing tasks. The LLaMA approach is based on a Transformer architecture, similar to other LLMs, but optimized for efficiency in terms of parameters and computational resources.

Key Features

  • Reduced Size: LLaMA is designed to be lighter than giant models, with variants ranging from 7B to 65B parameters.

  • Computational Efficiency: Due to its optimized design, LLaMA can be trained in less time and with fewer resources, making it accessible for smaller organizations and researchers.

  • Versatility: Despite its reduced size, LLaMA is capable of performing a wide range of natural language processing tasks, including text generation, translation, and language understanding.

4.6.1 LLaMA Architecture

The LLaMA architecture is based on the Transformer but includes several optimizations that allow it to maintain high prediction quality while using fewer parameters and computational resources.

Optimized Transformer Layers

LLaMA uses Transformer layers with specific improvements to optimize memory usage and processing time. The main differences include:

  • Optimized Multi-Head Attention: Reduces redundancy when calculating attention across multiple heads.

  • Optimized Feedforward: Utilizes compression techniques to reduce the number of required operations.

  • Compact Parameters: Reduces the number of parameters while maintaining the ability to capture complex linguistic relationships.

Training and Scalability

LLaMA was trained on large textual data corpora, including multiple languages and domains. The architecture allows the model to be scaled efficiently, with smaller versions (7B parameters) suitable for less intensive tasks and larger versions (65B parameters) competing with state-of-the-art models like GPT-3.

4.6.2 Example Usage of LLaMA

Although LLaMA is relatively new, it is possible to work with model variants or similar implementations using Hugging Face tools.

We will use a LLaMA version to perform a simple text generation task. We will assume that the LLaMA variant has been integrated into the Hugging Face Transformers library.

To execute the code below, we recommend using Google Colab. You will need to provide your Hugging Face token and request access to the LLaMa model directly on Hugging Face.

from transformers import AutoTokenizer, AutoModelForCausalLM
from huggingface_hub import login
from google.colab import userdata

from google.colab import userdata
userdata.get('HF_TOKEN')

# Log in to Hugging Face
login(token=userdata.get('HF_TOKEN'))

# Load the tokenizer and the LLaMA model
tokenizer = AutoTokenizer.from_pretrained(
"meta-llama/Meta-Llama-3-8B")
model = AutoModelForCausalLM.from_pretrained(
"meta-llama/Meta-Llama-3-8B")

# Input text
input_text = "Artificial intelligence is transforming the world of"

# Tokenize the input and generate text
input_ids = tokenizer.encode(input_text, return_tensors="pt")
generated_ids = model.generate(input_ids, max_length=50, num_beams=5, early_stopping=True)
generated_text = tokenizer.decode(generated_ids[0], skip_special_tokens=True)

print("Generated text:", generated_text)
Generated text: Artificial intelligence is transforming the world of business. It has the potential to revolutionize the way we work, communicate, and interact with each other. AI is already being used in a variety of industries, from healthcare to finance, and it is

In this example, we load the tokenizer and the LLaMA model and generate text based on an input prompt. The code can be adjusted for different model sizes and different text generation tasks.

4.6.3 LLaMA Applications

Due to its efficiency and versatility, LLaMA can be applied in a variety of scenarios, including:

  • Virtual Assistants: Implementation of assistants that can be executed on devices with limited resources.

  • Content Generation: Production of articles, stories, and other high-quality textual content.

  • Automatic Translation: Smaller LLaMA models can be used for real-time translation on mobile devices.

  • Sentiment Analysis: Applications that require efficient processing of large volumes of textual data.

4.6.4 Comparison with Other Models

When compared to larger models like GPT-3, LLaMA offers an excellent balance between performance and efficiency. It is particularly useful in scenarios where computational resources are limited or where large-scale deployment is a key consideration.

Some Advantages of LLaMA:

  • Cost Reduction: Lower demand for computational resources, resulting in reduced costs for training and deployment.

  • Scalability: Can be easily adapted for different tasks and environments.

  • Speed: Lower latency in inference due to the smaller model size.

Some Limitations of LLaMA:

  • Limited Capacity: While efficient, smaller models may not capture all the linguistic nuances that larger models can.

  • Less Variety of Tasks: May be less suitable for extremely complex tasks that require models with billions of parameters.

4.7 LLM in Practice

4.7.1 Hugging Face Pipeline

The Transformer library from Hugging Face makes it much easier to work with pre-trained models like GPT-2. Here is an example of how to generate text using the pre-trained GPT-2:

from transformers import pipeline
pipe = pipeline('text-generation', model='gpt2')
input = 'Olá, como vai você?'
output = pipe(input)
print(output)
[{'generated_text': 'The book is on one of the most exciting,'},
{'generated_text': 'The book is on sale via Amazon.com for'},
{'generated_text': 'The book is on sale tomorrow for $2.'},
{'generated_text': 'The book is on sale now, read more at'},
{'generated_text': 'The book is on the bookshelf in the'}]

This code is simple because it uses a model that has already been trained on a large dataset. It is also possible to fine-tune a pre-trained model on your own data to achieve better results.

4.7.2 Local LLM with Ollama

In this section, we will describe the details of installing the Ollama software, download the LLM Qwen2 0.5B model, and explore its capabilities with a few simple questions.

Ollama is a command-line platform that facilitates the use of AI models locally; there are others, but the general idea is quite similar. With it, you can download pre-trained models, generate text, and perform inferences without needing a powerful graphics card. Its simplicity and speed make it perfect for those who want to experiment with LLMs on modest computers.

Downloading and Installing Ollama: Access the official Ollama website and download the installer for your operating system. The procedures described in this section are based on Windows, but Ollama also works on macOS and Linux.

Go to the Ollama website and click the download button for Windows. Then, save the installer (a small file with a few megabytes) to your Downloads folder. Next, run the installer and follow the instructions to complete the installation. Once installed, Ollama is ready to be used from the terminal. See Figure 4.3 for the Ollama website download page.

Ollama website for download.

Figure 4.3. Ollama website for download.

Getting to Know Ollama Commands: With Ollama installed, open the terminal (Command Prompt on Windows) and type “ollama” to confirm that the installation was successful. You will see a list of available commands. See Figure 4.4 for the result of the list command output in the command prompt.

Command to list already installed LLM models.

Figure 4.4. Command to list already installed LLM models.

Let’s detail the Ollama run and show commands. The “ollama run <model-name>” command downloads and runs a specific model. The “ollama show <model-name>” command displays details about a model, such as context window and parameters. Since we haven’t downloaded any models yet, the “ollama list” command will show an empty list. Let’s fix this by downloading a model!

Choosing and Downloading a Model: On the Ollama website, in the “Models” section, you will find several available models. See Figure 4.5 for a screenshot of the browser showing the Ollama website with the result of searching for an LLM model.

Ollama website, search by model name.

Figure 4.5. Ollama website, search by model name.

Let’s use a very lightweight model called “Qwen2 0.5B”, from Alibaba, which has 0.5 billion parameters and is only 350 MB in size. It is ideal for simpler machines, such as a computer with a Pentium Gold processor without a GPU. See Figure 4.6 for a screenshot of the browser showing the Ollama website with the result of detailing the Qwen2.5 model.

Screen displaying details of the LLM Qwen2.5 model.

Figure 4.6. Screen displaying details of the LLM Qwen2.5 model.

To download and run the model, access the models page on the Ollama website. Locate the Qwen2 model and note the command for the 0.5B version: “ollama run qwen2:0.5b”. In the terminal, type:

$ ollama run qwen2.5:0.5b

This command will download the model and open an interactive text interface for you to start conversing with it. See Figure 4.7 for a screenshot of the browser showing the result of the “run” command prompt.

Command prompt demonstrating Ollama execution.

Figure 4.7. Command prompt demonstrating Ollama execution.

Interacting with the model: With the model downloaded, Ollama starts a terminal interface for text-based conversations. Let’s test it with some questions.

Example 1: Asking in Portuguese

Type the following question “What is machine learning?” into the console (or command prompt) of the installed Ollama with an LLM model loaded. See Figure 4.8 for a screenshot of the command prompt with the response from the loaded Qwen LLM answering the prompt: what is machine learning.

O que é aprendizagem de máquina?

Command prompt displaying the LLM output in Portuguese.

Figure 4.8. Command prompt displaying the LLM output in Portuguese.

As a small model, Qwen2 0.5B may "hallucinate" a bit or provide somewhat vague answers, especially in Portuguese. Its emergent dialogue capabilities are limited compared to larger models, but they are still impressive for its size.

Example 2: Asking in English

Now, let’s try the same question in English: “What is machine learning?”. Asking in English, the answer tends to be more precise. Figure 4.9 shows the result of the LLM’s response (output) in English.

What is machine learning?

Command prompt displaying the LLM output in English.

Figure 4.9. Command prompt displaying the LLM output in English.

The model performs better in English, likely because it was trained with more data in that language. This illustrates how the performance of language models can vary depending on the language and training data.

Example 3: A Simple Question and Answer

Let’s simplify by asking something simple, where the model would be comfortable answering: “What is Ollama?” See Figure 4.10 for the output of this question.

O que é Ollama?

Command prompt displaying the LLM output in Portuguese.

Figure 4.10. Command prompt displaying the LLM output in Portuguese.

The model confused "Ollama" as I referred to it with something else, highlighting the limitations of smaller models. When asked in English ("What’s Ollama in language models?"), it also failed, suggesting it is a type of Latin music.

The Ollama interface has some useful commands for managing the session. Among them “/clear”: Clears the current session to start from scratch; “/help”: Displays the available commands; “/bye”: Exits the model’s interactive mode. For example, after a few questions, you can type /clear to reset the context or /bye to end the model.

Checking LLM Model Details: To learn more about the model you are using, execute the command “ollama show <model name>”.

$ ollama show qwen2.5:0.5b

This command displays information, such as the context window: 32k tokens (the amount of text the model can consider at once); the quantization: Q4 (a method to reduce the model size and optimize performance). The context window is especially important, as it accumulates both what you type and the model’s responses, up to the limit of 32,000 tokens. A considerable limit for a small model.

Ollama runs on simple computers, making AI accessible to everyone; with it, local execution is possible since it does not depend on cloud services, ensuring privacy and control. Its configuration is fast, and its command-line interface is ideal for developers who prefer a minimalist, text-based workflow; finally, although there are more visual platforms for running LLMs, the speed and low resource consumption of Ollama make it an excellent choice for quick experiments.

4.7.3 Tokenizer in LLM

The tokenizer is responsible for dividing text into smaller parts (tokens) that the model can understand. After that, we need a model. The model is the part that actually does the work of understanding and generating text. We will use an existing tokenizer from Hugging Face.

# pip install transformers[torch]
from transformers import GPT2Tokenizer
tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
input= "Olá, como vai você?"
token_id = tokenizer(input)
print(token_id)
{'input_ids': [30098, 6557, 11, 401, 78, 410, 1872, 12776, 25792, 30], 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}

The output of this code will be a dictionary containing the token ids and the attention mask. The token id is the number that represents each word or part of the word in the model’s vocabulary. The attention mask indicates which tokens should be considered by the model during processing.

An attention mask is a list of 1s and 0s that indicates which tokens should be considered by the model during processing. A value of 1 means that the corresponding token should be considered, while a value of 0 means that it should be ignored.

4.7.4 LangChain

LangChain is an open-source software library designed to simplify interaction with Large Language Models (LLMs) and build robust natural language processing applications. It provides a high-level abstraction layer over the complexities of working directly with language models, making the creation of language understanding and generation applications more accessible.

Working with LLMs can be complex due to their sophisticated nature and computational resource requirements. LangChain handles many complex details in the background, allowing developers to focus on building effective language applications. Here are some advantages of using LangChain:

  • Simplicity: LangChain offers a simple and intuitive API, hiding the complex details of interacting with LLMs. It abstracts the nuances of loading models, managing computational resources, and executing predictions.

  • Flexibility: The library supports various deep learning frameworks, such as TensorFlow and PyTorch, and can be integrated with different LLMs. This offers developers the flexibility to choose the tools and models that best meet their needs.

  • Extensibility: LangChain is designed to be extensible, allowing users to create their own custom components. You can add new models, adapt text processing, or develop domain-specific features to meet the exclusive requirements of your application.

  • Community and support: LangChain has an active community of developers and researchers contributing to the project. The comprehensive documentation, tutorials, and community support make it easier to get started and navigate any challenges that arise during development.

The LangChain architecture can be understood through three main components:

Abstraction Layer: This layer provides a simple and unified interface for interacting with different LLMs. It abstracts the complexities of loading, initializing, and executing predictions in models, offering a consistent API regardless of the underlying model.

Text Processing Layer: LangChain includes robust tools for text processing, including tokenization, syntactic analysis, named entity recognition (NER), and more. This layer prepares input and output data so they can be effectively processed by language models.

Model Layer: This is where the LLMs themselves reside. LangChain supports a variety of language models, from general-purpose pre-trained models to domain-specific custom models. This layer handles prediction execution, computational resource management, and interaction with model APIs.

Let’s look at a simple example of how to use LangChain to query an LLM and get a response. In this example, we will use the gpt-4o-mini model from OpenAI to answer a question.

First, import the necessary libraries and configure the LangChain client. Next, load the desired language model. Now, you can use the model to make a query. Let’s ask who the president of Brazil is.

# pip install langchain

from langchain.chat_models import init_chat_model
from langchain_core.messages import HumanMessage
import os

OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")

model = init_chat_model("gpt-4o-mini",
    model_provider="openai",                        openai_api_key=OPENAI_API_KEY)

user_message = HumanMessage(content="Quem é o presidente do Brasil?")

response = model.invoke([user_message])

print(response.content)
Até a minha última atualização em outubro de 2023, o presidente do Brasil é Luiz Inácio Lula da Silva. Ele assumiu o cargo em janeiro de 2023. Para informações mais atualizadas, recomendo verificar fontes de notícias recentes.

This basic example demonstrates the simplicity of using LangChain to interact with LLMs. However, LangChain offers many more features and capabilities to build more robust chatbot applications.

4.7.5 Mangaba.AI

Mangaba.AI is a Python framework for creating autonomous AI agents that collaborate in teams to solve complex tasks. It allows you to assemble teams of agents with specialized functions—for example, a researcher agent, an analyst agent, a writer agent—that share contextual memory (i.e., interaction history and results) to continue work intelligently. Additionally, Mangaba integrates advanced models (including Google’s Gemini models), allows the use of external tools via APIs, and operates asynchronously to execute multiple tasks in parallel, which improves efficiency and speed. It can be accessed at mangaba-ai.vercel.app.

Among its practical uses, Mangaba.AI can be applied for automating repetitive processes, generating reports based on complex data, analyzing and extracting information from large volumes of documents, building virtual assistants, and supporting research and development. It aims to make developers’ lives easier by providing a simple and intuitive API for defining agents, assigning roles, configuring teams, and delegating entire tasks to this collaborative AI team.

# For installation instructions, see https://github.com/Mangaba-ai/mangaba_ai
from mangaba import Team, Agent

# Create an agent team
monitor = Team("Autorregulação")

# Add specialized agents
planejador = Agent("Plano de Estudo", role="Gera Plano de Estudo com cronograma baseado no tempo disponível do estudante")
apoio = Agent("Suporte Emocional", role="Motiva o estudante")
pesquisador = Agent("Guia de Estudo", role="Busca materiais didáticos para o estudante")

# Add agents to the team
monitor.add_agents([pesquisador, apoio, planejador])

# Define a complex task
result = monitor.solve(
  "Pesquise sobre Redes Neurais Artificiais"
)

print(result.output)

4.7.6 LLM Workflows (or Prompt Engineering)

Large Language Models (LLMs), such as the GPT family, are used for text comprehension and generation. An effective and relatively quick way to create a functional chatbot is through prompt engineering. Instead of manually coding complex rules and decision trees, you "program" the LLM by providing it with a detailed set of initial instructions (the prompt).

The prompt is the initial text you provide to the LLM. It defines:

  1. The Chatbot’s Role: Who it is (a pizza waiter, a fashion consultant, etc.).

  2. The Conversation’s Objective: What it needs to achieve (sell a pizza, help choose an outfit, open an account, etc.).

  3. The Conversation Rules: The exact sequence of questions to ask, the valid options for each question, and how to handle different user responses (conditional logic).

  4. The Tone and Style: Whether the chatbot should be formal, informal, friendly, etc. (though not specified in the examples, it can be added).

  5. The Final Output Format: How the collected information should be presented at the end.

How It Works

  1. Definition: You write a detailed prompt that describes the conversation flow step by step.

  2. Instruction: You feed this prompt into the LLM.

  3. Execution: The LLM uses the prompt as its master guide. It starts the conversation with the user by following the first step defined in the prompt, asks questions in the specified order, validates responses (if instructed), follows conditional paths, and finally generates the desired output.

  4. Iteration: If the chatbot does not behave exactly as expected, you adjust and refine the prompt until it follows the rules perfectly.

Some Advantages of Using Workflows in Chatbots:

  • Speed: Much faster than developing a traditional chatbot from scratch.

  • Flexibility: Easy to modify behavior by changing the prompt.

  • Conversational Capability: Leverages the LLM’s natural ability for fluid conversations.

Some Limitations of Using Workflows in Chatbots:

  • Fine Control: It can be more difficult to ensure it always follows exactly one complex logical path, although detailed prompts minimize this.

  • State: Managing complex states over very long conversations may require more advanced prompting techniques.

Requirement Examples

Let’s simulate a real need from some clients across 5 exercises. Given the following business requirements, we will implement the chatbots using LLMs. Therefore, first comes the business requirement, and after all requirements are presented, the implementation solution using only prompts.\

Requirements

Build a chatbot that takes a pizza order for a pizzeria.
Ask the customer which crust they prefer: pan or thin.
Ask which topping they want: cheese, calabresa sausage, or bacon.
If they pick pan crust, ask whether to stuff the crust with gorgonzola or cheddar.
Show the selected options at the end.
Build a chatbot that sells pants or shirts for a clothing store.
Ask the customer whether they want pants or a shirt.
For pants, ask for a size (34, 35, or 36) and a fit (slim, regular, or skinny).
For a shirt, ask for a size (S, M, or L) and a neckline (V-neck, crew neck, or polo collar).
Summarize the choices and tell the customer the order is being processed.
Build a chatbot that sells travel packages for a tour company.
Ask the customer to choose Maceió, Aracaju, or Fortaleza.
For Maceió, ask if they know the city's natural attractions and suggest the Nove Ilhas and Orla de Alagoas packages.
For Aracaju, ask them to choose the Passarela do Caranguejo or Orla de Aracaju tour. Tell them transport is by bus only and ask if they still want to continue.
For Fortaleza, offer the Falésias Cearenses package and ask whether they prefer to travel by bus or plane.
For any destination, ask whether they want to pay by credit or debit card.
Summarize the choices and tell the customer the booking is being processed.
Build a banking application that helps a user open a checking account.
Ask whether the user has an account at another bank. If so, ask whether they want to switch their account to this bank.
Ask for the prospective account holder's name and the initial deposit, which may be zero.
Ask whether they want a loan.
Summarize the account holder's name, whether they requested a loan or an account switch, and the initial deposit.
Build a chatbot for enrollment in two elective courses.
Offer Advanced Artificial Intelligence and Machine Learning.
Check that the student has completed Introduction to Programming, the prerequisite for both electives.
If the student chooses Advanced Artificial Intelligence, ask whether they have taken Artificial Intelligence.
At the end, list the courses the student enrolled in.

Solution

Below, we show how the conversation flows from the previous exercise can be translated into prompts for an LLM. Each prompt instructs the model to act as the specific chatbot and follow the defined rules.

You take orders for a pizzeria. If a question falls outside pizza ordering, say you do not know the answer.
Follow these steps in order:
1. Ask the customer to choose a crust. The valid options are "pan" and "thin".
   Example: "Hi! Would you like a pan crust or a thin crust?"
2. After they choose a crust, ask for a topping. The valid options are "cheese", "calabresa sausage", and "bacon".
   Example: "Great! Which topping would you like: cheese, calabresa sausage, or bacon?"
3. Ask about a stuffed crust only if the customer picked "pan". The valid fillings are "gorgonzola" and "cheddar".
   Example: "We can stuff your pan crust. Would you like gorgonzola or cheddar?"
4. Summarize the order, including the crust, topping, and stuffed-crust filling if applicable.
   Example: "Your order is a [crust] pizza with [topping] [and a crust stuffed with [filling], if applicable]."
Start the conversation with step 1.
You help customers buy pants or a shirt from a clothing store. If a question falls outside this task, say you do not know the answer.
Follow these steps in order:
1. Ask whether the customer is shopping for "pants" or a "shirt".
   Example: "Welcome! Are you looking for pants or a shirt today?"
2. If they choose pants:
   a. Ask for size "34", "35", or "36".
      Example: "Which pants size do you wear: 34, 35, or 36?"
   b. Ask for "slim fit", "regular fit", or "skinny fit".
      Example: "What fit would you prefer: slim, regular, or skinny?"
3. If they choose a shirt:
   a. Ask for size "S", "M", or "L".
      Example: "Which shirt size would you like: S, M, or L?"
   b. Ask for a "V-neck", "crew neck", or "polo collar".
      Example: "Which neckline would you like: V-neck, crew neck, or polo collar?"
4. Summarize the item and its options, and say the order is being processed.
   Pants example: "You chose size [size] pants in [fit]. Your order is being processed."
   Shirt example: "You chose a size [size] shirt with a [neckline]. Your order is being processed."
Start the conversation with step 1.
You are a virtual travel agent helping a customer choose and configure a tour package. If a question falls outside this task, say you do not know the answer.
Follow these steps in order:
1. Ask the customer to choose "Maceió", "Aracaju", or "Fortaleza".
   Example: "Hi! We offer packages for Maceió, Aracaju, and Fortaleza. Which destination interests you?"
2. If they choose Maceió:
   a. Ask whether they already know the city's natural attractions. Their answer is conversational and leaves the flow as it is.
      Example: "Maceió is beautiful! Have you seen its natural attractions?"
   b. Offer "Nove Ilhas" and "Orla de Alagoas" and ask which they prefer.
      Example: "We have two packages in Maceió: Nove Ilhas and Orla de Alagoas. Which would you prefer?"
   c. Go to step 5.
3. If they choose Aracaju:
   a. Ask them to choose "Passarela do Caranguejo" or "Orla de Aracaju".
      Example: "We offer tours of Passarela do Caranguejo and Orla de Aracaju. Which would you like?"
   b. Explain that travel to Aracaju is by bus only and ask whether to continue.
      Example: "We currently offer bus transport to Aracaju. Would you like to continue with your booking?"
   c. If they confirm, go to step 5. Otherwise, thank them and end the conversation.
4. If they choose Fortaleza:
   a. Tell them the available package is "Falésias Cearenses".
      Example: "For Fortaleza, we offer the Falésias Cearenses package."
   b. Ask whether they want to travel to Ceará by "bus" or "plane".
      Example: "Would you prefer to travel to Ceará by bus or by plane?"
   c. Go to step 5.
5. After collecting the destination, package or tour, and transport if applicable, ask for their payment method. The options are "credit card" and "debit card".
   Example: "Would you like to pay by credit card or debit card?"
6. Summarize the destination, package or tour, transport if applicable, and payment method. Say the booking is being processed.
   Example: "Your package for [destination] includes [package or tour], [transport, if applicable], and payment by [payment method]. Your booking is being processed."
Start the conversation with step 1.
You are a virtual banking assistant helping a user open a checking account. If a question falls outside this task, say you do not know the answer.
Follow these steps in order:
1. Ask whether the user has an account at another bank. Expected answers: "yes" or "no".
   Example: "Welcome! Do you already have a checking account at another bank?"
2. If they answer "yes", ask whether they want to switch their existing account to this bank. Expected answers: "yes" or "no".
   Example: "Would you like to request an account switch to our bank?"
3. Ask for the prospective account holder's full name.
   Example: "Please provide your full name for the application."
4. Ask for the initial deposit. Tell the user it can be zero or another amount.
   Example: "How much would you like to deposit initially? You can choose R$0.00 or another amount."
5. Ask whether they are interested in requesting a preapproved loan with the new account. Expected answers: "yes" or "no".
   Example: "Would you like to check for a preapproved loan offer now?"
6. Summarize the full name, account-switch request, loan request, and initial deposit.
   Example: "Your application is complete. Account holder: [full name]. Account switch requested: [yes/no]. Loan requested: [yes/no]. Initial deposit: R$[amount]."
Start the conversation with step 1.
You are a university enrollment assistant helping a student enroll in up to two electives. If a question falls outside this task, say you do not know the answer.
Follow these steps in order:
1. Present the electives "Advanced Artificial Intelligence" and "Machine Learning".
   Example: "Hello! You can enroll in Advanced Artificial Intelligence or Machine Learning."
2. Ask whether the student completed and passed "Introduction to Programming", which is required for both electives. Expected answers: "yes" or "no".
   Example: "Both electives require a passing grade in Introduction to Programming. Have you met this requirement?"
3. If they answer "no", explain that they are currently ineligible and end the conversation.
   Example: "You need to pass Introduction to Programming before enrolling in these electives. Contact your program coordinator for more information."
4. If they answer "yes":
   a. Ask which course they want, or whether they want both.
      Example: "Would you like to enroll in Advanced Artificial Intelligence, Machine Learning, or both?"
   b. If they choose Advanced Artificial Intelligence alone or with Machine Learning, ask whether they have taken "Artificial Intelligence". Expected answers: "yes" or "no".
      Example: "We recommend taking Artificial Intelligence before Advanced Artificial Intelligence. Have you taken it?"
      Note: Treat this as a recommendation and record the answer. The student can still enroll.
   c. Confirm enrollment in the courses the student selected once the Introduction to Programming requirement is verified.
      Example for both electives: "You are enrolled in Advanced Artificial Intelligence and Machine Learning."
      Example for Machine Learning only: "You are enrolled in Machine Learning."
      Example for Advanced Artificial Intelligence without prior AI coursework: "You are enrolled in Advanced Artificial Intelligence."
Start the conversation with step 1.

See Figure 4.11 for an example of implementation and dialogue when using ChatGPT.

Chatbot created with LLM (via ChatGPT).

Figure 4.11. Chatbot created with LLM (via ChatGPT).

The quality of an LLM’s response depends heavily on the clarity and detail of the prompt. The more specific the instructions, the higher the probability that the chatbot will behave exactly as desired. However, during the period in which this book was written, LLMs were good at detecting intent but were not yet as efficient at following complex instructions. Therefore, agent orchestration frameworks, such as mangaba.ia or crewAI, prove useful, as more atomic agents tend to perform better. The use of orchestration—chaining small agents with well-defined intents and transferring part of the instructions to communication between them, with the support of these frameworks—has received good acceptance from the community.

4.8 Integration of Techniques

In this section, we will explore how to integrate the techniques discussed in the previous sections to build efficient chatbots. We will address the use of Large Language Models (LLMs), Fine-Tuning, Retrieval-Augmented Generation (RAG), and LLaMA in a single system, aiming to create sophisticated and personalized dialogue experiences.

Designing a Chatbot: Building an advanced chatbot requires combining several techniques to ensure it is capable of understanding, processing, and responding to a wide range of user queries. Let us review the main components:

  • Large Language Model (LLM): The foundation for understanding and generating natural language.

  • Fine-Tuning: Adapting the LLM to specific domains or tasks.

  • Retrieval-Augmented Generation (RAG): Improving the relevance and accuracy of responses by combining information retrieval with text generation.

  • LLaMA: Using a more efficient model for production systems that need to balance performance and cost.

Chatbot Architecture: A chatbot’s architecture can be designed in a modular way, combining different techniques according to the application’s needs. First, the user’s input is captured and tokenized; next, the input is analyzed to determine intent and extract important entities. If necessary, the chatbot retrieves relevant information from an external database. Then, the LLM, potentially adjusted with Fine-Tuning, is used to generate a response based on the input and the retrieved information. Finally, the generated response is sent back to the user. See Figure 4.12 for a visual diagram of this procedure.

Data flow in a chatbot.

Figure 4.12. Data flow in a chatbot.

Implementing a Chatbot with LLaMA and RAG: Let us now implement a chatbot that uses LLaMA as the main model for response generation and RAG for retrieving additional information, if necessary.

Initial setup. First, configure the main components. LLaMA generates responses and Dense Passage Retrieval (DPR) retrieves information. We recommend using a Google Colab runtime with an A100 GPU. Run the following three code blocks in order.

from transformers import AutoTokenizer, AutoModelForCausalLM, DPRQuestionEncoder, DPRContextEncoder

# Load the tokenizer and the LLaMA model
llama_tokenizer = AutoTokenizer.from_pretrained(
"meta-llama/LLaMA-7B")
llama_model = AutoModelForCausalLM.from_pretrained(
"meta-llama/LLaMA-7B")

# Set up DPR for passage retrieval
question_encoder = DPRQuestionEncoder.from_pretrained( "facebook/dpr-question_encoder-single-nq-base")
context_encoder = DPRContextEncoder.from_pretrained( "facebook/dpr-ctx_encoder-single-nq-base")
Some weights of the model checkpoint at facebook/dpr-ctx_encoder-single-nq-base were not used when initializing DPRContextEncoder: ['ctx_encoder.bert_model.pooler.dense.bias', 'ctx_encoder.bert_model.pooler.dense.weight']
- This IS expected if you are initializing DPRContextEncoder from the checkpoint of a model trained on another task or with another architecture (e.g. initializing a BertForSequenceClassification model from a BertForPreTraining model).
- This IS NOT expected if you are initializing DPRContextEncoder from the checkpoint of a model that you expect to be exactly identical (initializing a BertForSequenceClassification model from a BertForSequenceClassification model).

Input Processing and Information Retrieval: Next, we implement the logic to process the user’s input and, if necessary, retrieve relevant information from a database. The code block below should be executed in Google Colab, in another cell, after the previous code.

# Run this snippet after the previous one.
import torch

def retrieve_relevant_passage(query, passages):
    query_input = question_tokenizer(query, return_tensors="pt")
    query_embedding = question_encoder(
       **query_input).pooler_output

    passage_inputs = context_tokenizer(passages, padding=True, truncation=True, return_tensors="pt")
    passage_embeddings = context_encoder(
      **passage_inputs).pooler_output

    similarity_scores = torch.matmul(query_embedding, passage_embeddings.T)
    best_passage_index = torch.argmax(similarity_scores, dim=1).item()

    return passages[best_passage_index]

# Example passages
passages = [
    "LLaMA é um modelo de linguagem desenvolvido pela Meta AI.",
    "RAG combina recuperação de informações com geração de texto.",
    "GPT-3 é um dos maiores modelos de linguagem disponíveis."
]

# User input
user_input = "O que é LLaMA?"

# Retrieve the most relevant passage
relevant_passage = retrieve_relevant_passage(user_input, passages)

print(f"Most relevant passage: {relevant_passage}")
Most relevant passage: LLaMA é um modelo de linguagem desenvolvido pela Meta AI.

LLaMA Response Generation: Finally, we use the LLaMA model to generate a response, using both the original user input and the retrieved passage. The code block below should be executed in Google Colab, in another cell, after the previous code.

# Concatenate the query and the relevant passage
input_text = user_input + " " + relevant_passage

# Generate a response
input_ids = llama_tokenizer.encode(input_text, return_tensors="pt")
generated_ids = llama_model.generate(input_ids, max_length=50, num_beams=5, early_stopping=True)
response = llama_tokenizer.decode(generated_ids[0], skip_special_tokens=True)

print("Chatbot response:", response)
Chatbot response: O que é LLaMA? LLaMA é um modelo de linguagem desenvolvido pela Meta AI. LLaMA é um acrônimo para Large Language Model, que significa modelo de linguagem grande. LLaMA é

In this example, the chatbot generates a response based on the combination of the user’s input and the relevant information retrieved, creating an informative and contextualized response.

Challenges in Chatbot Implementation: Implementing chatbots with multiple techniques presents several challenges, such as: combining models like LLaMA and DPR can be computationally intensive, especially in real-time applications; Fine-Tuning and model configuration need to be well-adjusted to ensure the chatbot is effective and relevant in its responses; furthermore, ensuring that the different components (retrieval, generation, etc.) function cohesively can be challenging. Nevertheless, chatbots can be applied in a variety of scenarios, such as: providing automated, personalized, real-time support; assisting in symptom triage or providing basic medical information; or even creating virtual tutors that can answer students’ questions accurately and contextually.

4.9 API and Playground

Generally, the developer of an LLM provides a web interface for the user to converse with their model in the form of a chatbot and provides an API (with a playground) for those who wish to integrate the solution into their applications. This is the case with ChatGPT, from the company OpenAI. They charge a fixed fee to provide subscribers with full access to their chatbot’s resources, including the SearchGPT feature (a web search), whiteboard, video generation, images, etc. For API access, the billing model is pay-per-use. See Figure 4.13 for an image of the OpenAI chatbot and Figure 4.14 for the OpenAI playground.

OpenAI Chatbot.

Figure 4.13. OpenAI Chatbot.

OpenAI Playground.

Figure 4.14. OpenAI Playground.

There is an inference provider called GROQ https://groq.com/. GROQ (with Q) is an infrastructure provider for inference in large language models (LLMs). This company sells an inference service that is faster than its competitors. On GROQ, we can use several openly available LLMs, such as Meta’s Llama, Google’s Gemma, or Mixtral AI’s Mixtral. ChatGPT is not available on GROQ because it is not open source.

Among other models, they use a version of LLaMA in their GROQ Chatbot, however their focus is the API, which can be tested on the GROQ playground. The playground operates on a pay-per-use format. The GROQ Chatbot also consumes the same pay-per-use credits, without a separate subscription, unlike the case of the ChatGPT chatbot. See Figure 4.15 for the GROQ Chatbot and Figure 4.16 for the GROQ Playground. Note that the GROQ Chatbot does not have the history feature like ChatGPT.

GROQ Chatbot.

Figure 4.15. GROQ Chatbot.

GROQ Playground.

Figure 4.16. GROQ Playground.

Grok (with a K) is the chatbot from xAI. It is a chatbot and is available to those with premium access to X (e.g., Twitter), while the Grok API can be accessed on a pay-as-you-go basis. At the time of writing, Grok offered R$25 in credit to try the API. However, Grok does not have an advanced playground, so to use the Grok API, one must use a graphical tool or external code, for example: LLM Studio, JAN AI, GPT4ALL, or the excellent Msty app. See Figure 4.17 for the Grok chatbot and Figure 4.18 for the Grok playground.

Grok Interface.

Figure 4.17. Grok Interface.

Grok Playground.

Figure 4.18. Grok Playground.

4.10 Summary

Large Language Models (LLMs) have played a central role in the revolution of Natural Language Processing (NLP). These models, which include variants such as GPT, BERT, and their successors, are capable of performing a wide range of tasks, from text generation to deep language understanding, thanks to their training on large volumes of textual data.

These models are fed by vast sets of textual data and use deep learning techniques, particularly neural networks, to learn patterns, contexts, and nuances of language. They are capable of performing a variety of linguistic tasks, including automatic translation, text generation, information summarization, question answering, and even the creation of interactive dialogues. They operate based on complex architectures, such as the Transformer, which allows the model to pay attention to different parts of a text simultaneously, facilitating the understanding of context and semantic relations between words and phrases.

The training of these models involves exposure to enormous amounts of text, which allows them to develop a deep understanding of grammar, vocabulary, and communication styles. However, this ability to generate coherent and relevant text also raises ethical and responsibility issues, especially regarding misinformation, algorithmic bias, and privacy.

They today represent a significant milestone in the evolution of artificial intelligence, just as Eliza did in its time, but with a greater impact, offering tools for human-computer interaction and opening new possibilities for applications in various areas, such as education (Silva et al. 2020), customer service, or content creation.

In this chapter, we explore the Transformer architecture, which revolutionized Natural Language Processing by introducing the attention mechanism. We discuss how Transformers work and how they are applied in popular models such as BERT and GPT. With examples in Python, we saw how to use these models for NLP tasks.

We also explored the technique of Retrieval-Augmented Generation (RAG), an approach that combines information retrieval with text generation. We saw how to implement RAG in Python using models such as DPR and BART, and discussed the applications and challenges of this technique.

Additionally, we explored LLMs, including their architectures, training techniques, and primary applications. Models such as GPT, BERT, T5, and XLNet exemplify how LLMs are redefining the field of NLP. With practical examples, we demonstrated how these models can be applied to a variety of tasks.

Another topic explored in this chapter was the process of Fine-Tuning pre-trained models, discussing their importance, challenges, and practical applications. Fine-Tuning allows Large Language Models to be adapted for specific tasks with efficiency, making them extremely versatile in various NLP applications.

We also explored LLaMA, a language model designed to be efficient and accessible without compromising its ability to perform complex NLP tasks. With an optimized architecture and a focus on computational efficiency, LLaMA offers a practical alternative to massive models like GPT-3. We also saw how to implement LLaMA in Python for text generation tasks and discussed its applications and limitations.

Furthermore, we integrated various techniques discussed in previous chapters to create a chatbot capable of providing accurate and contextualized responses using LLaMA and RAG. The implementation of these techniques provides a small foundation for the development of efficient dialogue systems.