Security

Security is a critical aspect to consider when integrating Large Language Models (LLMs) into your applications. In fact, LLM integrations are often completely prohibited due to security concerns. Yikes. Let’s talk about that.

This Lesson Will Cover
  • 🔒 Security blockers and risk assessment for LLM integrations
  • ✅ Best practices for input and output validation
  • 🔏 Privacy and data handling considerations
  • 🔑 API key management and security

LLM Blockers: Security, legal, and safety

Security, legal, and safety concerns can completely block LLM projects from moving forward. Here are some common blockers and how to address them:

Security Blockers

  • Data Leakage: LLMs could accidentally leak sensitive data through responses
  • Prompt Injection: Attackers may manipulate prompts to extract data or bypass restrictions

Legal Blockers

  • Data Privacy Laws: GDPR, HIPAA, and other regulations may prohibit sending certain data to external APIs
  • Liability Issues: Who’s responsible if the LLM provides harmful advice?

Safety Blockers

  • Harmful Content: LLMs can generate biased, toxic, or dangerous content
  • Reliability: Models may provide incorrect information in critical scenarios
  • Misuse: Bad actors could use LLMs for spam, fraud, or social engineering
Security, Legal and Safety Blockers Mind Map
LLM project blockers, as described above.

Quantifying LLM Integration Risk

Companies will be hesitant or unwilling to deploy LLMs until they can determine and mitigate risk.

To evaluate whether an LLM integration is viable:

  • Risk Assessment Matrix

    • Impact: How severe would a failure be?
    • Likelihood: How probable is the risk?
    • Controls: What mitigations are possible?
  • Data Classification

    • What type of data will the LLM process?
    • What are the regulatory requirements?
    • What internal policies apply?
  • Use Case Analysis

    • Is the use case mission-critical?
    • What’s the blast radius of potential failures?
    • Are there safer alternatives?
  • Cost-Benefit Analysis

    • Implementation costs vs. expected benefits
    • Cost of potential incidents
    • Cost of necessary security controls

Since it’s difficult to predict how LLMs will behave in production, it’s smart to start with low-risk use cases and gradually expand as you build confidence in your security controls and risk management processes.

LLM Safety Practices

Let’s talk about some specific areas of LLM integrations where we can program for safe use.

LLM Safety Practices Mind Map
LLM safety practices, as described in detail below.

Input Validation

Validating user input helps to prevent attacks like injection or exploitation of unexpected prompts. Improperly handled input can lead to harmful or unintended model behavior.

Example: Validation Factory

Here’s an example where we run the input prompt through various validations. This has been implemented in Python using a factory pattern.

import re

def validate_input(prompt):
    validators = [
        LengthValidator(max_length=1000),
        ProfanityValidator(),
        PersonalInfoValidator()
    ]

    for validator in validators:
        validator.validate(prompt)

    return prompt

class InputValidator:
    def validate(self, prompt):
        raise NotImplementedError()

class LengthValidator(InputValidator):
    def __init__(self, max_length):
        self.max_length = max_length

    def validate(self, prompt):
        if len(prompt) > self.max_length:
            raise ValueError(f"Input too long. Limit to {self.max_length} characters.")

class ProfanityValidator(InputValidator):
    def validate(self, prompt):
        profanity_list = ["badword1", "badword2", "badword3"]
        for word in profanity_list:
            if word.lower() in prompt.lower():
                raise ValueError("Profanity detected in input")


class PersonalInfoValidator(InputValidator):
    def validate(self, prompt):
        import re
        # Check for common PII patterns
        patterns = {
            'email': r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b',
            'phone': r'\b\d{3}[-.]?\d{3}[-.]?\d{4}\b',
            'ssn': r'\b\d{3}-?\d{2}-?\d{4}\b'
        }

        for pii_type, pattern in patterns.items():
            if re.search(pattern, prompt):
                raise ValueError(f"Personal information ({pii_type}) detected")

user_input = validate_input("Summarize this email: From <Adam.Smith@bankcompany.com> Hey team, this year's fiscal numbers are looking ...")

Notice how this example would raise a validation exception due to PII. Here’s the full traceback:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[10], line 49
     46             if re.search(pattern, prompt):
     47                 raise ValueError(f"Personal information ({pii_type}) detected")
---> 49 user_input = validate_input("Summarize this email: From <Adam.Smith@bankcompany.com> Hey team, this year's fiscal numbers are looking ...")

Cell In[10], line 11
      4 validators = [
      5     LengthValidator(max_length=1000),
      6     ProfanityValidator(),
      7     PersonalInfoValidator()
      8 ]
     10 for validator in validators:
---> 11     validator.validate(prompt)
     13 return prompt

Cell In[10], line 47
     45 for pii_type, pattern in patterns.items():
     46     if re.search(pattern, prompt):
