LLM Foundations for Adversarial AI
local graph
Chapter 13 — LLM Foundations for Adversarial AI
Section titled “Chapter 13 — LLM Foundations for Adversarial AI”In the previous chapter, we started looking at Generative AI and the profound challenges it brings in its ability to generate outputs that can be used adversarially.
Despite the different outputs, our first exploration of Generative AI still accepted inputs conventionally – that is, encoded images for GANs. In this chapter, we will look at large language models (LLMs) and their use of prompts, free-text inputs, mixing content, and instructions for the model. LLMs are a field of their own, with a very different development workflow. We will look at prompts in the context of the LLM revolution sparked by ChatGPT and the slight paradigm shift toward accessing external hosts via APIs rather than the model directly.
In this chapter, we will cover the following topics:
- A brief introduction to LLMs and their evolution
- Application development with LLMs, particularly public LLMs, using ChatGPT as our model with OpenAI’s API
- A hands-on introduction to LangChain to develop a FoodieAI sample bot for our examples.
- Bringing in your data with retrieval-augmented generation (RAG) and fine-tuning
- How LLMs and Generative AI redefine Adversarial AI attacks and mitigations
Let’s start with a quick introduction to LLMs.
A brief introduction to LLMs
Section titled “A brief introduction to LLMs”LLMs are a subset of artificial intelligence (AI) that are designed to process, understand, and generate human language. These models employ deep learning techniques and are trained on extensive text data to understand context, generate coherent text, and interact in human-like conversation. As mentioned in the previous chapter, LLMs resulted from the evolutionary journey of NLP in AI. This journey had some key milestones:
- Early stages of NLP: Initially, NLP models were rule-based, relying on manually crafted language rules. The advent of machine learning brought statistical models that learned from data. These models, however, were limited by their inability to understand language contextually.
- Breakthrough with Transformer models: The introduction of Transformer models in 2017 marked a significant evolution. As discussed in the previous chapter, using “attention mechanisms,” these models could focus on different parts of input text, enhancing tasks such as machine translation. Unlike previous models that processed words in isolation, Transformers consider the entire sequence, leading to more accurate context understanding.
- Bidirectional context understanding with BERT: Google’s BERT, introduced in 2018, was revolutionary for its bidirectional approach to understanding. Traditional models analyzed text in one direction (left to right or right to left), but BERT simultaneously processed text in both directions. This meant the model fully understood the context, improving performance in sentiment analysis, question answering, and language inference tasks. BERT was pre-trained on a large corpus of text and then fine-tuned for specific tasks, a significant shift from task-specific models.
- Combining encoder-decoder architectures with BART: Google’s BART combined the strengths of BERT’s encoder and the Transformer’s decoder, allowing it to excel in text generation tasks. Unlike BERT, which was primarily an encoder, BART’s architecture allowed for encoding (understanding text) and decoding (generating text), making it versatile for tasks such as summarization and translation. BART was trained with a novel approach borrowed from Stable Diffusion models, where the input text was corrupted in various ways (such as text shuffling), and the model was tasked with reconstructing the original text, enhancing its understanding and generation capabilities.
- GPT series and ChatGPT milestones with OpenAI’s GPT series: GPT-3 and its successors marked a leap in text generation capabilities. With 175 billion parameters, GPT-3’s ability to generate human-like text was unprecedented. Its successors, ChatGPT-3.5 and ChatGPT-4, improved understanding of context over longer conversations, making them more effective in interactive applications. GPT-3 and its successors utilized unsupervised learning on diverse internet text. They were designed to predict the next word in a sequence, honing their ability to generate coherent, authoritative-sounding, and contextually relevant text based on the given prompt. This is called autoregressive language modeling and it uses past sequence information to predict the next word in a response. That’s the essence of ChatGPT’s intelligence.
OpenAI coupled the models with a web-based chat app and APIs, triggering unprecedented adoption. In January 2023, 2 months after its launch, the app had 100 million active users and an estimated 13 million unique users per day. This is record user adoption, and it’s staggering when compared to other massively successful consumer applications; it took TikTok 9 months to reach the same number of active users, while it took Instagram 2.5 years to achieve the same milestone. This adoption also sparked competition with other sophisticated LLMs, notably Anthropic’s Claude, Google’s Gemini, and Meta’s Llama. The latter was leaked and eventually open sourced, leading to the emergence of many open source LLMs. We will cover these in the next chapter.
Because of their versatility, ChatGPT models sparked a widespread debate on how Generative AI could lead to artificial general intelligence (AGI) and safety concerns. An online letter in March 2023 asked for a 6-month pause on developing more advanced LLMs than ChatGPT-4. The letter was signed by thousands of individuals, including Elon Musk, Steve Wozniak, and Tristan Harris from the Center for Humane Technology. It was followed by a Statement on AI Risk by the Center of AI Safety, stating that “ mitigating the risk of extinction from AI should be a global priority alongside other societal-scale risks such as pandemics and nuclear war.” Notable AI scientists and industry executives, including Bill Gates and the CEOs of OpenAI, Anthropic, and Google Deepmind, signed the statement. A wave of debates and public initiatives culminated in the US Executive Order on AI and the Global AI Safety Summit hosted by the UK government. You can find out more about the debate on AI Safety at the following links:
- https://futureoflife.org/open-letter/pause-giant-ai-experiments/
- https://www.safe.ai/statement-on-ai-risk
- https://www.whitehouse.gov/briefing-room/presidential-actions/2023/10/30/executive-order-on-the-safe-secure-and-trustworthy-development-and-use-of-artificial-intelligence/
- https://www.gov.uk/government/publications/ai-safety-summit-2023-the-bletchley-declaration
Because of the sophistication of LLM output, safety and security are becoming even more intertwined. This will become evident when we start discussing adversarial inputs with prompt injections.
But first, let’s walk through the development of a simple ChatGPT app so that we understand threat mitigations with concrete examples.
Developing AI applications with LLMs
Section titled “Developing AI applications with LLMs”LLMs are complex, large-scale models, and are dominated by the ChatGPT models hosted by OpenAI. This has changed the paradigm of AI application development by shifting back to API-based access to an LLM and reducing machine learning development and deployment operations.
With LLMs, we reference these large models as foundational models. These are large-scale general-purpose models that have been pre-trained with vast amounts of web-scale data and are capable of thinking outside the box for a wide range of tasks. ChatGPT 3.5 and ChatGPT4 are well-known and popular foundational models hosted by OpenAI and are available for further training and fine-tuning via APIs. AI application developers interact with APIs without the burden (and flexibility) of MLOps. The following diagram summarizes a basic LLM application topology:

