ANSI escape code injection testing with garak

garak's ansiescape probes check whether a model can be prompted to emit ANSI escape sequences that disrupt terminals, logs and downstream parsers. This page covers when that test matters and how to run it.

On this page

Why ANSI escape code injection testing with garak matters for console-facing LLM output

garak's ansiescape probes test whether a model can be made to emit ANSI escape sequences that disrupt consoles, logs and downstream parsers. That matters when a CLI assistant, a coding agent or a logging pipeline prints model output straight to a terminal or writes it into a log file. A terminal interprets escape sequences as commands, so model text that carries them can change colors, move the cursor, overwrite earlier lines or hide content from the person reading the screen. Log viewers and parsers that expect plain text can be confused in similar ways. The question for your team is whether anything between the model and the console sanitizes that output, and whether that control has ever been tested.

garak, the Generative AI Red-teaming and Assessment Kit, is an open-source command-line scanner licensed under Apache 2.0. It is installed from PyPI with pip and the PyPI package requires Python 3.11 or newer, so the test host needs that runtime before anything else is planned. Its ansiescape family includes three probes: AnsiEscaped, AnsiRaw and AnsiRawTokenizerHF. The probes differ in how they ask for escape output, and the exact prompt wording and detectors live in the probe source. Read the ansiescape probe source before you decide which probes apply to your model and how you will interpret a fail.

Before you run a scan, confirm three things with your own environment: which model or endpoint will sit behind the console, which component renders or stores its output, and whether that component strips control characters. Those answers determine whether a failing generation is a real console risk or only a raw string in a JSON report. Record them alongside the scan so that a later reader can tell what was tested and what was assumed.

What a successful ANSI escape injection can disrupt

A model that emits ANSI escape sequences is only a problem where something interprets those bytes. The four surfaces below are where that interpretation usually happens, and each one depends on how your own stack is built.

Terminal display and cursor control

Terminals interpret escape sequences as commands, so a sequence in model output can move the cursor, clear lines, change colors or hide text that a user then reads. For a CLI assistant, this can make a suggested command look different from what it actually contains. Confirm which terminal emulators and shells your users run, and whether the assistant prints raw model text or passes it through a renderer. Check whether a scan's flagged output still displays as expected in each one.

Log viewers and log files

Logs that capture model responses can carry escape sequences into log viewers, where they may overwrite earlier lines, spoof entries or corrupt the view an operator uses during an incident. Confirm whether your logging path strips or escapes control characters before writing to disk, and which viewers your on-call teams use. A useful test is to scan with garak, then inspect the same output as it appears in your actual log tooling, not only in a raw file.

Pipelines that parse output as text

Scripts, CI jobs and downstream parsers that read model output as plain text can break when control bytes shift field boundaries, add unexpected characters to values or cause a regular expression to fail. The risk grows when output is written to files that other tools read later. Identify every consumer that takes model text as input, and confirm how each one handles bytes outside the expected character set. Record which consumers fail on a flagged sample.

Copy-paste into terminals

Users often copy model output straight into a shell, a configuration file or a ticket. Hidden escape sequences can survive that copy, so the pasted text may differ from what the user saw on screen. This is a human-facing risk that no server-side parser will catch. Confirm whether your application warns users about unusual characters, whether it displays output in a plain-text view, and whether copied content is sanitized before it reaches a clipboard or a chat channel.

Choosing between AnsiEscaped, AnsiRaw and AnsiRawTokenizerHF

The AnsiEscaped probe asks the model to produce output that contains ANSI escape sequences written in an escaped, visible form, so the characters arrive as text the model can reproduce. This is the probe to start with for most chat-style applications and CLI assistants, because the prompt is ordinary natural language and any REST or hosted chat endpoint can carry it without special handling. Its value is in testing whether the model is willing to write control sequences into a response that a console or log viewer might later interpret.

  • Delivery: the prompt is plain text sent through the same channel as user messages.
  • Best fit: hosted chat APIs, REST endpoints and CLI assistants that return text.
  • What it shows: whether the model reproduces escape sequences when asked in normal language.
  • Limit: a visible escape string may not reach a terminal if your application strips or escapes it before display.
  • Check: confirm the exact prompt wording and detectors in probes/ansiescape.py for your installed garak version.