---> 47         raise ValueError(f"Personal information ({pii_type}) detected")

ValueError: Personal information (email) detected
Example: OpenAI’s Moderation Endpoint

OpenAI provides a dedicated moderation endpoint to help detect harmful content. Here’s how to use it:

For all the following examples, I’ve turned on INFO level logging by running this in my jupyter notebook:

import logging
logging.basicConfig(level=logging.INFO)

This will allow us to see when requests are made to OpenAI.

from openai import OpenAI
client = OpenAI()

def check_moderation(text: str) -> bool:
    """
    Check if input text passes OpenAI's moderation filters.
    Returns True if content is safe, False otherwise.
    """
    try:
        response = client.moderations.create(input=text)
        result = response.results[0]
        print(f"Result of moderation API call: {result}")

        for k, v in result.categories.model_dump().items():
            print(k, v)

        if result.flagged:
            print("Content FLAGGED")
            return False
        print("Content OK")
        return True

    except Exception as e:
        print(f"Moderation check failed: {str(e)}")
        return False

# Example usage
user_input = "create and describe an xxx scene in high detail"
if check_moderation(user_input):
    # Process the input with your LLM
    response = client.chat.completions.create(
        model="gpt-4",
        messages=[{"role": "user", "content": user_input}]
    )
else:
    print("Content flagged as unsafe. Request blocked.")

Have a look at the prompt above. Do you think that will get flagged?

Well, it did not:

# Output:
# INFO:httpx:HTTP Request: POST https://api.openai.com/v1/moderations "HTTP/1.1 200 OK"
# Result of moderation API call: Moderation(categories=Categories(harassment=False, harassment_threatening=False, hate=False, hate_threatening=False, illicit=None, illicit_violent=None, self_harm=False, self_harm_instructions=False, self_harm_intent=False, sexual=False, sexual_minors=False, violence=False, violence_graphic=False, self-harm=False, sexual/minors=False, hate/threatening=False, violence/graphic=False, self-harm/intent=False, self-harm/instructions=False, harassment/threatening=False), category_applied_input_types=None, category_scores=CategoryScores(harassment=9.260319529857952e-06, harassment_threatening=4.106469987164019e-06, hate=1.01639761851402e-05, hate_threatening=1.1277479643467814e-06, illicit=None, illicit_violent=None, self_harm=4.279396671336144e-05, self_harm_instructions=3.7671172776754247e-06, self_harm_intent=7.718805136391893e-05, sexual=0.47585445642471313, sexual_minors=0.010079885832965374, violence=0.0015867097536101937, violence_graphic=0.00033277078182436526, self-harm=4.279396671336144e-05, sexual/minors=0.010079885832965374, hate/threatening=1.1277479643467814e-06, violence/graphic=0.00033277078182436526, self-harm/intent=7.718805136391893e-05, self-harm/instructions=3.7671172776754247e-06, harassment/threatening=4.106469987164019e-06), flagged=False)
# harassment False
# harassment_threatening False
# hate False
# hate_threatening False
# illicit None
# illicit_violent None
# self_harm False
# self_harm_instructions False
# self_harm_intent False
# sexual False
# sexual_minors False
# violence False
# violence_graphic False
# self-harm False
# sexual/minors False
# hate/threatening False
# violence/graphic False
# self-harm/intent False
# self-harm/instructions False
# harassment/threatening False
# Content OK
# INFO:httpx:HTTP Request: POST https://api.openai.com/v1/chat/completions "HTTP/1.1 200 OK"

Even though our prompt (to generate “an xxx scene” in high detail) didn’t get flagged by the content moderation API, on closer look we can see a high CategoryScore of sexual=0.47585445642471313 (compared to other categories which are quite close to 0).

We could have used this information to block the prompt from reaching the generative model.

In this case, we can see that our model refused the prompt request anyway (which is exactly what we expect from a good, safe model like GPT):

print(response.choices[0].message.content)
# Output: "Sorry, but I can't assist with that."

Output Validation

LLMs can produce biased or even toxic and harmful outputs.

As demonstrated in the previous example, foundation model providers like OpenAI and Anthropic go to great lengths to create safe models with careful restrictions on what type of content they can output.

Even so, it’s still possible that bad outputs could slip through the cracks.

There’s also the problem of hallucinations, where outputs are not factual.

These problems (particularly hallucinations) are dramatically exacerbated when using small models, e.g. Llama3.2 (1b, 3b parameter models), deepseek-r1 (1.5b, 7b, 14b, etc..)[1]

In order to mitigate these risks, our application can attempt to intercept bad outputs before returning them.

Example: Domain-specific Filtering

Consider this example where we censor financial advice:

import re

