A Practical Guide to LLM Pitfalls with Open Source Software
2025-01-28
CS
PM
Finance
CS
PhD, UCL
PM
SF
Finance
Ex-Two Sigma
Figure 1: Samuel Colvin, Pydantic
From the perspective of software engineering, current AI systems are unmanageable, and as a consequence their use in serious contexts is irresponsible.
– Prof. Eerke Boiten, Head of School of Computer Science and Informatics at De Montfort University (DMU), Leicester, UK. source
LLMs are Generative, Non-Deterministic, and have Emergent Properties.
LLMs “Emerging Properties” Phenomenon. From: “Pathways Language Model (PaLM): Scaling to 540 Billion Parameters for Breakthrough Performance”
| Aspect | Traditional Software Products | LLM-Based Software Products |
|---|---|---|
| Capability Assessment | Validates specific functionality against requirements | May assess emergent properties like reasoning and creativity |
| Metrics and Measurement | Precisely defined and measurable metrics | Subjective qualities that resist straightforward quantification |
| Dataset Contamination | Uses carefully crafted test cases | Risk of memorized evaluation examples from training |
| Benchmark Evolution | Maintains stable test suites | Continuously evolving benchmarks as capabilities advance |
| Human Evaluation | Mostly automated validation | May require significant human oversight |
Figure 2: Conceptual overview of Multiple LLM-based applications evaluation.
description: Best model eval
prompts:
- file://prompt1.txt
- file://prompt2.txt
- file://prompt3.txt
providers:
- openai:gpt-3.5-turbo
defaultTest:
assert:
- type: llm-rubric
value: 'Evaluate the output based on how detailed it is. Grade it on a scale
of 0.0 to 1.0, where:
Score of 0.1: Not much detail.
Score of 0.5: Some detail.
Score of 1.0: Very detailed.
'
tests: file://tests.csvTakeaways
But what user needs drive the demand for LLM output constraints? A recent Google Research (M. X. Liu et al. 2024) study explored this question through a survey of 51 industry professionals who use LLMs in their work:
The text generation process follows a probabilistic approach. At each step, the model calculates the probability distribution over its entire vocabulary to determine the most likely next token:
\[\begin{equation} P(X) = P(x_1, x_2, \ldots, x_n) = \prod_{i=1}^n p(x_i|x_{<i}) \end{equation}\]
where, \(x_i\) represents the current token being generated, while \(x_{<i}\) encompasses all preceding tokens.
Figure 3: Text Generation Process: “Sampling”.
This controlled text generation process can be formalized as (Liang et al. 2024):
\[\begin{equation} P(X|\color{green}{C}) = P(x_1, x_2, \ldots, x_n|\color{green}{C}) = \prod_{i=1}^n p(x_i|x_{<i}, \color{green}{C}) \end{equation}\]
Here, \(\color{green}{C}\) represents the set of constraints or control conditions that shape the generated output.
Common constraints (\(C\)) include:
Format Constraints: Enforcing specific output formats like JSON, XML, or YAML ensures the generated content follows a well-defined structure that can be easily parsed and validated. Format constraints are essential for system integration and data exchange.
Multiple Choice Constraints: Restricting LLM outputs to a predefined set of options helps ensure valid responses and reduces the likelihood of unexpected or invalid outputs. This is particularly useful for classification tasks or when specific categorical responses are required.
Static Typing Constraints: Enforcing data type requirements (strings, integers, booleans, etc.) ensures outputs can be safely processed by downstream systems. Type constraints help prevent runtime errors and improve system reliability.
Length Constraints: Limiting the length of generated content is crucial for UI display, platform requirements (like Twitter’s character limit), and maintaining consistent user experience. Length constraints can be applied at the character, word, or token level.
Ensuring Output Consistency: Consistent output length and format are crucial for user experience and UI clarity. Constraints help maintain this consistency, avoiding overwhelming variability in generated text.
Figure 4: A common yet dangerous way to solve LLM Structural (un)Reliability.
Figure 5: A state machine approach to constrain LLM outputs.
from pydantic import BaseModel
from openai import OpenAI
class DocExtraction(BaseModel):
mentioned_entities: list[str]
mentioned_places: list[str]
def extract_from_doc(doc_text: str, prompt: str) -> DocExtraction:
client = OpenAI()
completion = client.beta.chat.completions.parse(
model="gpt-4o-mini",
messages=[
{
"role": "system",
"content": prompt
},
{"role": "user", "content": doc_filing_text}
],
response_format=DocExtraction
)
return completion.choices[0].message.parsedFigure 6: Tools for Structural Reliability
Other related tools worth mentioning include Guidance (Guidance AI 2024), Instructor (instructor.ai 2024), LM Format Enforcer (Noam Gat 2024), and NVIDIA’s Logits Processor Zoo (NVIDIA 2024a).
Figure 7: Impact of Output Constraints in Model Performance (Dottxt 2024)
Prompt engineering and the use of fine-tuned models can help control the output of LLMs.
However, when strong guarantees are needed, practitioners should consider techniques such as logit post-processing that provides formal guarantees for controlled output generation.
The impact of output constraints on model performance remains an open research question suggesting the need for evals to guide implementation decisions
Structured Data Extraction
Figure 8: Merrill Lynch’s CIO Capital Market Outlook released on December 16, 2024
Structured Data Extraction