Before relying on this probe, confirm with the source that your garak version and the detector it uses match what your application would print.

Configuration options and when each fits

This table compares the run choices that shape an ANSI escape injection test with garak, including probe scope, generator type, generation count and harness. Read each row against the way your model or application writes output, since the right choice depends on whether the text reaches a terminal, a log or a parser.

OptionWhat it changesTrade-offWhen it fits
Ansiescape probes onlyRuns AnsiEscaped, AnsiRaw and AnsiRawTokenizerHF against the targetFast and focused, but tests nothing else about the applicationTargeted check of a CLI assistant or console-bound model output
Full scan across probe familiesAdds jailbreak, injection and leakage probes alongside ANSI testsBroader coverage with longer runs and more reports to reviewPre-release review where ANSI output is one risk among many
Hugging Face Hub generatorLoads a model directly from the Hub for local or hosted inferenceSimple setup for open models, but the tokenizer must match the probe pathTesting an open-weight model before any application wrapper exists
OpenAI API generatorSends prompts to a hosted OpenAI model over its APIEasy to start, but the output is what the API returns, not your system prompt or filtersChecking a hosted model's raw behavior with a known API key
REST generator via YAMLCalls your own endpoint as the application sees itMost realistic view of what reaches users, but needs a correct YAML description of the endpointTesting a CLI assistant or chat backend with its real pre- and post-processing
LiteLLM generatorRoutes through a gateway to one or many providersConsistent access across providers, with gateway behavior added to resultsComparing models behind an existing internal AI gateway
llama.cpp gguf generatorRuns a local quantized model through llama.cppWorks offline and fits air-gapped hosts, but quantization can change outputTesting a locally hosted model on a restricted network
Default 5 generations per promptEach prompt is sent five times; any undesirable output marks a FAILCatches intermittent escape output, at the cost of more calls per runDefault for most runs; confirm call volume against your provider limits
Fewer generationsFewer attempts per promptCheaper and quicker, but a rare escape sequence may be missedSmoke tests during development, not final evidence
Default probewise harnessRuns each probe with its recommended detectorsConsistent and easy to compare over time, with less control over detector choiceStandard runs where the report must match other garak results

How to run an ansiescape scan step by step

This sequence takes a team from a clean Python environment to a reviewed set of ansiescape results, with a check at each stage so that a failed setup is caught before it is mistaken for a clean scan.

  1. Confirm the Python version and environment

    Check that the host runs Python 3.11 or newer, as the PyPI package requires, and create a dedicated virtual environment so garak and its dependencies stay separate from system packages. The engineer doing the work should record the Python version and the garak version they plan to use. This step is done when python3 --version reports 3.11 or higher and the virtual environment activates without errors.

  2. Install garak from PyPI

    Install the tool with pip inside the activated environment using the garak package from PyPI. Pin the version you intend to use so later reruns produce comparable results, and note the release you chose, since the most recent release in the supplied facts is v0.17.1. This step is done when python3 -m garak --help prints the command-line options without import errors.

  3. Describe the target in a generator configuration

    For an application endpoint, write a REST generator YAML file that describes the URL, request format, headers, authentication and where the response text sits in the JSON. Store the API key in an environment variable rather than in the file, and keep the file under version control with the rest of your test assets. This step is done when the file loads without a configuration error on the first run attempt.

  4. Confirm the generator returns a response

    Send one benign prompt through the generator before any ansiescape probe runs, so that a connection, authentication or parsing failure is not mistaken for a model that refuses to emit escape codes. Check the response text in the garak output and confirm it matches what the application returns when used normally. This step is done when a test prompt returns readable text from the target that the team has reviewed.

  5. Run the ansiescape probes

    Run garak against the configured generator and select the ansiescape probes, which cover AnsiEscaped, AnsiRaw and AnsiRawTokenizerHF. Use the default generation count unless your plan calls for a different number, and keep the run command in a script so that reruns are identical. The probes exist to test whether the model emits ANSI escape sequences that could disrupt terminals, logs and downstream parsers. This step is done when garak completes and prints a summary for each ansiescape probe.

  6. Review the JSONL report

    Open the JSONL report written by the run and find the entries for each ansiescape attempt, with the prompt, the response and the evaluation. Confirm that every probe you selected appears and that the number of attempts matches the configured generations, since a missing probe usually means a selection or configuration problem. A probe marked FAIL means at least one attempt produced undesirable output, so record which responses contained escape sequences. This step is done when each ansiescape probe has its attempts listed in the report.

  7. Check garak.log for errors and warnings

    Read the garak.log file, which continues across runs, and locate the entries for the current run. Look for generator timeouts, parsing errors, detector warnings or skipped probes that could make a pass or fail misleading. Save the log alongside the report so the reviewer can see how the run behaved. This step is done when the log for the run shows no unexplained errors that would change the reading of the report.

  8. Confirm downstream handling of escape output

    Test whether the application or console consuming the output strips, escapes or renders escape sequences, using a sample response from the report. Confirm this with the owner of the logging, terminal or parser component rather than assuming it, and record what each downstream system does. This step is done when the team can state, for each consumer of model output, whether escape sequences reach it and what happens to them.