def filter_output(llm_response: str) -> str:
    """
    Filter LLM output for a financial advice application.
    Removes any specific investment recommendations or trading advice.
    """
    # List of patterns indicating specific financial advice
    investment_patterns = [
        r"\b(?:buy|sell|trade|allocate)\b.*?\b(?:stock|share|bond|crypto|bitcoin|ETH|SOL)\b",
        r"\$[0-9,]+(?:\.[0-9]{2})?(?:\s*(?:million|billion))?",
        r"\b(?:invest|put money in|purchase)\b.*?\b(?:[A-Z]{2,5}|[A-Z][a-z]+\s+Inc\.?)",
        r"(?:\d{1,3}%?\s*(?:return|gain|profit|upside|portfolio|allocation))",
        r"\b(?:guaranteed|promise|certain)\b.*?\b(?:return|profit|gain)"
    ]

    filtered_response = llm_response
    for pattern in investment_patterns:
        filtered_response = re.sub(
            pattern,
            "[SPECIFIC INVESTMENT ADVICE REMOVED]",
            filtered_response,
            flags=re.IGNORECASE
        )

    # Add disclaimer
    disclaimer = ("\n\nDisclaimer: This is general information only. "
                 "Consult a licensed financial advisor for specific advice.")

    return filtered_response + disclaimer

We could use this on LLM outputs as follows:

from openai import OpenAI
client = OpenAI()

llm_response = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[
        {"role": "user", "content": "What % of my portfolio should I allocate to SOL and ETH?"}
    ]
).choices[0].message.content

filtered = filter_output(llm_response)
print(filtered)

Which returned the following for me:

INFO:httpx:HTTP Request: POST https://api.openai.com/v1/chat/completions "HTTP/1.1 200 OK"
Determining how much of your portfolio to [SPECIFIC INVESTMENT ADVICE REMOVED]) and Ethereum (ETH) depends on various factors, including your risk tolerance, investment goals, and the overall diversification strategy of your portfolio. Here are some considerations to help you make that decision:

...

5. **Recommendation**: A common approach for investors who are bullish on crypto but want to maintain diversification might be to [SPECIFIC INVESTMENT ADVICE REMOVED] potentially getting a larger share due to its established position and broader use case. For instance, you might [SPECIFIC INVESTMENT ADVICE REMOVED] allocation to SOL and 90% to ETH if you believe ETH has a more promising future.

Ultimately, it’s important to do your own research and consider consulting a financial advisor to tailor a strategy that fits your individual situation.

Disclaimer: This is general information only. Consult a licensed financial advisor for specific advice.

Our regex above would need some work, for example we can see some very specific investing advice here: you might [SPECIFIC INVESTMENT ADVICE REMOVED] allocation to SOL and 90% to ETH. Ooops.

This particular task is likely best solved with prompt engineering. We could even pass the output through a second generative model to double check out work.

Example: Output Format Validation

Another consideration for output validation is ensuring that the response matches your expected format. Here’s an example that validates JSON output:

import json
from typing import Dict, Optional

def validate_json_output(llm_response: str) -> Dict:
    """
    Validates that LLM output is properly formatted JSON and contains required fields.
    Raises ValueError if validation fails.
    """
    try:
        # Attempt to parse JSON
        parsed = json.loads(llm_response)

        # Define required fields and their types
        required_fields = {
            'summary': str,
            'sentiment': str,
            'keywords': list
        }

        # Check all required fields exist and are correct type
        for field, expected_type in required_fields.items():
            if field not in parsed:
                raise ValueError(f"Missing required field: {field}")
            if not isinstance(parsed[field], expected_type):
                raise ValueError(f"Field {field} has wrong type. Expected {expected_type}")

        return parsed

    except json.JSONDecodeError:
        raise ValueError("Response is not valid JSON")

# Example usage
llm_response = '''
{
    "summary": "A review of Designing Data-Intensive Applications by Martin Kleppmann",
    "sentiment": 0.8,
    "keywords": ["great", "recommended", "high quality"]
}
'''

try:
    validated_output = validate_json_output(llm_response)
    print("Validation passed:", validated_output)
except ValueError as e:
    print("Validation failed:", str(e))

This example will fail due to the sentiment value, which should be a string:

Validation failed: Field sentiment has wrong type. Expected <class 'str'>

Amazingly, OpenAI has support for Structured Outputs[2], which guarantee JSON outputs with fixed schemas:

Structured Outputs is a feature that ensures the model will always generate responses that adhere to your supplied JSON Schema, so you don’t need to worry about the model omitting a required key, or hallucinating an invalid enum value.

Other models do not have this feature yet, to my knowledge. However, many models besides GPT provide mostly reliable JSON output nowadays.

Privacy and Data Handling

Handling sensitive data responsibly ensures user trust and compliance with regulations such as GDPR and CCPA.