Structured Data Extraction


Stale Data -> Hallucination
question = "Who's the Author of the Book Taming LLMs?"
response = client.chat.completions.parse(
model="gpt-4o-mini",
messages=[
{"role": "user", "content": question}
]
)
response.choices[0].message.contentResponse
The book "Taming LLMs" is authored by *G. Arulkumaran, H. M. B. P. D. Karthikeyan, and I. A. M. Almasri.* If you need more information about the book or its contents, feel free to ask!
RAG Helps Mitigate Hallucination, Lack of Temporal and Domain-Specific Knowledge
Figure 9: Simplified RAG Pipeline including a Vector Database with Embeddings and Indexing, a Retrieval System including re-ranking with LLM Augmented Generation via In-Context Learning.
Figure 10: Long-Context LLMs demonstrate superior performance while RAGs are more cost-effective (Z. Li et al. 2024).
Do we really need RAGs? The answer is conditional:
Takeaways
Without proper safeguards, LLMs can generate harmful content and respond to malicious prompts in dangerous ways (OpenAI et al. 2024; Hartvigsen et al. 2022). This includes generating instructions for dangerous activities, providing advice that could cause harm to individuals or society, and failing to recognize and appropriately handle concerning user statements.
Figure 11: Responses from Mistral (7B), Dolly v2 (12B), and Llama2 (13B) to a harmful user prompt (Vidgen, Scherrer, et al. 2024).
Governments and Institutions:
Private Sector:
Figure 16: Safety layers help protect against harmful content and behaviors.
| Risk | Prompt | Output |
|---|---|---|
| profanity | ✓ | ✓ |
| violence | ✓ | ✓ |
| jailbreaking | ✓ | |
| hallucination | ✓ |
There are several specialized commercial and open source tools that can be used to implement a filtering layer, which we can categorize into two types: Rules-Based and LLM-Based.
Rules-Based
LLM-Based
Moderation API
Fine-Tuned Open Source Models
Custom Models
LLM-Based
{
"harassment": false,
"harassment/threatening": false,
"hate": false,
"hate/threatening": false,
"illicit": true,
"illicit/violent": true,
"self-harm": false,
"self-harm/instructions": false,
"self-harm/intent": false,
"sexual": false,
"sexual/minors": false,
"violence": false,
"violence/graphic": false,
"harassment/threatening": false,
"hate/threatening": false,
"illicit/violent": true,
"self-harm/intent": false,
"self-harm/instructions": false,
"self-harm": false,
"sexual/minors": false,
"violence/graphic": false
}LLM-Based
LLM-Based: Custom
Figure 18: LLM-as-a-judge as safety filter.
LLM-Based: Custom
Figure 19: Example of a prompt engineered for an LLM-as-a-judge to be used as a safety filter for a chatbot used by middle school students
LLM-Based: Custom
Best practices:
Figure 20: Case Study - Safety Filter using OpenAI, Mistral, LLaMa Guard, and custom LLM-as-a-judge.
Figure 21: Validator Performance Metrics: True Positive Rate, False Positive Rate, and Inference Time.
Figure 22: Surprisingly (or not), when we actually translate the above prompts and carefully read them, one could deem them as unsafe at least for our case study where K-12 students and teachers are interacting with the model. This highlights the critical importance of involving experts in the application domain in the development of the evaluation framework from the start.
Figure 23: The release of ChatGPT 3.5 in late 2022 marked a significant moment in the history of artificial intelligence. Within just five days of its launch, the model attracted over a million users, and within two months, it became the fastest-growing consumer application in history with over 100 million monthly active users.
Figure 24: OpenAI Website Traffic Due To ChatGPT Growth.
Why did ChatGPT 3.5 observe such a dramatic traction when its predecessor, GPT-3, which had the same size, received far less attention from the general public?
Arguably, the answer lies not in raw capabilities, but in Human-Preference Alignment.
ChatGPT 2.0, for instance, works as a next-token prediction machine, i.e. text-completion model.
Prompt: “Explain the moon landing to a 6 year old in a short sentence”
“Explain the moon landing to a 6 year old in a short sentence. If the first moon is a good idea, you may get one of those little green dots out of the ground. Then the next day it will be a black line”
Modern LLMs, on the other hand, are not just text-completion models. They are instruction-following human preference-aligned models, i.e. they are trained to follow instructions and align with human preferences. Hence, incorporating human-like features.
Claude 3.5 Sonnet: Human Preference Alignment
Prompt: “Explain the moon landing to a 6 year old in a short sentence”
“A brave group of astronauts flew a special spaceship all the way to the moon, stepped out onto its dusty surface, and planted a flag there to show they made it!”
Figure 25: A simplified view of the alignment process: First, a powerful pre-trained base model is released, which is then fine-tuned using SFT to create an instruction-following version. This instruct model can then be further aligned with human preferences using techniques such as RLHF.
Figure 26: Instruction fine-tuning process for aligning language models with human preferences.
An aligned model can be fine-tuned directly from a base model or from an instruction-tuned model. For example,
Aligning a Language Model to a Policy:
Figure 27: Safety Plan Design Phases.
Figure 28: DPO dataset generation process showing how policy-aligned preferences are generated using LLMs.
| Instruction | Rejected Response | Chosen Response |
|---|---|---|
| user prompt | rejected assistant response | preferred assistant response |
LLM Instruction Generator: A language model that generates user prompts designed to test our policy boundaries. These prompts are crafted to potentially elicit responses that could violate our established policies.
Base LLM: Our unaligned base model that we aim to fine-tune. Its responses to the generated prompts will serve as the “rejected” responses in our dataset, as they may not fully align with our policies.
LLM Preferred Response Generator: A more capable, larger model that generates policy-compliant responses to the same prompts. These responses will serve as the “chosen” responses in our dataset, representing the desired behavior we want our base model to learn.
Figure 29: Example of a prompt and “rejected” response from base model.
Figure 30: Example of a prompt and “accepted” response from the aligned model.
Experimental Setup:
Figure 31: DPO Optimization by blending a policy-aligned synthetic dataset with the UltraFeedback binarized dataset from H4.
Figure 32: DPO training rewards showing convergence of policy alignment over training steps.
Figure 33: DPO fine-tuned model card on Hugging Face Hub
Figure 34: Vibe check - Base Model.
Figure 35: Vibe check - Aligned Model.
Figure 36: DPO evaluation metrics comparing base and aligned model responses.
The SafetyJudge class has two main components:
The scoring scale is:
| Model Type | Mean Score |
|---|---|
| Base Model | 0.108 |
| Aligned Model | 0.231 |
| Alignment Category | Base Model | Aligned Model |
|---|---|---|
| Not Aligned | 335 (99.1%) | 281 (83.1%) |
| Somewhat Aligned | 0 (0.0%) | 14 (4.1%) |
| Aligned | 3 (0.9%) | 43 (12.8%) |
Challenges
Opportunities
Models tell you merely what something is like, not what something is.
—Emanuel Derman
Thanks to Simon and the Code.org team for providing me with the opportunity to collaborate during my garden leave. The experience was invaluable and enriched my understanding of building safe and educational AI products.