Detecting prompt injection with LiteLLM

LiteLLM can screen requests for prompt injection at the gateway using similarity checks and an optional LLM check. This page explains what it covers, how to configure it, and where it falls short.

On this page

Detecting prompt injection with LiteLLM before requests reach a model

LiteLLM's prompt injection check screens incoming requests for instructions that try to override the model's original task, and a security team needs it once its shared self-hosted gateway accepts input from people, documents or tools it does not control. The check combines similarity matching against known attacks with an optional LLM call that judges whether a request looks like an injection attempt. It runs on /v1/chat/completions, /v1/messages, /v1/responses, /v1/completions, /v1/embeddings and /v1/moderations, and it covers tool outputs and text attachments as well as user messages. Treat it as one screening layer in front of the model, not as a complete defense: similarity rules only catch attacks that resemble known patterns, and an LLM judge can be wrong in both directions. Pair it with least-privilege tool permissions, output checks and logging, and document that boundary for your reviewers. Read the LiteLLM prompt injection documentation before you configure it, since the exact settings and endpoint behavior are defined there.

Decide first which traffic the check must cover. Tool outputs and retrieved documents are often the most dangerous input because they arrive from systems that a user or a third party can influence, so confirm that your deployment scans them and not only the latest user turn. Test each endpoint your callers actually use, because an embeddings or moderation route that is left unscreened becomes the path an attacker chooses. Next, decide what happens to files the gateway cannot scan. Audio, video and other non-text attachments are rejected with a 400 unless skip_unscannable_attachments is set, so the team must choose between blocking those requests and accepting an unscreened file, and record that choice with the owner who accepted the risk. Ask your implementation partner or LiteLLM contact to confirm how the LLM check is configured, which model it calls, and what that call adds to latency and provider cost, since those details are not fixed by the summary here.

Which endpoints and inputs the prompt injection check covers

The LiteLLM prompt injection check is not one switch that covers every request path. Its coverage spans several endpoint families and the content nested inside them, so each family and input type needs its own test before you rely on it. Confirm coverage against the LiteLLM version you deploy, since endpoint support changes between releases.

Chat completions endpoint

The check runs on /v1/chat/completions, the path most application traffic uses. Test it with system, user and assistant messages, including injected instructions placed in earlier turns of a long conversation. Confirm that the guardrail fires on the exact route your applications call, because a client that switches to another endpoint may bypass a guardrail configured only for chat.

Prompt injection docs

Messages endpoint

The check also runs on /v1/messages, the Anthropic-style path that many coding tools and agent clients call. Injection text can arrive in content blocks that are not plain strings, so test structured content as well as simple text. Verify that the same policy applies here as on chat completions, since teams often assume one guardrail covers both.

Responses and completions endpoints

The check covers /v1/responses and /v1/completions, the newer response API and the legacy text completion path. Clients still call the legacy path in some internal tools, so include it in your inventory. Send a test prompt through each endpoint and confirm that the scan result appears in logs for every one.

Embeddings and moderations endpoints

The check runs on /v1/embeddings and /v1/moderations, which matter for retrieval pipelines that embed untrusted documents. Injection text in a document can later steer a model when retrieved, so scanning at embedding time is a separate control from scanning chat input. Confirm which of these calls your deployment actually routes through the gateway.

Tool outputs in requests

Tool results returned to the model are a common injection path, because a web page, ticket or file read by an agent can carry hidden instructions. The LiteLLM documentation states that tool outputs are included in the scan. Test with a tool result that contains an instruction to ignore prior rules, and confirm the check flags it rather than passing it through.

Text attachments and unscannable files

Text attachments are scanned, but audio, video and other non-text files cannot be checked. Such requests are rejected with a 400 unless skip_unscannable_attachments is set. Decide per team whether to reject or allow these files, and test both paths so users see a clear error instead of an unexplained failure.

Similarity matching or an LLM call check: how each method works