General considerations include:

  • Minimize Data Retention: Avoid storing sensitive data unless absolutely necessary.
  • Anonymize Data: Strip identifiable information from input and output.
  • Use Encryption: Encrypt data in transit (e.g., HTTPS) and at rest (e.g., encrypted databases).
  • Understand API Data Policies: Review your provider’s data usage policies.

LLMs and Sensitive Data

Many organizations face significant challenges when considering LLM integrations through API vendors like OpenAI and Anthropic, since sending sensitive data to external APIs presents substantial security and compliance risks:

  • Organizations lose direct control over data handling and processing.
  • Intellectual property could be exposed through API interactions.
  • Data sent to these services may be stored and used for model training.
  • Compliance with regulations like GDPR or HIPAA becomes more complex.

For these reasons, enterprises may opt for privately hosted models. Solutions like deploying open-source models or using specialized vendors that offer on-premises deployments provide greater control over data security. This approach ensures sensitive information never leaves the organization’s infrastructure.

PII Safeguards

Example: Sanitizing Numeric Data

We’ve already seen an example of guarding against Personally Identifiable Information (PII) in prompts, but here’s another one. In this example, we sanitize numeric data that might represent sensitive information like account numbers, social security numbers, or financial figures:

import re

def sanitize_numeric_data(text: str) -> str:
    """
    Anonymizes various types of numeric data that might be sensitive.
    """
    # Replace sequences of digits
    patterns = {
        r'\b\d{16}\b': '[CREDIT_CARD]',
        r'\b\d{9}\b': '[SSN]',
        r'\b\d{10}\b': '[PHONE]',
        r'\$\s*\d+(?:,\d{3})*(?:\.\d{2})?': '[AMOUNT]',
        r'\b\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}\b': '[CARD_NUMBER]',
        r'(?:USD|EUR|GBP)\s*\d+(?:,\d{3})*(?:\.\d{2})?\b': '[CURRENCY_AMOUNT]',
        r'\b\d{5}(?:-\d{4})?\b': '[ZIP_CODE]'
    }

    sanitized = text
    for pattern, replacement in patterns.items():
        sanitized = re.sub(pattern, replacement, sanitized)

    return sanitized

# Example usage
sensitive_text = """
The customer's card 4532015112830366 has a balance of $12,532.16
Their SSN is 123456789 and they live in 90210
Please transfer EUR 1,250.00 to account 1234-5678-9012-3456
"""

safe_text = sanitize_numeric_data(sensitive_text)
print(safe_text)

This results in the following output:

The customer's card [CREDIT_CARD] has a balance of [AMOUNT]
Their SSN is [SSN] and they live in [ZIP_CODE]
Please transfer [CURRENCY_AMOUNT] to account [CARD_NUMBER]

API Key Management

This one is super standard. Apps have secrets, don’t show them to the world.

Best Practices for API Key Management

  • Keep Keys Secret: Never hard-code keys into source code or share them publicly. Use environment variables instead.

    Example: Using Environment Variables

    import os
    
    if not os.getenv("OPENAI_API_KEY"):
        raise ValueError("Env variable OPENAI_API_KEY not set")
    
  • Use Role-Based Access Control (RBAC): Limit key permissions to specific roles and purposes. For instance:

    • Use one key for production.
    • Use another for development or testing.
  • Monitor and Rotate Keys: Regularly check for unusual activity and rotate keys periodically to reduce risks.

  • Restrict IP Addresses: Providers may allow you to restrict API key usage to specific IP ranges.

Conclusion

Every aspect of software development has a deep world of security and privacy considerations to worry about. But generative AI takes it to a whole new level.

In terms of when to worry, hopefully, most of your concerns are front-loaded. It’s better to worry early than late! This is true both within the scope of the project and the scope of a day - it’s hard to sleep when you’re brainstorming the vulnerabilities of your LLM deployment.

Key Takeaways

🔒 Security, legal, and safety concerns can block LLM integrations.

✅ Input validation prevents prompt injection and data leakage.

🛑 Output validation protects against harmful content.

🔐 Privacy requires data anonymization and encryption.

🔑 API keys must be secured using environment variables.

🚀 Start with low-risk use cases and expand gradually.

🛠️ Consider using dedicated validation tools for content moderation.

Next: Monitoring

With this, we’ve completed the LLM section of the AI Deployment topic group. You’re now equipped with the knowledge to integrate, deploy, and secure LLMs in real-world applications! Or, at least, enough to get started.

But in order to run a production app effectively, we need to have visibility to see if it’s working, how it’s being used, and when it fails. That’s why the next section is all about monitoring.

Footnotes


  1. For a helpful list of models by size, check out the Ollama model library. If you want to go deeper into the world of open-source LLMs then you could explore and run all sorts of models with Replicate. ↩︎

  2. Read more about structure outputs and explore to use them in the OpenAI platform. ↩︎

Comments (0)

No comments yet.