Working with GenAI on K8s – Chatbot Example
local graph
Chapter 5 — Working with GenAI on K8s – Chatbot Example
Section titled “Chapter 5 — Working with GenAI on K8s – Chatbot Example”In this chapter, we will build on the examples we discussed in Chapter 4 and start deploying those examples in K8s / Amazon EKS. We will start by deploying JupyterHub (https://jupyter.org/hub) on EKS, which can be used for model experimentation. Next, we will fine-tune the Llama 3 model within EKS and deploy it. Finally, we’ll set up a RAG-powered chatbot that will deliver personalized recommendations for an e-commerce company use case.
We’ll cover the following key topics:
- GenAI use cases for e-commerce
- Experimentation using JupyterHub
- Fine-tuning Llama 3 in K8s
- Deploying the fine-tuned model on K8s
- Deploying a RAG application on K8s
- Deploying a chatbot on K8s
Technical requirements
Section titled “Technical requirements”In this chapter, we will be using the following tools, some of which require you to set up an account and create an access token:
- Hugging Face: https://huggingface.co/join
- OpenAI: https://platform.openai.com/signup
- The Llama 3 model, which can be accessed via Hugging Face: https://huggingface.co/meta-llama/Meta-Llama-3-8B
- An Amazon EKS cluster, as illustrated in Chapter 3
GenAI use cases for e-commerce
Section titled “GenAI use cases for e-commerce”As we discussed in Chapter 1, it is critical to think about KPIs and business objectives as we explore possible deployment options for GenAI applications. For an e-commerce platform, possible use cases could be chatbots to answer customer questions, personalized recommendations, content creation for product descriptions, and personalized marketing campaigns.
Let’s say that we have an e-commerce company called MyRetail for which we have been given the responsibility to explore and deploy GenAI use cases. The company has been growing rapidly and has a clear goal and strong differentiation: to provide its customers with a personalized, seamless shopping experience. To stay competitive, MyRetail aims to integrate cutting-edge AI technologies into its customer service while focusing on the following two features:
- Creating personalized product recommendations using a RAG system.
- Providing automated responses to inquiries related to the company’s loyalty program through a fine-tuned GenAI model.
MyRetail’s diverse customer base means that generic product recommendations and traditional FAQ systems are no longer sufficient. Customers expect personalized shopping experiences, and the company’s MyElite loyalty program needs to offer real-time, detailed information on rewards, points, and account status.
To achieve these goals, MyRetail has decided to adopt the open source K8s orchestration platform and has selected Amazon EKS to deploy it in the cloud. They plan to build a chatbot application that utilizes two GenAI models: the first one will be a fine-tuned Llama 3 model trained on their MyElite loyalty program FAQ to answer user queries, while the second one will be a RAG application that supplements user queries with contextual shopping catalog data to enhance their shopping experience. The overall architecture of this solution is shown in Figure 5*.1*:

Figure 5.1 – Chatbot architecture
However, before we implement this chatbot and RAG system in EKS, let’s create a JupyterHub -based playground for our data scientists to experiment with and optimize the GenAI models.
Experimentation using JupyterHub
Section titled “Experimentation using JupyterHub”Experimentation plays a vital role in any GenAI project life cycle as it enables engineers and researchers to iterate, improve, and refine models while optimizing performance. Several tools are available for this; recall that we used Anaconda and Google Colab in Chapter 4. Primarily, these tools help us to experiment interactively with GenAI models, visualize, monitor, and integrate with popular AI/ML frameworks, integrate with cloud services, and collaborate with others. Jupyter Notebook (https://jupyter.org/) has gained widespread adoption among data scientists and ML engineers due to its flexibility and easy-to-use web interface. This is evident from the average daily downloads of the notebook package (900K to 1 million downloads) (https://pypistats.org/packages/notebook), as indicated by the Python Package Index (https://pypi.org/). Traditionally, we install these notebooks on local machines, but they often need specialized resources such as GPUs to perform meaningful analysis. To solve this issue, we will leverage a K8s cluster to spin up Jupyter notebooks as needed using JupyterHub.
JupyterHub offers a centralized platform for running Jupyter notebooks, enabling users to access computational resources without requiring individual installations or maintenance. System administrators can manage user access effectively and tailor the environment with pre-configured tools and settings to meet user-specific preferences.
Let’s start by learning how to install JupyterHub on an Amazon EKS cluster:
- First, deploy the Amazon EBS CSI driver add-on. Jupyter notebooks require access to persistent storage volumes so that they can store session data, custom configurations, datasets, and more. The Amazon EBS CSI driver (https://github.com/kubernetes-sigs/aws-ebs-csi-driver) lets us use Amazon EBS volumes (https://aws.amazon.com/ebs/) for the K8s Pods in the EKS cluster and manages the life cycle of the EBS volumes as storage for ephemeral and persistent K8s volumes. We have made the following changes to
addons.tfto install the CSI plugin, as well as added the necessary IAM permissions. The complete code for this is available on GitHub at https://github.com/PacktPublishing/Kubernetes-for-Generative-AI-Solutions/blob/main/ch5/addons.tf:module "eks_blueprints_addons" {....eks_addons = {aws-ebs-csi-driver = {service_account_role_arn = module.ebs_csi_driver_irsa.iam_role_arn}....}module "ebs_csi_driver_irsa" {...role_name_prefix = format("%s-%s", local.name, "ebs-csi-driver-")attach_ebs_csi_policy = true...} - Now, we need to create a default StorageClass (https://kubernetes.io/docs/concepts/storage/storage-classes/) for the EBS CSI driver that specifies attributes such as the reclaim policy, storage provisioner, and other parameters used in dynamic volume provisioning. Here, we are setting the newer gp3 as the default type for EBS CSI driver-created volumes. Refer to the Amazon EBS documentation at https://docs.aws.amazon.com/ebs/latest/userguide/ebs-volume-types.html to learn more about different
resource "kubernetes_annotations" "disable_gp2" {annotations = {"storageclass.kubernetes.io/is-default-class": "false"...metadata {name = "gp2"...resource "kubernetes_storage_class" "default_gp3" {metadata {name = "gp3"annotations = {"storageclass.kubernetes.io/is-default-class": "true"...}
- Run the following commands to deploy the EBS CSI driver to the
$ terraform init$ terraform plan$ terraform apply -auto-approve
- You can verify the installation status of the add-on by running the
$ aws eks describe-addon --cluster-name eks-demo --addon-name aws-ebs-csi-driver..."addonName": "aws-ebs-csi-driver","clusterName": "eks-demo","status": "ACTIVE",...
- Now, start deploying the JupyterHub add-on by running the
eks-data-addons(https://registry.terraform.io/modules/aws-ia/eks-data-addons/aws/latest) Terraform module on the EKS cluster. This open source module can be utilized to deploy commonly used data and AI/ML K8s add-ons. Please refer to the Terraform documentation page at https://registry.terraform.io/modules/aws-ia/eks-data-addons/aws/latest#resources to find a list of available add-ons. Make sure you download theaiml-addons.tffile from https://github.com/PacktPublishing/Kubernetes-for-Generative-AI-Solutions/blob/main/ch5/aiml-addons.tf; it includes Terraform code to deploy the JupyterHub add-on on the EKS cluster. Let’s walk through what the Terraform code does:- A random 16-character string is created to secure access
Important note
In this setup, we are using a dummy authentication method where JupyterHub uses a static username and password. It also provides other authentication methods, as listed at https://jupyterhub.readthedocs.io/en/latest/reference/authenticators.html. Use the method that fits your needs.
resource "random_password" "jupyter_pwd" {length = 16special = trueoverride_special = "_%@"}
- A new K8s namespace called
jupyterhubis defined to deploy the JupyterHub
resource "kubernetes_namespace" "jupyterhub" {metadata {name = "jupyterhub"}}- A K8s service account and an IAM role with appropriate S3 permissions to read from the S3 buckets are defined for interacting with S3 via Jupyter notebooks. We are using the IAM roles for service accounts (https://docs.aws.amazon.com/eks/latest/userguide/iam-roles-for-service-accounts.html) feature of Amazon EKS, which provides IAM credentials to applications running in K8s
module "jupyterhub_single_user_irsa" {...role_name = "${module.eks.cluster_name}-jupyterhub-single-user-sa"role_policy_arns = {policy = "arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess"}...resource "kubernetes_service_account_v1" "jupyterhub_single_user_sa" {metadata {name = "${module.eks.cluster_name}-jupyterhub-single-user"annotations = {"eks.amazonaws.com/role-arn": module.jupyterhub_single_user_irsa.iam_role_arn}...- Now, we must deploy the JupyterHub Helm chart. We are using Helm values from a public S3 bucket available at https://kubernetes-for-genai-models.s3.amazonaws.com/chapter5/jupyterhub-values.yaml. It contains the necessary configuration to enable dummy authentication using the password we randomly generated previously and uses a K8s service account for Jupyter
data "http" "jupyterhub_values" {url = "https://kubernetes-for-genai-models.s3.amazonaws.com/chapter5/jupyterhub-values.yaml"}module "eks_data_addons" {source = "aws-ia/eks-data-addons/aws"...enable_jupyterhub = truejupyterhub_helm_config = {values = [local.jupyterhub_values_rendered]...- Run the following commands to deploy JupyterHub on the
$ terraform init$ terraform plan$ terraform apply -auto-approve- Verify that JupyterHub has been installed by running the
$ helm list -n jupyterhubNAME NAMESPACE REVISION STATUSjupyterhub jupyterhub 1 deployed - A new K8s namespace called
- A random 16-character string is created to secure access
Important note
In this setup, we are using a dummy authentication method where JupyterHub uses a static username and password. It also provides other authentication methods, as listed at https://jupyterhub.readthedocs.io/en/latest/reference/authenticators.html. Use the method that fits your needs.
- Since we are experimenting with GenAI models, we need to run the Jupyter notebooks on GPU instances. Given that the EKS cluster doesn’t have GPU instances, we need to add one more EKS-managed node group to
eks.tfthat contains GPU nodes (g6.2xlarge). Here, we are using EC2 Spot Instances pricing to minimize AWS charges; please refer to the documentation at https://aws.amazon.com/ec2/spot/pricing/ for pricing details. We are also adding K8s taints (https://kubernetes.io/docs/concepts/scheduling-eviction/taint-and-toleration/) to ensure that only GPU workloads are scheduled to these worker nodes. K8s taints are key-value pairs that are applied to nodes that prevent certain Pods from being scheduled on them unless the Pods tolerate the taints, allowing for better control over workload placement. By applying taints, we can ensure that non-GPU workloads are prevented from being scheduled on GPU nodes, reserving those nodes exclusively for GPU-optimized Pods. You can download theeks.tffile from https://github.com/PacktPublishing/Kubernetes-for-Generative-AI-Solutions/blob/main/ch5/eks.tf.module "eks" {....eks_managed_node_groups = {eks-gpu-mng = {instance_types = ["g6.2xlarge"]capacity_type = "SPOT"taints = {gpu = {key = "nvidia.com/gpu"value = "true"effect = "NO_SCHEDULE"....} - Run the following commands to add the GPU node group to the EKS cluster. Please note that this may take 5-10 minutes. You can verify the GPU node’s status by running the following
kubectlcommand, which outputs the node’s name$ terraform init$ terraform plan$ terraform apply -auto-approve$ kubectl get nodes -l nvidia.com/gpu.present=trueNAME STATUSip-10-0-17-1.us-west-2.compute.internal Ready - Now, we can connect to the JupyterHub console to create a notebook. In this setup, we’ve limited JupyterHub console access to within the cluster by exposing it as a ClusterIP service. Run the following commands to connect to the console locally; alternatively, you can set the service type to LoadBalancer to expose it via a
$ kubectl port-forward svc/proxy-public 8000:80 -n jupyterhub
- You can launch the JupyterHub console by navigating to http://localhost:8000/ in your web browser. You’ll see a login page, similar to what’s shown in .2. Here, we’ve pre-created a user named k8s-admin1 as part of our JupyterHub installation. Run the following command to retrieve the password of
$ terraform output jupyter_pwd

Figure 5.2 – JupyterHub login page
- After logging in, you will be presented with three notebook options. Since we are using JupyterHub for GenAI tasks that need GPU power, select Data Science (GPU) and click Start, as shown in Figure 5*.3*:

Figure 5.3 – JupyterHub home page
- As shown in Figure 5*.4*, this will start a new notebook instance running in a K8s Pod and also request a Persistent Volume Claim (PVC) (https://kubernetes.io/docs/concepts/storage/persistent-volumes) so that the EBS CSI driver will create an Amazon EBS volume and attach it to the notebook. We’re using a persistent volume here to preserve the notebook’s state, data, and configurations across Pod restarts and terminations. This allows the notebook instance to be terminated after periods of inactivity and relaunched when the user returns, making the process more cost-efficient:
$ kubectl get pods -n jupyterhub -l component=singleuser-serverNAME READY STATUS RESTARTS AGEjupyter-k8s-2dadmin1 1/1 Running 0 9m

Figure 5.4 – Our Jupyter notebook
- You can now import the following notebooks from Chapter 4 and execute the necessary commands to test both the RAG and fine-tuning examples:
With that, we have set up JupyterHub on the EKS cluster and used it to launch a Jupyter notebook to test our GenAI experimentation scripts. Next, we will containerize both the fine-tuning and RAG scripts and run them as K8s Pods on the EKS cluster.
Fine-tuning Llama 3 in K8s
Section titled “Fine-tuning Llama 3 in K8s”As discussed in Chapter 3, running fine-tuning workloads on K8s has several advantages, including scalability, efficient resource utilization, portability, and monitoring. In this section, we will containerize the Llama 3 fine-tuning job that we experimented with in the Jupyter notebook and deploy it on the EKS cluster. This is essential for automating the end-to-end AI/ML pipelines and versioning the models.
The following steps are involved in fine-tuning a Llama 3 model:
- Gather training and evaluation datasets and store them in Amazon S3.
- Create a container image and upload it to Amazon ECR.
- Deploy the fine-tuning job in the EKS cluster.
Data preparation
Section titled “Data preparation”We will utilize two datasets (training and evaluation) to fine-tune and validate a Llama 3 model that answers questions related to MyRetail’s MyElite loyalty program. When running the fine-tuning jobs in containers, it is recommended to store the datasets in an external datastore and access them during the fine-tuning process. By doing so, we can make the container image agnostic to the dataset, and we will be able to reuse the image for different datasets. For your convenience, we have stored the MyElite loyalty program’s training and evaluation datasets in a public Amazon S3 bucket called kubernetes-for-genai-models. Amazon S3 (https://aws.amazon.com/s3/) is an object storage service that’s used to store and retrieve any amount of data from anywhere, making it the ideal choice for sharing large datasets for collaboration:
$ aws s3 ls s3://kubernetes-for-genai-models/chapter5/...loyalty_qa_train.jsonlloyalty_qa_val.jsonl...In this section, we explored the datasets that will be used to fine-tune the Llama 3 model for our e-commerce use case. We also covered best practices such as storing these databases in external storage services such as Amazon S3 rather than packaging them in the container image. In the next section, we will focus on creating a container image for the fine-tuning job.
Creating a container image
Section titled “Creating a container image”To create a container image for the fine-tuning job, we need a Dockerfile, a fine-tuning script, and a dependency list. We’ve already created these artifacts and made them available on GitHub: https://github.com/PacktPublishing/Kubernetes-for-Generative-AI-Solutions/tree/main/ch5/llama-finetuning. Let’s start building the container so that we can fine-tune the Llama 3 model with these artifacts:
- Create a directory
llama-finetuning$ mkdir -p llama-finetuning$ cd llama-finetuning - We will be using the Llama 3 fine-tuning code from Chapter 4 while making the following changes to make it container-ready. You’ll need to request access to the Llama 3 model in Hugging Face and generate an access token before proceeding. Please refer to Chapter 2 for instructions on how to do this. The complete fine-tuning code is available on GitHub at https://github.com/PacktPublishing/Kubernetes-for-Generative-AI-Solutions/blob/main/ch5/llama-finetuning/fine_tune.py:
- Read the filenames of the training and evaluation datasets from the relevant environment variables and load them using the
datasets...train_dataset_file = os.environ.get('TRAIN_DATASET_FILE')eval_dataset_file = os.environ.get('EVAL_DATASET_FILE')train_dataset = load_dataset('json', data_files=train_dataset_file, split='train')eval_dataset = load_dataset('json', data_files=eval_dataset_file, split='train')- After training, we need to save the model weights, configuration files, and tokenizer configuration so that they can be used to create an inference
trainer.save_model(f"./{fine_tuned_model_name}")tokenizer.save_pretrained(f"./{fine_tuned_model_name}")- Export the model weights and configuration files to an
...def sync_folder_to_s3(local_folder, bucket_name, s3_folder):s3 = boto3.client('s3')for root, dirs, files in os.walk(local_folder):for file in files:...try:s3.upload_file(local_path, bucket_name, s3_path)except Exception as e:print(f'Error uploading {local_path}: {e}')...sync_folder_to_s3('./'+fine_tuned_model_name+'/', model_assets_bucket, fine_tuned_model_name)
- Read the filenames of the training and evaluation datasets from the relevant environment variables and load them using the
- Create a Dockerfile where we can build the fine-tuning container image. It should start with the nvidia/cuda (https://hub.docker.com/r/nvidia/cuda) parent image, install the required Python dependencies, and contain the fine-tuning script. The complete file is available at https://github.com/PacktPublishing/Kubernetes-for-Generative-AI-Solutions/blob/main/ch5/llama-finetuning/Dockerfile:
FROM nvidia/cuda:12.8.1-runtime-ubuntu24.04...RUN pip install torch transformers datasets peft accelerate bitsandbytes sentencepiece s3fs boto3...COPY fine_tune.py /app/fine_tune.pyCMD ["python", "fine_tune.py"]
- Create the container image by running the
$ docker build -t my-llama-finetuned .
- You can verify the container image by using the following
$ docker imagesREPOSITORY TAG IMAGE IDmy-llama-finetuned latest 207a07f1bf00
With that, we’ve successfully built the container image so that we can fine-tune the Llama 3 model. Next, we will upload this to an Amazon ECR repository and deploy it to the EKS cluster.
Deploying the fine-tuning job
Section titled “Deploying the fine-tuning job”To deploy the fine-tuning job, we need to save the container image in Amazon ECR and create an S3 bucket where we’ll save model assets, as well as create a K8s job in the EKS cluster:
- Create an Amazon ECR repository using Terraform and upload this container image. Add the following code to the
ecr.tffile in thegenai-eks-demodirectory. The complete code is available on GitHub at https://github.com/PacktPublishing/Kubernetes-for-Generative-AI-Solutions/blob/main/ch5/ecr.tf:resource "aws_ecr_repository" "my-llama-finetuned" {name = "my-llama-finetuned"... - Create an Amazon S3 bucket so that you can store the fine-tuned model assets. We’ll create one using Terraform. Download the
model-assets.tffile https://github.com/PacktPublishing/Kubernetes-for-Generative-AI-Solutions/blob/main/ch5/model-assets.tfresource "random_string" "bucket_suffix" {length = 8...resource "aws_s3_bucket" "my_llama_bucket" {bucket = "my-llama-bucket-${random_string.bucket_suffix.result}"...output "my_llama_bucket" {value = "${aws_s3_bucket.my_llama_bucket.id}"... - We also need to create a K8s service account and an IAM role for our fine-tuning job so that it can download the training and validation datasets and upload the model asset files to the Amazon S3 bucket. This was added as part of the
eks.tffile you downloaded earlier:module "llama_fine_tuning_irsa" {...role_name = "${module.eks.cluster_name}-llama-fine-tuning"role_policy_arns = {policy = "arn:aws:iam::aws:policy/AmazonS3FullAccess"}...resource "kubernetes_service_account_v1" "llama_fine_tuning_sa" {metadata {name = "llama-fine-tuning-sa"... - Run the following commands to create the ECR repository and S3 bucket. The S3 bucket’s name will be printed in
$ terraform init$ terraform plan$ terraform apply -auto-approve
- Run the
terraform outputcommand to list the ECR upload commands. Copy and paste those output commands into your terminal to push themy-llama-finetunedcontainer image$ terraform output -raw my_llama_finetuned_ecr_push_cmdsaws ecr get-login-password --region us-west-2 | docker login --username AWS --password-stdin 123456789012.dkr.ecr.us-west-2.amazonaws.com/my-llama-finetuneddocker tag my-llama-finetuned 123456789012.dkr.ecr.us-west-2.amazonaws.com/my-llama-finetuneddocker push 123456789012.dkr.ecr.us-west-2.amazonaws.com/my-llama-finetuned - Now that we’ve created the required infrastructure, let’s go ahead and deploy the fine-tuning job to the EKS cluster. To do so, we need to create a K8s Job manifest file that will run this as a K8s Job. Download the manifest from GitHub at https://github.com/PacktPublishing/Kubernetes-for-Generative-AI-Solutions/blob/main/ch5/llama-finetuning/llama-finetuning-job.yaml and replace the image, the Hugging Face token, and the name of the S3 bucket that contains the model assets you
apiVersion: batch/v1kind: Jobmetadata:name: my-llama-jobspec:...containers:- name: my-llama-job-containerimage: <<Replace your ECR image name here>>env:- name: MODEL_ASSETS_BUCKETvalue: "<<Replace your S3 bucket here>>"- name: HUGGING_FACE_HUB_TOKENvalue: "<<Replace your Hugging face token here>>"- name: TRAIN_DATASET_FILEvalue: "s3://kubernetes-for-genai-models/chapter5/loyalty_qa_train.jsonl"- name: EVAL_DATASET_FILEvalue: "s3://kubernetes-for-genai-models/chapter5/loyalty_qa_val.jsonl"...
- Run the following commands to run the job on the
$ kubectl apply -f llama-finetuning-job.yamljob.batch/my-llama-job is created
- A K8s Pod will be scheduled on a GPU node and start the fine-tuning process. You can monitor its process by tailing
$ kubectl logs -f job/my-llama-job
- Once fine-tuning is complete, the job will automatically upload the model assets to the S3 bucket, as shown in Figure 5*.5*:

Figure 5.5 – An Amazon S3 bucket that contains fine-tuned model assets
In this section, we began by modifying our Llama 3 fine-tuning script to make it container-ready. Then, we created a container image that includes the script and its dependent libraries, using the nvidia/cuda image from DockerHub as the base. Finally, we created an Amazon ECR repository that will store the container image and deploy it as a K8s job in the EKS cluster. In the next section, we will utilize the fine-tuned model assets to create an inference container image and deploy it in the EKS cluster.
Deploying the fine-tuned model on K8s
Section titled “Deploying the fine-tuned model on K8s”In this section, we will containerize the fine-tuned Llama 3 model using Python FastAPI and deploy the inference endpoint as a K8s deployment in the EKS cluster.
Let’s start by creating the inference container using the fine-tuned model assets stored in the S3 bucket. We will be using Python FastAPI (https://fastapi.tiangolo.com/) to expose the model as an HTTP API. FastAPI is a modern high-performance web framework for building APIs in Python:
- Create a directory
llama-finetuned-inf$ mkdir -p llama-finetuned-inf$ cd llama-finetuned-inf - Download the model assets from the S3 bucket to the local directory so that we can copy them to the
$ aws s3 sync s3://<<Your S3 Bucket Name>>/<<Your Model directory>> model-assets/
- Create a Dockerfile so that you can build an inference container that contains fine-tuned artifacts. Here, we are using
nvidia/cudaas the parent image, installing the necessary Python dependencies, and adding the fine-tuned model from themodel-assetsdirectory. The complete file is available at https://github.com/PacktPublishing/Kubernetes-for-Generative-AI-Solutions/blob/main/ch5/inference/Dockerfile:FROM nvidia/cuda:12.8.1-runtime-ubuntu24.04...RUN pip install torch transformers peft accelerate bitsandbytes sentencepiece fastapi uvicornCOPY model-assets /app/model-assetsCOPY main.py /app/main.pyCMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"] - Next, we will wrap the fine-tuned Llama 3 model into an API using Python FastAPI. It exposes a single API at
/generatethat accepts HTTP POST requests and returns a response after invoking the model. You can download the complete code from https://github.com/PacktPublishing/Kubernetes-for-Generative-AI-Solutions/blob/main/ch5/inference/main.py:...app = FastAPI()# Load tokenizer and modeltokenizer = AutoTokenizer.from_pretrained('./model-assets')# Define the quantization configuration for 8-bitbase_model_id = "meta-llama/Meta-Llama-3-8B"bnb_config = BitsAndBytesConfig(load_in_4bit=True,bnb_4bit_use_double_quant=True,bnb_4bit_quant_type="nf4",bnb_4bit_compute_dtype=torch.bfloat16)base_model = AutoModelForCausalLM.from_pretrained(base_model_id, torch_dtype=torch.float16, quantization_config=bnb_config, device_map='auto')# Load the Peft Model from pre-trained assetsmodel = PeftModel.from_pretrained(base_model, './model-assets')...@app.route('/generate')async def generate(request: Request):...inputs = tokenizer(prompt, return_tensors="pt").to(device)with torch.no_grad():outputs = model.generate(**inputs,max_new_tokens=100,...# Decode the response and return itresponse = tokenizer.decode(outputs[0], skip_special_tokens=True)return {"response": response} - Create the container image by running the
$ docker build -t my-llama-finetuned:inf .
- We will be reusing the ECR repository for this image. Alternatively, you can create a new repository using Terraform, as described in Chapter 3. Replace the account number and region values in the following commands before running them:
$ aws ecr get-login-password --region us-west-2 | docker login --username AWS --password-stdin 123456789012.dkr.ecr.us-west-2.amazonaws.com/my-llama-finetuned$ docker tag my-llama-finetuned:inf 123456789012.dkr.ecr.us-west-2.amazonaws.com/my-llama-finetuned:inf$ docker push 123456789012.dkr.ecr.us-west-2.amazonaws.com/my-llama-finetuned:inf
- Next, we will deploy the inference container in the EKS cluster as a K8s deployment. Download the
finetuned-inf-deploy.yamlK8s manifest from https://github.com/PacktPublishing/Kubernetes-for-Generative-AI-Solutions/blob/main/ch5/inference/finetuned-inf-deploy.yaml and replace the ECR image and Hugging FaceapiVersion: apps/v1kind: Deploymentmetadata:name: my-llama-finetuned-deploymentspec:...containers:- name: llama-finetuned-containerimage: <<Replace your ECR image here>>...env:- name: HUGGING_FACE_HUB_TOKENvalue: "<<Replace your Hugging face token here>>"... - Finally, deploy the model by running the
$ kubectl apply -f finetuned-inf-deploy.yamldeployment.apps/my-llama-finetuned-deployment createdservice/my-llama-finetuned-svc created
- It may take a few minutes for the K8s Pod to be ready since the image needs to be downloaded from ECR. Run the following command to verify
$ kubectl get all -l app.kubernetes.io/name=my-llama-finetunedNAME READY STATUS RESTARTS AGEpod/my-llama-finetuned-deployment-54c75f55fc-77tbc1/1 Running 0 116sNAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGEservice/my-llama-finetuned-svc ClusterIP 172.20.86.243 <none> 80/TCP 116s...
In this section, we took the model assets that were generated via the fine-tuning process and wrapped them with Python FastAPI to create an HTTP API. Then, we created a container, deployed it to the EKS cluster, and exposed it via the K8s ClusterIP service. This demonstrates how you can customize the behavior of general-purpose LLMs with your dataset and serve them using K8s. In the next section, we will explore how to deploy a RAG application on K8s.
Deploy a RAG application on K8s
Section titled “Deploy a RAG application on K8s”As explained in Chapter 4, RAG allows us to integrate external knowledge sources into the LLM response generation process, leading to more accurate and contextually relevant responses. By providing up-to-date and relevant information in the input, RAG also reduces errors such as hallucinations (https://www.ibm.com/topics/ai-hallucinations). In this section, we will explore how to deploy a RAG application to a K8s cluster. The following high-level steps are involved:
- Set up a vector database.
- Create a RAG application to query the vector store and call the LLM with both the input and contextual data.
- Deploy the RAG application on K8s.
- Load and index the data in the vector store.
We’ll begin by setting up a vector database, which is a specialized datastore that’s used for storing and querying high-dimensional vector embeddings. In RAG, such databases play an essential role by allowing a similarity search to be performed on the input request and relevant information to be retrieved. There are many open source and commercial vector databases available, such as Pinecone (https://www.pinecone.io/), Qdrant (https://qdrant.tech/), Chroma (https://www.trychroma.com/), and OpenSearch (https://opensearch.org/). Since many of these offerings are available as managed or SaaS models, one question naturally arises: when should we opt to run a self-hosted vector database in K8s? The main factors we should consider are as follows:
- Performance and latency
- Data sovereignty and compliance
- How customizable the configuration is
- Cost control
- How to avoid vendor lock-in
Follow these steps:
- For our setup, we are using a Qdrant vector database to store MyRetail’s sales catalog. Let’s download the
qdrant.tffile from our GitHub repository at https://github.com/PacktPublishing/Kubernetes-for-Generative-AI-Solutions/blob/main/ch5/qdrant.tf and runterraform applycommand. This will install the Qdrant vector database as a K8s StatefulSet (https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/) on the EKS cluster in theqdrantnamespace using a publicly available Helm chart....resource "helm_release" "qdrant" {name = "qdrant"repository = "https://qdrant.github.io/qdrant-helm"chart = "qdrant"namespace = "qdrant"create_namespace = true} - Create an Amazon ECR repository that will store the RAG application container image using Terraform. Append the following to the
ecr.tffile or you can download the complete code from GitHub at https://github.com/PacktPublishing/Kubernetes-for-Generative-AI-Solutions/blob/main/ch5/ecr.tf:resource "aws_ecr_repository" "rag-app" {name = "rag-app"} - Run the following commands to deploy the Qdrant Helm chart to the EKS cluster and verify its installation by running the relevant
kubectlcommand. The following output shows that aqdrantvector database Pod has been deployed and isRunning:$ terraform init$ terraform plan$ terraform apply -auto-approve$ kubectl get pods -n qdrantNAME READY STATUS RESTARTS AGEqdrant-0 1/1 Running 0 2m - Optionally, you can connect to Qdrant’s Web UI to interact with the vector database. Run the following command to connect to the Qdrant Web UI locally. Please refer to the Qdrant documentation at https://qdrant.tech/documentation/interfaces/web-ui/ to learn about its
$ kubectl port-forward service/qdrant 6333:6333 -n qdrant
- The next step is to develop the RAG application so that it can interact with the vector database and load and query data. We’ve created a sample application in Python at https://github.com/PacktPublishing/Kubernetes-for-Generative-AI-Solutions/blob/main/ch5/rag-app/main.py. Primarily, it does the
- Exposes a Python FastAPI endpoint called
/load_datathat takes an input filename and creates vector embeddings by calling the OpenAI API endpoint and stores the embeddings in the@app.post("/load_data")async def load_data(request: LoadDataModel):...response = requests.get(request.url)reader = csv.DictReader(file_content)...qdrant_store = QdrantVectorStore(embedding=OpenAIEmbeddings(),collection_name=collection_name,client=qdrant_client)qdrant_store.add_documents(docs)- Exposes a Python FastAPI endpoint called
/generatethat accepts a user prompt and an optional session ID. It creates the embedding for the input prompt using OpenAIEmbeddings and performs a similarity search against the Qdrant vector database to retrieve the relevant
@app.post("/generate")async def generate_answer(prompt_model: PromptModel):try:prompt = prompt_model.promptsession_id = prompt_model.session_id...qdrant_store = QdrantVectorStore(embedding=OpenAIEmbeddings(),collection_name=collection_name,client=qdrant_client)history_aware_retriever = create_history_aware_retriever(llm, qdrant_store.as_retriever(), contextualize_q_prompt)- Creates a conversational RAG application that remembers a user’s prior questions and answers and applies logic that can be incorporated into the current request. Here, we are building
rag_chainusinghistory_aware_retriever(https://python.langchain.com/api_reference/langchain/chains/langchain.chains.history_aware_retriever.create_history_aware_retriever.html) from the LangChain package (https://python.langchain.com/docs/introduction/). It takes an input prompt and past chat history and calls an LLM (OpenAI’s GPT-3.5 Turbo) to fetch the contextualized input. LangChain is a framework that’s designed to build applications powered by LLMs, enabling easy integration, management, and orchestration of multiple models and data pipelines for tasks such as creating chatbots, generating text, and more:
...rag_chain = create_retrieval_chain(history_aware_retriever, question_answer_chain)conversational_rag_chain = RunnableWithMessageHistory(rag_chain,get_session_history,input_messages_key="input",history_messages_key="chat_history",output_messages_key="answer")...- Invokes the RAG chain with the input and returns the response, along with the session ID, in
result = conversational_rag_chain.invoke({"input": prompt},config= {"configurable": {"session_id": session_id}},)["answer"]...return JSONResponse({"answer": result, "session_id": session_id}, status_code=200) - Exposes a Python FastAPI endpoint called
question_answer_chaincombines the retrieved context, the chat history, and the current user input to generate the final answer:
- Exposes a Python FastAPI endpoint called
Figure 5.6 – RAG application flow
- Create a directory
rag-app$ mkdir -p rag-app$ cd rag-app - Download the
main.pyandrequirements.txtfiles with our RAG application code and dependent libraries from https://github.com/PacktPublishing/Kubernetes-for-Generative-AI-Solutions/tree/main/ch5/rag-app and place them inrag-appdirectory. - The next step is to create a Dockerfile for this RAG application. We will start with a Python parent image, install the necessary FastAPI dependencies, add the Python application code, and run the uvicorn (https://www.uvicorn.org/) command to start a web server for the FastAPI application. The complete Dockerfile is available at https://github.com/PacktPublishing/Kubernetes-for-Generative-AI-Solutions/blob/main/ch5/rag-app/Dockerfile:
FROM python:slim...RUN pip install --no-cache-dir -r requirements.txtCOPY main.py /app...CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"]
- Build the container image and push it to the ECR repository. Replace the account number and region values before
$ docker build -t rag-app .$ aws ecr get-login-password --region us-west-2 | docker login --username AWS --password-stdin 123456789012.dkr.ecr.us-west-2.amazonaws.com/rag-app$ docker tag rag-app 123456789012.dkr.ecr.us-west-2.amazonaws.com/rag-app$ docker push 123456789012.dkr.ecr.us-west-2.amazonaws.com/rag-app
- Now that we have the container image, let’s deploy the RAG application on the EKS cluster. Download the K8s deployment manifest from https://github.com/PacktPublishing/Kubernetes-for-Generative-AI-Solutions/blob/main/ch5/rag-app/rag-deploy.yaml and replace
imageandOPENAI_API_KEYwith your own values. Follow the OpenAI documentation at https://platform.openai.com/docs/quickstart/create-and-export-an-api-key to learn how to generate an API key. The following manifest creates a K8s deployment for the RAG application with one replica and injects the OpenAI API key as an environment variable so that the application can use it to connect to the OpenAI API:apiVersion: apps/v1kind: Deploymentmetadata:name: rag-app-deployment...containers:- name: rag-app-containerimage: <<Replace your ECR image here>>...env:- name: OPENAI_API_KEYvalue: "<<Replace your OpenAI API Key here>>"... - After updating the manifest, you can run the following commands to deploy the RAG application to the cluster. This will create a K8s deployment called
rag-app-deplomentwith one replica that’s exposed via a ClusterIP service on port80. You can validate this by running the$ kubectl apply -f rag-deploy.yamldeployment.apps/rag-app-deployment createdservice/rag-app-service created$ kubectl get po,svc -l app.kubernetes.io/name=rag-appNAME READY STATUS RESTARTS AGEpod/rag-app-deployment-c4b4b49d4-wclwz1/1 Running 0 4m26sNAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGEservice/rag-app-service ClusterIP 172.20.41.161 <none> 80/TCP 4m26s - Finally, we must load MyRetail’s shopping catalog into the vector database; we’ve already created the necessary embeddings, exported a snapshot of the catalog collection, and created a K8s job that restores the data in the database. Download the
qdrant-restore-job.yamlfile from https://github.com/PacktPublishing/Kubernetes-for-Generative-AI-Solutions/blob/main/ch5/rag-app/qdrant-restore-job.yaml and run the following command to restore$ kubectl apply -f qdrant-restore-job.yamlbatch/job qdrant-restore-job created
In this section, we created a conversational RAG application using the LangChain framework, a Qdrant vector database, and OpenAI GenAI models. We containerized the application by exposing it as a Python FastAPI and deployed it to the EKS cluster. In addition, we created another example RAG application that utilizes Amazon Bedrock (https://aws.amazon.com/bedrock/) and Anthropic Claude (https://aws.amazon.com/bedrock/claude/) models instead of OpenAI. You can find it at https://github.com/PacktPublishing/Kubernetes-for-Generative-AI-Solutions/tree/main/ch5/bedrock-rag-app and choose either one based on your preference. In the next section, we’ll tie everything together using a Chatbot UI.
Deploying a chatbot on K8s
Section titled “Deploying a chatbot on K8s”So far, we’ve deployed a fine-tuned Llama 3 model that has been trained on the MyElite loyalty program’s FAQ and a conversational RAG application using sales catalog data. Now, we will build a Chatbot UI component that will expose both services to MyRetail customers.
We will be building the Chatbot UI using Gradio (https://www.gradio.app/), an open source Python package used to build demos or web applications for ML models, APIs, and more. You can refer to the QuickStart guide at https://www.gradio.app/guides/quickstart to learn more about the Gradio framework. Alternatively, you can explore using UI frameworks such as Streamlit (https://streamlit.io/), NiceGUI (https://nicegui.io/), Dash (https://github.com/plotly/dash), and Flask (https://flask.palletsprojects.com/en/stable/) to build chatbot interfaces.
For your convenience, we’ve already created a chatbot container and made it available publicly on DockerHub: https://hub.docker.com/repository/docker/k8s4genai/chatbot-ui/. The source code for this application is available on GitHub at https://github.com/PacktPublishing/Kubernetes-for-Generative-AI-Solutions/tree/main/ch5/chatbot for your reference.
Important note
We are creating a public-facing NLB for testing purposes. Feel free to restrict access to your IP address by updating the inbound rules of the NLB security group. Refer to the AWS NLB documentation at https://docs.aws.amazon.com/elasticloadbalancing/latest/network/load-balancer-security-groups.html for more details.
Let’s deploy the chatbot application on the EKS cluster and configure it with both the fine-tuning Llama 3 deployment and the RAG application:
- Download the Chatbot UI K8s deployment manifest from https://github.com/PacktPublishing/Kubernetes-for-Generative-AI-Solutions/blob/main/ch5/chatbot/chatbot-deploy.yaml and deploy it to the EKS cluster by running the following commands. This will create a K8s deployment with one replica of the Chatbot UI application and expose it to the public internet via AWS Network
$ kubectl apply -f chatbot-deploy.yamldeployment.apps/chatbot-ui-deployment createdservice/chatbot-ui-service created
- Fetch the AWS Network Load Balancer endpoint by running the
$ export NLB_URL=$(kubectl get svc chatbot-ui-service -o jsonpath='{.status.loadBalancer.ingress[0].hostname}')$ echo $NLB_URL
- Open the Chatbot UI by launching the Load Balancer URL in a web browser, as shown in Figure 5*.7*. Now, you can interact with the chatbot by selecting the Shopping assistant (RAG application) or the Loyalty Program assistant (Llama 3 fine-tuned model) and typing a question in the chatbox – for example, Please suggest walking shoes for a 60 year male in tabular format:

Figure 5.7 – Chatbot UI
- Once the results are displayed, go ahead and ask a follow-up question – for example, Can you sort the results in descending order by price. As shown in Figure 5*.8*, you will see that the results are sorted accordingly. Since the shopping assistant was developed with conversational RAG, it considers the user’s prior conversational history while answering the current prompt. In this example, we asked the chatbot to Please suggest walking shoes for a 60 year male in tabular format, followed by Can you sort the results in descending order by price. For the second query, the RAG application considered the user’s prior conversations and returned the sorted results:

Figure 5.8 – Chatbot UI results
- You can also toggle between the Shopping assistant and the Loyalty Program assistant by using the options under Choose an assistant and ask questions related to the loyalty program, as shown in Figure 5*.9*:

Figure 5.9 – Choosing the Loyalty Program assistant
In this section, we deployed a Chatbot UI application that had been developed with the Gradio Python package to an EKS cluster and exposed it via the K8s LoadBalancer service. This application is connected to both the RAG application and the fine-tuned Llama 3 model we developed in this chapter so that it can answer user queries about MyRetail’s MyElite loyalty program and shopping catalog.
Summary
Section titled “Summary”In this chapter, we covered how to fine-tune and deploy GenAI models in a K8s environment using Amazon EKS. We used a fictional company, MyRetail, as an example to highlight GenAI applications in e-commerce/retail business by creating personalized shopping experiences for our customers using GenAI models. This allowed us to automate responses for the company’s loyalty program and offer product recommendations.
We began by discussing the importance of experimentation in the overall GenAI project life cycle and deployed JupyterHub in EKS. JupyterHub enables centralized access to computational resources such as GPUs, making it more suitable for large-scale AI tasks. Then, we created a Llama 3 fine-tuning container image and deployed it to the EKS cluster. The fine-tuning job utilized training and validation datasets from Amazon S3 to fine-tune the Llama 3 model and exported the model assets to S3. We containerized the inference container using those model assets and deployed it to the EKS cluster as a K8s deployment.
This chapter also outlined how to deploy a RAG application that queries a vector database (Qdrant) to retrieve context-relevant information before calling the LLM to generate responses. This reduces hallucinations and improves response accuracy by incorporating external data. Finally, we deployed a Chatbot UI and connected it to both the fine-tuned Llama 3 model and the RAG application to enhance the shopping experience for MyRetail customers. In the next chapter, we will explore various autoscaling constructs provided by K8s and how we can leverage them to optimize GenAI workloads.
Get This Book's PDF Version and Exclusive Extras
|