Similarity matching compares incoming text against a set of known prompt injection attacks and flags requests that closely resemble them. The comparison runs inside the gateway and does not call a language model, so it adds no model provider call to the request path. Its strength is recognizing known phrasing and replayed attack patterns. Its weakness is that it only recognizes what it has seen, so reworded or newly invented instructions can pass through.

  • What it catches: known injection phrasings and close variants of them in chat, messages, responses, embeddings and tool output text.
  • What it misses: new attack wording, encoded or obfuscated instructions, and attacks split across several messages or attachments.
  • Cost and latency: the check itself should not generate a model provider charge, but its added processing time on your traffic must be measured in your own environment.
  • Decisions before enabling: which known-attack set is in use, how close a match must be before a request is blocked, and who reviews false positives.

Confirm the current matching behavior and attack set in the LiteLLM prompt injection documentation before you set blocking thresholds.

Configuration options and when each fits

This table compares the main configuration choices for LiteLLM prompt injection detection: endpoints, the optional LLM check, unscannable attachments and attachment scope by key, team or model. Read each row as a decision you make before rollout, and note that the exact settings and default values should be confirmed against the LiteLLM version you run.

OptionWhat it controlsWhen it fits
Endpoint coverageWhich routes run the similarity check: chat completions, messages, responses, completions, embeddings and moderationsEnable every route your applications call. A check on chat alone leaves embeddings and responses traffic unscreened.
Similarity matching onlyCompares inputs against known attack patterns without an extra model callGood first step for lower added latency and no additional model spend, but expect it to miss novel phrasing.
Optional LLM checkA second model call that judges whether the input is an injection attemptUse for higher-risk workflows such as agents reading web pages or email. Budget for the extra call's latency and cost, and confirm which model performs the judgment.
Skip unscannable attachments onLets requests with audio, video or non-text files pass without being scannedFits workloads where users legitimately send media and you accept that those files get no injection screening. Pair with logging so skipped requests are visible.
Skip unscannable attachments offRejects requests carrying unscannable audio, video or non-text files with a 400 errorFits regulated or high-risk workflows where unscreened files must not reach the model. Expect callers to need clear error handling.
Attachment and tool output scopeWhether text attachments and tool outputs are included in the scanInclude them when retrieved documents, tool results or uploaded text can carry instructions. Excluding them leaves indirect injection paths open.
Key-wide attachmentApplies the check to every virtual key and model on the gatewayFits a single standard baseline for all traffic. Confirm the check does not break low-risk internal tools that send unusual payloads.
Team or model scoped attachmentApplies the check only to selected teams, keys or modelsFits mixed estates, such as a public-facing assistant that needs strict screening while an internal batch job does not. Confirm the attachment method your LiteLLM version supports.

How to set up prompt injection detection on a LiteLLM gateway