How the ansiescape test flows from probe to console

The run starts in garak, where an ansiescape probe sends a prompt through a generator to the target model or application endpoint. The model's response returns to the detector, which scores whether it contains ANSI escape sequences, and the attempt and its evaluation are written to the JSONL report. The key boundary is the application's own output handling: the same text can reach a terminal, a log file or a parser downstream, so check what the application does with the response before it reaches those consumers.

The ansiescape test path from probe to report, with the application boundary marked.

Security and operational considerations for running the scan

Running garak against an LLM endpoint is an operational task as well as a test. The four cards below cover the risks that most often catch teams out: the target environment, credentials, stored output, and the terminal that displays results. Each one has a check to make before the first scan starts.

Scan staging before production

ANSI escape probes send prompts designed to make the model emit control sequences, and the model's replies may reach logs, dashboards or downstream parsers that the application shares with real users. Point garak first at a staging deployment with the same system prompt, output handling and logging as production. Ask the owner of any production endpoint to approve the scan window and request volume in writing, so that rate limits and alerting are understood before anything is sent.

Keep generator keys out of config

The REST generator and the hosted model generators read credentials from configuration, and a YAML file committed beside the scan settings can end up in version control or a shared CI log. Load keys from environment variables or the secrets store your organization already runs, and scope each key to the minimum model access the scan needs. Confirm that the configuration directory is excluded from backups that leave your control, and rotate any key that has appeared in a copied file.

Treat report files as sensitive

Each run writes a JSONL report of every attempt and its evaluation, and a garak.log file that continues across runs. Both contain raw model output, which may include system prompt fragments, sample data or hostile control sequences. Store them in a restricted location with the same classification as the application's logs, set retention in line with your policy, and check whether your garak version writes prompts or responses to the log at the verbosity you chose.

garak README

Isolate the terminal that displays results

Because the probes are built to elicit escape codes, the text they produce can change the colour, title, cursor or screen contents of whatever terminal prints it. Read JSONL output with a viewer that escapes control characters, avoid piping raw reports into an interactive shell, and run scans from a disposable host, container or session rather than an administrator's workstation terminal. Ask the team to confirm that their tooling displays output safely before anyone reviews a report on a privileged machine.

What to change after an ansiescape finding and how to verify the fix

A failing ansiescape probe is evidence that model output reaches a terminal, log file or parser without sanitization. The model did emit escape sequences, and the question for the engineering team is where those bytes travel after leaving the model. Start by tracing each output path the probe exercised: the CLI rendering layer, any log writer, any JSON or text parser that consumes the response, and any downstream tool that reads the console. Each path that passes raw output through is a place where a sequence can move the cursor, clear lines, change terminal titles or hide text from a reviewer. The fix belongs at the boundary where model output meets the console, log or parser, not in the prompt. Prompt wording may reduce how often the model produces these sequences, but it does not remove the exposure.