Figure 13.1 – Basic LLM application with the third-party model (for example, OpenAI)
Note
This is gradually changing with the emergence of open source LLMs. But for now, we will use the third-party model hosting topology to simplify our discussion. We will look at open source and self-hosted models in the next chapter.
For third-party models, API syntax will vary depending on the model provider. Still, unlike previous interactions with models in LLMs, we don’t have to pre-process, normalize, or encode data. Communication with the model – via the API – is done via prompts. These are natural language requests asking the model – like a chatbot – to perform a task, usually answering a question. An example prompt would be, “ Provide a recipe for a healthy meal.” Similarly, responses are in free-text format.
Behind the scenes, the tokenization of the prompt is translated into tokens. The model provider states the maximum number of tokens a request can contain. Like any other API, prompt queries and responses will be part of the API’s JSON. Initially, this was a single step, but increasing a conversational array of prompts and responses is part of the request. This is to help developers include conversational history so that the model can have a better context and provide relevant answers by referencing previous exchanges.
In addition to prompts and responses, developers can specify other attributes, such as temperature, which tells the model how creative (high temperature) or reproducible (low temperature) its response to a prompt should be.
The following section will demonstrate using OpenAI’s LLM API in a simple example.
Hello LLM with Python
Section titled “Hello LLM with Python”To create a basic chat LLM application, we will use the OpenAI ChatGPT APIs to send a response and get a request. We will use the chatCompletions API, which offers a multi-prompt array of messages to include conversation history.
You can find many examples of using the legacy single-prompt completions API. This has been designed for models, most of which were deprecated in January 2024. For more details, see https://platform.openai.com/docs/api-reference/completions.
To create a simple ChatGPT app, follow these steps:
- Create an account with OpenAI at https://platform.openai.com/signup.
- Log in to OpenAI.
- Navigate to API Keys and create a new key. Ensure you copy this somewhere secure because it will not be displayed again.
- Test the API by listing the models you have access to, using
curlto call themodelsThis should return a JSON response with a list of the models available to you. These models may not contain ChatGPT4 unless you have made at least one payment in the Billing section (under Settings) using pay-as-you-go credit.curl 'https://api.openai.com/v1/models' --header 'Authorization: Bearer <your API key>' - Create a Python environment and set dependencies by running the
Alternatively, you can run the following command:pip install --upgrade openaiThis command will use thepip install -r requirements.txt
requirements.txtfile containing the OpenAI dependency. - Create a simple Python script called
HelloLLM1.pythat sends a single prompt to ChatGPT:The code is explained in the comments, but we briefly set up the API key for authentication, the selected model, and the prompt. Then, we call the API and receive a collection of response objects, each containing a message attribute. This could vary from a single response to multiple ones. For more information, see the API documentation. In this simple example, we have the API key in the code. This is a significant security failure, and we should have the key outside the code. We can do this by implementing three different approaches:import openai as client# Set OpenAI API keyclient.api_key = '<your API Key – alternatively setup'># setup model and promptselected_model = "gpt-3.5-turbo"prompt = "Hello there. What's the date today?"# Call the API using the appropriate model for ChatGPT-4response = client.chat.completions.create(model=selected_model,messages = [{"role": "user", "content": f"{prompt}" }])# Print the responseprint(response.choices[0].message)- An OPEN_AI_KEY OS environment variable: This is the recommended development option for using the same key for multiple projects.
- A development environment file (.env): This is suitable for a single project or different keys per project. In this case, use
.gitignoreto exclude the environment. - A secure secrets management solution: This is recommended for production systems. Use solutions such as AWS Parameter Store or Secrets Manager, Azure’s Key Vault, or HashiCorp Vaults.
Note how we use
response.choices[0].message. This is because we’re using a more recent model that supports conversational messaging, and as a result, it will return a single choice. The multiple choices attribute is to accommodate earlier models and the legacy completions API. These lacked conversational context and produced a series of alternative responses to choose from.
- A development environment file (.env): This is suitable for a single project or different keys per project. In this case, use
- An OPEN_AI_KEY OS environment variable: This is the recommended development option for using the same key for multiple projects.
- Run the script in your IDE or on the command line with
python HelloLLM1.pyYou will see the following message:ChatCompletionMessage(content="Hello! Today's date is January 1st. How can I assist you further?", role='assistant', function_call=None, tool_calls=None)
Congratulations! You have just used a powerful LLM, admittedly, for a very simple task.
Although the API can hold an array of messages, we used it for a single prompt. Let’s expand this a bit and build a simple interactive Python-based text bot. But first, let’s rectify our approach to API key handling by storing it as an operating system environment variable by using export in the command line:
export OPENAI_APIKEY=<your API key>Now, remove client.api_key = '<your api Key '> and run it. It should work using the environment variable.
We will use the same approach for our simple chat box. The following code demonstrates how to use the message array in a loop and create a command-line Python chat box that considers conversational history. It runs the API call in a loop, adding previous requests and responses to the conversation_history array, which is then passed as the messages parameter of the API:
import openai as client# setup modelselected_model = "gpt-3.5-turbo"# Initialize an empty list to store conversation historyconversation_history = []while True: # Prompt the user for input user_input = input("You: ") # Check if the user wants to exit the loop if user_input.lower() == 'exit': break # Add user's message to the conversation history conversation_history.append({"role": "user", "content": user_input}) # Call the API using the appropriate model for ChatGPT response = client.chat.completions.create( model=selected_model, messages=conversation_history ) # Extract the model's response model_response = response.choices[0].message.content.strip() # Print the model's response print(«AI:», model_response) # Add the model's response to the conversation history conversation_history.append({"role": "system", "content": model_response})You can run it using your IDE or on the command line using python SimpleBot.py (or whatever name you saved the file with). It will give you a command-line interface, similar to the one displayed in the following screenshot:

Figure 13.2 – A simple Python chatbot using the OpenAI API
Congratulations, you have created your first chatbot using a powerful LLM! You can test its memory by asking questions that refer to the previous answer. The following screenshot demonstrates the sophistication of context understanding by the model:

Figure 13.3 – ChatGPT replying using previous responses
Note
OpenAI provides an interactive playground that allows you to test APIs interactively. See https://platform.openai.com/playground?mode=chat for more details.
This is by no means a thorough exploration of building LLM applications or OpenAI APIs. It is a taster to help us understand what an LLM application looks like so that we can start exploring how to exploit it. But first, let’s complete our exploration by looking at a version of our chat application that uses a popular vendor-independent framework, LangChain.
Hello LLM with LangChain
Section titled “Hello LLM with LangChain”A different approach to building LLMs’ less-vendor-specific strategy is to use LangChain.
An advanced LLM application framework that shields underlying APIs can orchestrate several models and offers a host of additional features, such as templates, plugins, and workflow chains that can be exposed as REST APIs. These features enhance and streamline the development of LLM applications, making LangChain extremely useful for more complex applications. There are other frameworks, such as Semantic Kernel from Microsoft, but at the time of writing, none have the versatility and popularity of LangChain. You can read more about LangChain at https://github.com/langchain-ai/langchain.
To use LangChain with OpenAI models, you must first install langchain and langchain-openai using pip:
pip install langchain langchain-openai --upgradeOnce that’s in place, save a Python file as LangChainBot.py and ensure it contains the following code. The main loop will be the same as before, but we will use LangChain’s ConversationChain, which takes care of the message’s history and context. The ConversationChain chain does that by using memory providers from its langchain.memory package. In this example, we’ll use ConversationBufferMemory, a simple buffer for storing the chat history:
import osimport openaifrom langchain_openai import ChatOpenAIfrom langchain.chains import ConversationChainfrom langchain.memory import ConversationBufferMemoryopenai.api_key = os.environ['OPENAI_API_KEY']selected_model = "gpt-3.5-turbo"chat = ChatOpenAI(model=selected_model)conversation = ConversationChain( llm=chat, memory=ConversationBufferMemory(), verbose=False,)# Start conversation loopwhile True: # Get user input user_input = input("You: ") # Check if user wants to end the conversation if user_input.lower() in ["exit", "quit", "bye"]: print(«AI: Goodbye!») break # Use the invoke method to process the input and generate a response response = conversation.invoke(user_input) # Output the bot's response print(f"AI: {response['response']}")Run the script; you will have the same functionality as before.
Note
LangChain offers a variety of memory providers, including a fixed-window buffer, a summary buffer, and a SQLite and Redis-backed buffer. For more information, see https://api.python.langchain.com/en/stable/langchain_api_reference.html#module-langchain.memory.
This example showed a basic use of LangChain to familiarize us with the framework and allow us to apply Adversarial AI input in context.
In the next section, we will look at how we can bring our own data with RAG and fine-tuning.
Bringing your own data
Section titled “Bringing your own data”So far, our exploration of LLMs has focused on a simple scenario where the app queries the model on the data the model was trained on. Models are updated periodically. Usually, we want to include more up-to-date information, such as web searches or data relevant to our solution domain. For example, if I am developing a legal application, I would want to include confidential customer legal documents and casework to make responses more relevant.
There are broadly two approaches to bringing in your own data:
- Fine-tuning, which applies transfer learning and further trains the model with our data. The following diagram summarizes fine-tuning:

Figure 13.4 – LLM fine-tuning
In the case of public LLMs such as ChatGPT, there are APIs to fine-tune a model. We will discuss fine-tuning in the next chapter, but needless to say, it brings its own risks that we have already mentioned when we talked about predictive AI, such as data poisoning, memorization, lack of access control on what is used in responses, and privacy attacks. We will delve into these more in the next chapter.
- RAG, which uses search to include relevant documents alongside the user prompt to enhance the response with relevant data. RAG has become immensely popular because it is simple, dynamic in its contextual data inclusion, and can apply access control. Unlike trained models, it provides traceability to sources and is known to reduce hallucination – that is, the property of LLMs to produce made-up information. RAG can be optimized with NLP tokenization of the data using embeddings, at which point these embeddings can be stored in vector databases. These can be used to speed up search and RAG.
The following diagram illustrates how RAG works:

Figure 13.5 – RAG in public LLMs
RAG has security risks, but traditional data provenance and governance with least-privilege access control can address them. We will explore these later in this chapter when we discuss mitigations. For now, we’re interested in how it becomes the mechanism to facilitate indirect prompt injections.
For instance, you could add the ability to search the web for recipes or other ingredient-related content using a search API such as Bing Search, and then add the results to the prompt.
For our FoodieAI example, we use a simple local file that demonstrates the concept. We will explore adding a local pricing document to respond to price and recipe cost questions.
In this example, we will use a local document with pricing information to allow FoodieAI to respond to cost queries. We’ll use local documents for simplicity, but you could use LangChain’s connectors to Google Drive and AWS S3 to retrieve the document. Alternatively, you could invoke an API-based search (for example, Lucene, Elastic Search, or Azure AI search services) to obtain the pricing information and pass it to the model. Searching would be more suitable than passing the entire supermarket’s pricing catalog! But let’s describe how we use the pricing document in our simple FoodieAI example:
- Create a CSV document with prices in a format of
item,unit,pricetuna tin,110g,£1.20eggs,6 pack,£1.85onions,1 item,£0.12
- Create a function to load
# Function to get pricing document from a local filedef get_pricing_document(file_path):with open(file_path, 'r') as file:pricing_document = file.read()return pricing_documentfilename= 'pricing.csv
- Change the conversational logic to load the document and append it to the prompt when the prompt contains the
costorprice# Use the invoke method to process the input and generate a response# Include pricing info if the query contains the key keywords cost or priceif "cost" in user_input.lower() or "price" in user_input.lower():pricing_info = get_pricing_document(filename)modified_input = user_input + " use the following pricing information. say N/A if the prices are not in the document" + pricing_inforesponse = conversation.invoke(modified_input)else:response = conversation.invoke(user_input)# Output the bot's responseprint(f"FoodieAI: {response['response']}") - Run and test the updated FoodieAI, asking for the cost. The following screenshot shows the results of our super-simple RAG version of FoodieAI:

Figure 13.6 – Using RAG to add pricing information
The preceding examples have been oversimplified to help you understand external content in the context of prompt injections. Typically, we would implement some restrictions on the sources we can trust. Additionally, we would tokenize external data into embeddings, and for documents, we would store embeddings as vectors in a vector database designed for this purpose. We have kept this example simple so that we can focus on indirect prompt injections. You can find a thorough treatment of RAG with an example of using a vector database, PDFs, web searches, and YouTube searches in the Samsung 2023 paper A Study on the Implementation of Generative AI Services Using an Enterprise Data-Based LLM Application Architecture. It’s written by Cheonsu Jeong and is available at https://arxiv.org/abs/2309.01105.
This completes our introduction to LLMs and their different workflows.
Based on our understanding, the next section will discuss how LLMs and Generative AI redefine Adversarial AI attacks.
How LLMs change Adversarial AI
Section titled “How LLMs change Adversarial AI”Generative AI fundamentally reshapes the landscape of adversarial scenarios in AI, departing from the traditional challenges associated with predictive AI models.
This shift is underpinned by several key factors intrinsic to Generative AI technologies, including LLMs and other advanced generative systems.
First, the architecture and scale of Generative AI models are distinct from those developed using traditional machine learning frameworks such as Keras, TensorFlow, or PyTorch. Generative models, especially those categorized as foundation models, are characterized by their immense size and complexity.
Training such models demands significant computational resources and expertise, making it a specialized domain. As a result, foundational models tend to be developed exclusively by organizations specializing in LLMs.
This exclusivity reduces the likelihood of direct attacks on the model training process itself as the barrier to entry is considerably high. However, the complexity and exclusivity of foundation models introduce alternative attack vectors that adversaries might exploit. Fine-tuning and RAG become more attractive targets for malicious actors. While still requiring technical know-how, these processes are more accessible compared to training a foundation model from scratch. They offer attackers the opportunity to introduce poisoned data or tampered models into the AI ecosystem with potentially less scrutiny than the foundational training process might attract.
Moreover, Generative AI diverges from predictive AI regarding input and output dynamics. Unlike predictive models, where outputs are more deterministic and structured, Generative AI can produce diverse outputs for a given input. This variability, combined with the less structured nature of inputs and outputs, complicates traditional adversarial approaches such as model extraction, inversion, and inference attacks. The vastness and variability of generative models pose unique challenges in ensuring data privacy and securing AI systems against such attacks.
As open source LLMs become increasingly prevalent, the potential for their misuse in supply-chain attacks grows. This accessibility creates new avenues for attackers to inject malicious code or data into widely used models, making supply-chain attacks more feasible and attractive for adversaries.
Summary
Section titled “Summary”In this chapter, we covered LLMs by providing an overview of their concepts but also a simple, practical example of building a simple LLM application using OpenAI APIs and the popular LLM application development framework LangChain.
LLMs typically use pre-trained models, and we looked at how we can bring our own data using RAG and fine-tuning.
Finally, we discussed how LLMs change Adversarial AI with their non-deterministic outputs, complexity, and size.
Armed with this knowledge, we will delve into a practical exploration of adversarial attacks on LLMs in the next three chapters. We will start by examining adversarial attacks on LLM input and outputs.