This sequence takes a self-hosted LiteLLM gateway from a confirmed install to one where prompt injection checks run on every text-bearing endpoint in use. It ends with recorded test results for each endpoint, tool output and attachment type, plus a written policy for files the checks cannot read.

  1. Confirm LiteLLM version and database

    The platform team checks the running image tag against the LiteLLM releases page and confirms that the version sits on a release line the vendor still supports. They confirm PostgreSQL is the database, since virtual keys require it, and that Redis 7.0 or newer is in place if more than one proxy instance runs. Done when the proxy starts cleanly against PostgreSQL and a test virtual key can be created and used for a request.

  2. Add the prompt injection guardrail to config

    The team adds a prompt injection guardrail entry to the proxy configuration file that holds the model routes, and sets its mode to match the plan, such as blocking before the model call or logging only while thresholds are tuned. Confirm the exact key names and supported modes for the release in use against the prompt injection documentation before deploying. Done when the proxy reloads without configuration errors and the guardrail appears in the loaded configuration.

  3. Enable scanning on each endpoint

    Decide which of the six endpoints callers use: chat completions, messages, responses, completions, embeddings and moderations. Enable scanning on each one that receives untrusted text, and record any endpoint left out along with the reason and the owner. Confirm in the documentation whether scanning applies per endpoint by default or needs a setting. Done when one harmless request to each enabled endpoint returns a normal response and appears in logs with its guardrail result, if logging is on.

  4. Test benign and attack prompts per endpoint

    Build a fixed test set with benign prompts, known injection attempts such as instruction overrides and requests to reveal system prompts, and paraphrases of each attack. Run the full set against every enabled endpoint, recording the response, the block or pass decision and the added latency. Expect the similarity check and the optional LLM check to behave differently, and record what each one flags. Done when benign prompts pass on every endpoint, the known attacks are caught, and the results are saved with the config version.

  5. Verify tool outputs and attachment handling

    Send an injection string inside a tool result in a multi-turn request and confirm the check runs on that content, not only on the user message. Then send text attachments containing injected instructions, followed by audio, video and a non-text file. Requests carrying those unscannable files return a 400 unless skip_unscannable_attachments is set, so confirm callers receive a clear error message. Done when each test produces the outcome you expect and the results are recorded.

  6. Set the policy for unscannable files

    Set skip_unscannable_attachments only for file types where the data owner has accepted that unscanned content can pass to the model. Where unscanned content could carry sensitive data or instructions, keep the default rejection and tell callers which formats to convert to text before sending. Record the decision per file type in the change record. Done when a test with each file type produces the outcome written in that policy.

  7. Save results and retest on upgrades

    Store the test set, the results and the config version in the change record so the same prompts can be rerun after every LiteLLM upgrade. During the first monitoring period, review how many requests were blocked and whether benign users are hitting false positives, then adjust thresholds through the config and retest. Done when the full test set passes on the version planned for production and the monitoring owner has signed off on the blocked request review.

How a request passes the prompt injection check

The request starts at the client, which is outside the trust boundary. Everything it sends, including chat messages, tool outputs and text attachments, crosses into the LiteLLM gateway, where the prompt injection check runs before any model call. Confirm which endpoints your callers use, since the check covers chat, messages, responses, completions, embeddings and moderations. The skip_unscannable_attachments setting decides whether audio, video or other unscannable files are rejected with a 400 or passed on.

Request path through the gateway, with the attachment rejection branch.

Handling audio, video and files the gateway cannot scan

Requests that carry audio, video or other non-text files the gateway cannot read are rejected with a 400 error by default. That default is the safe starting point for prompt injection detection, because content the gateway cannot scan would otherwise reach the model unscreened. The setting that changes this behavior is skip_unscannable_attachments. When it is enabled, the gateway forwards those requests without inspecting the unscannable parts, so the injection checks only cover the text that was actually read. Decide which of these two outcomes your organization accepts before you enable any of the checks in production, and confirm the exact behavior for each endpoint and file type in the LiteLLM prompt injection documentation for the version you run.

The trade-off is between two kinds of harm. Rejecting every unscannable request protects against content the gateway never screened, but it breaks legitimate callers such as transcription workflows, meeting summarizers and document tools that send attachments as part of normal use. Skipping those attachments keeps those workflows running, but it means a crafted instruction hidden in a recording or file can pass to the model with no screening at the gateway. Many teams split the difference by routing attachment-heavy applications to a dedicated key or team with a narrower model list, so the exception applies only where the business case is clear. Ask application owners which file types their callers send and how often, since that count drives how many requests the exception will touch.

Whichever setting you choose, write it down as a policy: which file types are rejected, which are skipped, who approved the exception and when it is reviewed. Then log every skipped request with the key, team, model, endpoint and file type, so the security team can see what passed uninspected and spot abuse patterns. Test both paths before go-live by sending a sample audio file and a sample PDF through each endpoint in scope and confirming the expected 400 or the logged skip. Review the policy whenever you change LiteLLM versions or add a new endpoint, because coverage can differ between them and a change in either can silently widen the uninspected surface.

Security and operational risks of relying on prompt injection checks