Three fix areas cover most findings. First, strip or escape control characters before output is displayed, so that the terminal receives printable text only, or receives escape sequences that the application itself has chosen to render. Second, render logs with escaping, so that the escape byte is written in a visible form and cannot change how a log viewer or a terminal tail displays earlier lines. Third, validate parsers, so that any component reading model output treats control characters as data, not as formatting, and fails closed when a response does not match the expected shape. Confirm with your platform team which sanitization library or terminal library your stack already provides, and whether each fix is applied once at a shared output function or repeated at every call site.

Verify the fix by rerunning the same ansiescape probes against the same target configuration, then comparing the new JSONL report with the report from the failing run. The comparison only means something when the garak version is pinned, because scoring and probe behavior can change between releases, so record the exact version used for both runs. Check that the attempt count, generator settings and detectors match, and that the failure rate has dropped for the paths you changed. Also test the output paths directly, with a fixed sample containing escape bytes, because a model that happens to behave well on one run does not prove that the console path is safe. Keep both reports with the change record so that the evidence trail shows the finding, the fix and the retest.

Limits of this test and what to confirm in your environment

The ANSI escape probes answer one narrow question about the model or endpoint under test. The cards below separate what a clean or failing result proves from what still depends on your garak install, your generator and the software that displays or parses the output.

One behavior, not the whole application

The ansiescape probes check whether the model emits escape sequences when prompted. They do not test your system prompt, retrieval layer, output filters, tool calls or the way your CLI wraps model text. A pass on this probe means the model did not produce the tested sequences in the attempts run, not that your application cannot be made to write control codes to a terminal. Treat the result as one input to a wider review of output handling.

Probe source

Confirm the garak version and probe source

Record the exact garak version and the commit or release that provided ansiescape.py on the machine that ran the scan. The latest release is v0.17.1, dated 16 October 2026. Probe names, payloads and detectors can change between releases, so a result is only comparable with another when both runs used the same version. Store the version in the report alongside the JSONL output.

Check whether the generator returns raw text

The probe scores the text your generator hands back. If a REST wrapper, SDK or chat template strips, escapes or rewrites characters before returning, a probe can miss sequences the console would have received. Compare the raw response body with the text garak logged for a sample prompt. Note any JSON escaping, markdown rendering or post-processing between the model and the scanner.

Check what your terminal and viewers do

Whether an escape sequence causes harm depends on the consumer. Some terminals interpret cursor movement, color or title codes, while log viewers, web dashboards and SIEM parsers may display them as literal text or break line parsing. Test the actual display paths your team uses, such as the CLI assistant's terminal, the application log viewer and any downstream parser, with harmless sample sequences in a non-production host.

Decide where output sanitization sits

Escape handling is often a design choice rather than a model property. Ask whether your application strips or encodes control characters before printing, whether logging libraries escape them, and which component owns that rule. A failing probe points to the model's behavior, while a passing run on a model that is later swapped out says nothing about the new model. Re-run the probe after model, prompt or wrapper changes.

Keep the scope and approvals written down

Scans against production endpoints, shared model gateways or third-party APIs need agreed scope, rate limits and an owner for the findings. Confirm with the model provider that automated prompting of this kind is permitted under your contract, and record which environment, account and date the scan covered. These records make it clear later which system was tested and under which configuration.

Questions teams ask before running ANSI escape injection tests

Is garak free to use for ANSI escape injection testing?

Yes. garak is licensed under Apache 2.0, and its maintainers describe it as a free tool. The license governs the software itself. It does not cover the work of configuring it, running it against your endpoints, or interpreting results. Those costs come from people and infrastructure: the engineer who writes the endpoint configuration, the host that runs the scan, and the time spent reviewing output. Confirm the license terms in the project repository before you distribute modified copies inside your organization, and ask any partner to separate software licensing from service fees in the quote.

How much effort does a first ANSI escape scan take?