Prompt injection checks reduce exposure but do not remove it. The cards below cover where detection fails, what false positives cost the teams using the gateway, and the operating routines that keep the checks useful after launch.

Attacks that evade pattern matching

Similarity matching compares incoming text with known attacks, so reworded, translated, encoded or split instructions can pass unflagged. Injected text also reaches the model through tool outputs and text attachments, where the original user never typed it. Test the check with paraphrased and multi-step samples drawn from your own use cases, and treat a clean result as a lower risk, not a guarantee. Keep tool permissions and data access limited so a missed injection has little to act on.

Prompt injection docs

False positives that block legitimate work

A security-minded phrase in a legitimate prompt, such as a question about prompt injection itself or a document about system configuration, can trigger a block. Each false positive stops a user or an automated workflow, and teams may route around the gateway if blocks are frequent. Measure block rates by team and endpoint during a pilot, and agree with the business owners which workflows need an exception path before enforcement starts.

Model dependency and cost of the LLM check

The optional LLM check sends each screened request to a second model, which adds latency, provider spend and a new point of failure. Ask which model performs the check, where it runs, and whether its prompts and outputs are logged. Confirm the behavior when that model is unavailable, because a fail-open setting lets traffic pass unchecked and a fail-closed setting stops it. Decide these settings per endpoint and per team, not once for the whole gateway.

Keeping attack patterns current

The similarity check is only as good as its library of known attacks, and new techniques appear faster than most teams update rules. Assign an owner for reviewing the pattern set, define how often it is refreshed, and record which version of the rules was active for each block. Pair the pattern updates with the LiteLLM upgrade routine, since guardrail behavior can change between releases. Retest after each change with a fixed set of attack and benign samples.

Logging and reviewing blocked requests

Blocked requests are the most useful signal the gateway produces, showing both attacks and friction for users. Configure logs to capture the key, team, model, endpoint, rule that fired and the decision, while limiting the storage of raw prompt content to what your privacy and retention rules allow. Set a recurring review with the security team to sort blocks into real attacks, false positives and tuning candidates, and feed the results back into the rules and exception list.

Defense in depth beyond the gateway

Prompt injection checks at the gateway sit alongside controls that limit damage when an injection succeeds. Restrict which tools each key can call, keep secrets out of prompts, and review what data each model route can reach. Document the residual risk for the system owner so the decision to accept it is explicit. Testing the full application, including its agents and retrieval sources, shows whether the gateway checks match the risks your deployment actually carries.

Questions teams ask before adding prompt injection detection

How much does prompt injection detection in LiteLLM cost to set up?

The cost has two parts: the one-time work of configuring, testing and tuning the checks, and the recurring spend on the LiteLLM LLM check model plus the people who review patterns over time. The similarity checks run inside the gateway, so their direct cost is mostly the compute of the proxy itself. The LLM check is optional, and each call to its model is billed by that provider, so its spend grows with request volume and the endpoints you enable it on. Ask any partner for a quote built from a written scope that lists the endpoints in use, the attachment policy, the test corpus size and the number of guardrail policies. DeployOpen does not publish a price list, and a quote follows from that written scope.

How long does a tested prompt injection setup take?

Duration depends on how many endpoints you cover, how many teams and keys need different policies, and how much tuning your false positive tolerance requires. Work usually runs in sequence: mapping traffic, configuring the checks, building a test corpus, running attack and benign tests, tuning thresholds and then documenting the result. No supplied timeline applies to every environment, so ask for a timeline in the written scope rather than relying on a generic figure. Confirm whether your gateway already runs in production, because a live proxy changes what testing has to avoid breaking.

What does our team need to provide before the work starts?

Three inputs drive most of the early work. The first is the list of endpoints in use, such as /v1/chat/completions, /v1/messages, /v1/responses, /v1/completions, /v1/embeddings and /v1/moderations, plus any tool output paths. The second is your attachment policy: which file types callers may send, and what should happen to audio, video or other files the gateway cannot scan. The third is a test corpus of known attack prompts and representative benign business prompts, with a named owner who can judge false positives. Teams also need a running LiteLLM instance and access to its configuration, so the checks can be tested against real routes.

How should we handle files the gateway cannot scan?

LiteLLM rejects requests that carry audio, video or other non-text files it cannot scan with a 400 error, unless the skip_unscannable_attachments setting is enabled. Enabling that setting lets those requests pass without being scanned, so it is a risk decision, not a convenience switch. Decide before go-live which file types your business needs, whether each should be blocked, allowed with a documented exception, or routed to a separate review process. Record that decision in the attachment policy and test it with sample files, because the choice affects both security posture and how often callers see errors.

Does the LLM check add much to ongoing spend?

It can. The LLM check sends content to a model for classification, so it adds a model call for each screened request on the endpoints where you enable it. Its spend is recurring and scales with traffic, prompt length and the model you choose. The similarity checks against known attacks do not call a model. A practical approach is to measure the similarity checks first, then decide whether the LLM check is worth its cost on high-risk routes. Ask any implementation partner to state which endpoints and policies will use the LLM check, and to show how its spend will appear in your cost reports.

Who maintains the detection rules after launch?

Detection is not finished at launch. Attack techniques change, your callers add new tools and attachment types, and the false positive rate shifts as usage grows. Someone must review blocked and flagged requests, update the test corpus, adjust thresholds and keep the gateway on a supported release line. This review is recurring work and is often the largest ongoing effort. Decide who owns it, how often it happens and what triggers a change, and include it in any support arrangement. Retainers for ongoing support, upgrades and continuous testing are available from DeployOpen if you prefer to outsource that review.

Can our in-house team set this up without a partner?

Often yes, if your team already operates the LiteLLM gateway, has security testing skills and can staff the tuning and review work. The configuration itself is not the hard part. The harder parts are building a representative test corpus, choosing thresholds that balance blocked legitimate requests against missed attacks, and documenting the evidence your security reviewers will ask for. Assess whether you have someone who can run adversarial tests against your own routes and maintain them. If not, a fixed-scope engagement can cover setup and testing, with a retainer for later review.

Does prompt injection detection guarantee that attacks are blocked?

No control of this kind blocks every attack, and any vendor or partner that promises otherwise should be questioned. Similarity matching finds attacks that resemble known patterns, and the LLM check judges intent, but novel or obfuscated injections can pass both. Treat detection as one layer alongside tool permissions, least-privilege credentials and output handling. Ask for testing evidence that shows which attack types were caught and missed in your environment, and plan how missed cases will be reported and retested.

How DeployOpen scopes and delivers prompt injection screening

DeployOpen plans, builds, tests and hands over prompt injection screening on a self-hosted LiteLLM gateway inside the client's own infrastructure. Work starts with a written scope that names the endpoints, traffic and attachment types in use, and the team that will operate the checks afterward.

How we scope

  • Inventory which endpoints, such as chat, messages, responses and embeddings, carry user or tool-output text into the gateway
  • Record which teams, keys and models need screening and which can run without it
  • Agree in writing how unscannable audio, video and binary attachments will be rejected or allowed

How we build

  • Configure the built-in prompt injection check, similarity matching and any optional LLM check in a staging gateway before production
  • Set up tool output and text attachment handling so injected instructions returned by tools are screened too
  • Document the configuration as code so changes go through review and can be rolled back

How we hand over

  • Test the screening with known attack samples and benign traffic, and record which requests were blocked, passed or logged
  • Deliver a written runbook covering alert triage, false positive review and the attachment policy
  • Walk the operations team through the configuration, logs and the steps to change a rule

How we support

  • Engagements are fixed-scope, with scope, deliverables and timelines agreed in writing before work starts
  • Ongoing support, upgrades and continuous testing are available as a retainer
  • Confirm the supported LiteLLM release line and planned upgrades with your team before the build starts

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.