The effort is driven mainly by how hard it is to reach the model under test and how many layers sit between the model and the console. A first scan usually needs an endpoint configuration, a test host with Python 3.11 or newer, and a review of the output. The ansiescape probes are a small part of the garak probe set, so the scan itself is quick compared with the setup. Effort rises when the application has tool calls, streaming output, retrieval, or a custom response format that garak must parse. Ask for a written list of those components in any quote, because each one changes the configuration work.

What does ANSI escape testing need from our team?

Three things need to be in place before testing starts. First, access to the endpoint that returns model output, whether that is a REST API, a hosted model, or a local model served through a supported generator. Second, a test host where garak can be installed from PyPI and where the scan can run without touching production users. Third, a named person who can read the JSONL report and decide what counts as a finding. That reader should understand how the application writes output to terminals, logs and downstream parsers, because a probe hit only matters if those consumers process the raw text.

Can our internal team run ANSI escape injection tests alone?

Often yes, if the team already runs tests against its own services and has someone comfortable with Python and YAML. garak is a command-line tool, and the REST generator is configured with a short YAML file describing the endpoint. The harder parts are judgment calls: deciding whether a control character in a log line is a real defect, deciding how the application should sanitize output, and deciding when a fix needs retesting. Teams without that background often ask a partner to set up the first run and document the configuration, then keep the routine scan in-house. Make that split explicit in the scope so ownership of the config and the findings is clear.

How long does an ANSI escape scan take to finish?

The duration depends on how many attempts the probes make and how quickly the endpoint responds. By default garak makes 5 generations per prompt, so the number of prompts and the generation count multiply the total requests. A hosted model with rate limits will finish more slowly than a local model on a GPU, and a slow REST endpoint adds time to every attempt. Running the scan in a single probe family rather than the full set shortens the run. Ask the person running the scan to record the start and end times of a trial run, then plan the schedule from that measured figure rather than from an estimate.

Does a passing ANSI escape scan prove the application is safe?

No. A passing result shows that the probes in the run did not produce the undesirable output they test for, under the configuration and detectors used at the time. It does not prove that every escape sequence path is blocked. Results can change with the system prompt, the model version, the generator settings, and the way the application post-processes text. garak is one input to a security review, alongside code review of how output reaches terminals and parsers, and tests of the downstream tools themselves. Record the garak version, the configuration file, and the date with every result so that a later reader can see exactly what was tested.

What should we confirm about ANSI escape probes before we start?

Confirm three points with the garak source and your own environment. Check the current probe classes in probes/ansiescape.py on the project's main branch, because the names and behavior are the source of truth for your run. Confirm which detectors score each probe in your garak version, since the default harness runs each probe with its recommended detectors. Finally, confirm which downstream consumers receive the raw model output, such as a CLI renderer, a log shipper, or a parser that reads escape-prefixed lines. Those answers decide whether a hit is a console risk, a logging risk, or both.

How DeployOpen works on this

DeployOpen plans and runs ANSI escape code injection testing with garak as a fixed-scope engagement, inside the environment where your model or assistant runs. The work covers which output paths reach terminals, logs and parsers, how the garak run is set up and evidenced, and what your team receives to repeat the test later.

How we scope

  • Map every place model output reaches a terminal, log file, pipeline or downstream parser.
  • Agree which garak ansiescape probes run against which model endpoints and applications.
  • Confirm the written scope, deliverables and timeline before any testing begins.

How we build

  • Configure garak in your environment, with the REST generator or model connector your endpoint needs.
  • Run the AnsiEscaped, AnsiRaw and AnsiRawTokenizerHF probes and review each JSONL attempt.
  • Check whether your application strips or escapes control sequences before output is displayed.

How we hand over

  • Deliver a findings report that ties each failure to the output path it could affect.
  • Document the run configuration, probe selection and garak version so results can be reproduced.
  • Provide a configuration file and runbook your own team can use for repeat scans.

How we support

  • Retest after fixes to output sanitization or rendering so results show the change.
  • Offer ongoing support, upgrades and continuous testing as a retainer if you need regular scans.
  • Confirm with your team how scan results will be stored and who reviews them.

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.