Scanning a Python application directly with garak's function generator

garak's function generator lets you call a Python function as the target, so your application's own pre- and post-processing is tested without an HTTP endpoint. This page covers when that fits, how it is set up, and what to confirm.

On this page

Why scan a Python application directly with garak's function generator

Scan a Python application directly with garak's function generator when your LLM behavior depends on code that runs before and after the model call, and you do not want to expose a test HTTP endpoint just to run a scan. The function generator calls a Python function you specify as the generator, so garak sends each probe prompt into your application's own pipeline and receives whatever that pipeline returns. According to the garak source, the generator is designed to be used programmatically rather than from the command line, and it comes in Single and Multiple variants. That design matters for application teams because the prompt rewriting, retrieval, policy checks, output filtering and response formatting that shape the final answer all run inside the function under test, not in a proxy or a separate service that only approximates them.

The REST generator reaches a model or application over HTTP. It is configured with a short YAML file describing the endpoint, and it suits any REST endpoint that returns plaintext or JSON. The function generator skips that step. Your team keeps the application code in its own process, avoids standing up a listener, and avoids putting a test route on a network path that should stay closed. Before you commit to this approach, confirm which variant fits your call pattern, since the Single and Multiple variants differ in how prompts reach your function, and check the exact configuration keys in the garak user guide at docs.garak.ai. garak is licensed under Apache 2.0 and is installed from PyPI with pip. The PyPI package requires Python 3.11 or newer, so confirm your application's runtime meets that requirement before planning the test environment.

Function generator options and when each fits

This table compares the Single and Multiple function generator variants and the run choices that surround them, such as the function signature, how responses come back and how generations, detectors and harness are set. Use it to match the variant to the shape of your application before you write any code, and confirm exact parameter names in the source and user guide.

OptionSingle variantMultiple variantWhen to choose it
Function call shapeOne prompt in, one response out per callSeveral prompts or conversation turns passed in one callSingle fits stateless request handlers; Multiple fits apps that take a batch or a message list
Return valueA single string or object the generator reads backA list of candidate outputs, one per generationConfirm in generators/function.py how returned values map to garak's attempt records
Application pre-processingRuns inside the function, so filters and prompt templates are testedSame, applied to each item in the batchChoose the variant whose call path includes the guardrail or template you want exercised
Generations per promptSet through the run configuration, applied per callMay change how many outputs one call returns, so counts can differConfirm the generations setting against the user guide at docs.garak.ai before comparing runs
Detectors and harnessChosen by the default probewise harness or by configSame harness, but check that detectors read each returned outputKeep the default harness for a first run, then tune detectors once outputs look right
Error handlingExceptions inside the function surface as failed attemptsA failure in one item may affect the whole batch resultDecide whether an exception should stop the scan or be recorded as a finding
Setup for programmatic useImport the function and pass it to the generator by referenceSame import pattern, with a list-shaped contractBoth are used from Python rather than the CLI, so plan a small driver script

How the function generator fits into a garak run

The function generator changes what garak calls, not how a run is organized. garak still selects probes, sends each prompt to the target, runs the detectors attached to each probe, and writes the results. The difference is that the target is a Python function you point garak at, so the application's own pre-processing and post-processing run inside that call. A prompt goes in as a string, your code applies its input handling, calls the model or chain, applies output handling, and returns text. The probe prompt is only tested end to end if the function does everything the production path does before returning. Each attempt then gets evaluated by detectors, and the outcome is written to the JSONL report and to the garak.log debugging file that continues across runs.

The default probewise harness still applies. Each probe runs with its recommended detectors, and by default garak makes 5 generations per prompt, marking a probe as FAIL when any attempt produces undesirable output. That means one probe prompt becomes up to five calls into your application code, and the function has no way to opt out of that repetition. Scan time therefore scales with the number of probes, the number of prompts each probe sends, and the time your function takes per call, including any model latency, retrieval, or external checks your pre- and post-processing make. Confirm with your team how long one call takes under realistic load, and whether the function has side effects such as writing logs, creating records or consuming a paid API quota, since every attempt repeats them. Test against a non-production data set where possible.

Request flow from garak probes to the Python application and back

The run starts with the probes, which supply attack prompts to the harness. The harness passes each prompt to the function generator, which calls the application function in the same Python process. Inside the application code, pre-processing, the model call and post-processing run before the text returns to garak. The harness then sends each response to the detectors, which write every attempt and its result to the JSONL report, while garak.log records run events. Check that your function returns plain text the detectors can evaluate, and that the application code sits inside a boundary your team reviews.

Probe-to-function flow, with the application code as its own boundary.

Setting up a function generator scan step by step

This sequence takes a Python application from a clean install to a first verified scan through its own function, then widens coverage in stages. Each step ends with a check so the team knows the scan ran and produced usable evidence.

  1. Create an isolated environment and install garak

    Create a virtual environment on a Python version of 3.11 or newer, activate it, and install garak from PyPI with pip install garak. Run the install in the same environment your application uses, or one that matches its dependency versions, so the function imports the same libraries it does in production. Confirm the install by running python -m garak --help and checking that the command lists its options. The step is done when the help output appears without import errors.

  2. Write the target function with a stable signature

    Write a Python function that accepts a prompt string and returns the response string your application would send to a user, including its own pre-processing and post-processing steps. Keep the signature fixed, with one input and one output, and keep any session state, database handles and credentials inside the module rather than in arguments that change between calls. Test the function directly from a short script by passing one sample prompt and printing the result. The step is done when the function returns a string for a benign prompt without raising an error.

  3. Wire the function into the function generator

    Point the function generator at your function's module path and function name, following the configuration in garak's generators/function.py source, which describes the Single and Multiple variants. Choose the variant that matches how your function is called, and use the programmatic interface, since the generator is designed for use from Python rather than the command line. Confirm the wiring by sending one prompt through the generator and checking that the returned text matches what your function printed in the previous step. The step is done when the generator's output equals the function's output for the same input.

  4. Run a small probe set first

    Select a single probe family that matches your application's exposure, such as prompt injection or data leakage, and run it through the function generator with the default five generations per prompt. A small first run keeps the number of calls low, which makes it easier to spot problems in the wiring, the probe choice or your function's error handling. Watch the console for exceptions raised from inside your function, since these usually point to a signature or state problem. The step is done when the run completes and prints a pass or fail summary for the probe.

  5. Confirm the JSONL report and garak.log

    Open the JSONL report that the run writes, and check that it contains one record for each attempt with the prompt, your function's response and the detector evaluation. Then open garak.log and confirm it has entries from this run appended to the earlier content, since the log continues across runs. If the report contains responses that differ from what your function returns when called directly, stop and fix the generator wiring before scanning further. The step is done when you can trace one attempt from prompt to response to evaluation.

  6. Widen probe selection in stages

    Add probe families one group at a time, keeping the same environment and target function so results stay comparable between runs. After each addition, repeat the report check from the previous step and note any new exceptions or timeouts. Ask your security and application owners which probe families reflect the risks they care about, and record the selection in a configuration file so the next run uses the same settings. The step is done when the expanded run completes, the report covers every selected probe and the selection is saved for repeat runs.

Security considerations when calling application code directly

Calling application code from garak runs your functions inside the scanner process, so the scanner inherits whatever those functions can reach. The cards below cover the places where that exposure appears and the control to put in place for each one before the first scan.

Secrets loaded into the scanner

Application modules often read API keys, database passwords and signing keys from environment variables or a settings file at import time. Once garak imports the module, those values sit in the same process that writes reports and logs. Use a test-only credential set for the scan, load it from a dedicated environment file, and confirm that the function never reads production secrets when garak imports it.

Production data reachable from the function

A function that wraps a retrieval step or a customer lookup can query live systems as soon as a probe sends a prompt. A prompt built to extract data may succeed through your own code path, not only through the model. Point database and API clients at a staging instance, use read-only roles, and list every outbound connection the function can open before the scan starts.

Sensitive output in logs and reports

garak writes a JSONL report of every attempt and keeps a garak.log file across runs. If the function returns customer records, account details or internal system text, those strings land in both files and may be copied into tickets or CI artifacts. Redact or synthesize sensitive values in the test data, restrict file permissions on the report directory, and set a retention rule for scan output.

Staging copy drift

A scan against a staging copy only tests what staging contains. Configuration, feature flags, model versions and retrieval indexes can differ from production, so a clean result may not hold for the deployed system. Record the version of the code and configuration used for each run, and confirm with the owners of the staging environment which differences matter for the findings you plan to report.

Side effects from tool calls

Application functions often send email, create tickets, write files or call payment APIs. A probe that manipulates the function into taking an action will trigger that action for real unless the connector is stubbed. Replace outbound writes with recording stubs, and review each function for code paths that change state before running it under garak.

Scanner host access and ownership

The machine running garak needs the application's dependencies and often its network access, which makes it a privileged host. Decide who owns the scan environment, restrict who can edit the function module that garak loads, and keep the host separate from build runners that hold deployment credentials. Confirm this boundary with your security team before scheduling recurring scans.

When to test through HTTP instead of the function generator

The function generator is the right choice when you want to test what your Python code does to a prompt before it reaches the model and what it does to the model's answer before it reaches the user. It calls your function directly, so the scan exercises your application logic and nothing outside it. That is the point, but it also means the scan says nothing about the network path, the authentication check, the API gateway, the reverse proxy, the container image or the deployment configuration that a real user passes through. If a guardrail is enforced by a gateway rule rather than by your function, a function-level scan will not see it fail.

An HTTP scan through the REST generator covers the layers the function generator skips, but only if the scan actually runs through them. Pointing garak at an internal service address that bypasses the gateway tests a different system from the one customers use. Before choosing HTTP, confirm with your platform team which URL external traffic reaches, which headers or tokens the gateway requires, whether rate limits or content filters sit in front of the model, and whether the staging environment matches production closely enough for the results to carry over. The REST generator's configuration is a short YAML file describing the endpoint, so the work is mostly in getting the endpoint and credentials right, and in keeping secrets out of the file.

A deployed endpoint needs its own scan even when the function generator scan passes, because the two scans answer different questions. A practical pattern is to run the function generator scan in development against the same probe set on every change to pre- or post-processing code, then run an HTTP scan against each deployed environment on a schedule or before a release. Compare the two reports only when the probe set, generations and detectors match, and record the garak version in both, since scores can shift between releases. Ask your team to decide in advance who reviews a failure found by one method but not the other, because that disagreement usually points to a layer, such as the gateway or deployment, that needs its own fix.

Limits to confirm before you rely on a function scan

The function generator is convenient because it skips the HTTP layer, but it also moves the scan into your Python process. The cards below list the behaviors to confirm in your own environment before you treat a function scan as evidence of how the application behaves.

Single and Multiple behavior

Confirm exactly how the Single and Multiple variants call your function, how many times each prompt is sent, and what return types garak accepts. Check whether a return value that is not a plain string is converted, rejected or passed through unchanged. Run a small probe against a function that returns a known string, then inspect the JSONL report to see what garak recorded as the output.

Function generator source

Importability from the scanner

Confirm whether the function must be importable from the environment where garak runs, and how the module path is resolved. A function that depends on application settings, environment variables or a package installed only in the service image may load in a shell but fail inside the scan process. Test the import in the same virtual environment and user account that will run the scan.

Concurrency and thread safety

Confirm whether garak calls your function concurrently and whether your application code tolerates that. Shared clients, connection pools, global caches and session state can produce answers that depend on call order, which makes failures hard to reproduce. Ask whether a scan can be set to run one call at a time, and record that setting alongside the report.

Errors and exceptions in reports

Confirm how a function that raises an exception appears in the report. Decide whether a failed call counts as a pass, an error or a missing attempt, because each choice changes the failure rate you publish. Feed the function a deliberately invalid input and check the garak.log file and the JSONL report to see where the exception is recorded.

Version pinning against the release

Confirm that the garak version in your scanner environment matches the release you pin and document. The supplied release is v0.17.1, released 16 October 2026, so check the installed version with the package tooling before each scan, not only at setup. Record the version in every report so a later rerun can be compared against the same generator behavior.

garak releases

Scope of the evidence

Confirm what a function scan does not exercise, such as the HTTP layer, authentication middleware, rate limits and the deployed model configuration. A clean result describes the function as called in the scanner process, not the production service. Write that boundary into the scan record so reviewers do not read a function scan as proof of the deployed endpoint.

Questions teams ask before scanning a Python application with garak

How much effort does a first garak scan of a Python application take?

The effort depends mostly on how the application is built, not on garak itself. A first scan needs a Python function that accepts a prompt and returns the response the application would show a user, plus an environment where the application's dependencies, model connections and data sources can be loaded. The main drivers are:

  • How many layers sit between the prompt and the output, such as query rewriting, retrieval, tool calls, filters and formatting.
  • How many dependencies the application needs, and whether they install cleanly on the scanning host.
  • Whether the function reaches live databases, internal APIs or customer data, which requires test data and access approvals before any probe runs.

A simple wrapper around a single model call is a short task. An application with retrieval, agents and filters is a longer one, because the team must confirm the wrapper calls the same code path production uses. Ask any partner to state which of these drivers they assumed in the quote.

Can an in-house engineering team run a function scan without outside help?

Yes, if the team has a Python engineer who knows the application and someone who can own the scan results. garak is a command-line tool installed from PyPI with pip, and the PyPI package requires Python 3.11 or newer, so the tooling itself is straightforward. The harder parts are judgment calls: which probes match the application's real exposure, which detector outputs count as failures for the business, and how to avoid testing against production data. Teams without prior LLM security experience often benefit from an outside review of probe selection and of the results before they reach a risk committee. DeployOpen's security testing and AI security review services can cover that step if the team wants it, scoped in writing.

What does the team need to provide before a function scan starts?

The team needs three things. First, a callable entry point: a Python function that takes the prompt as input and returns the application's final output, so the scan exercises pre- and post-processing. Second, a staging environment that mirrors production configuration, with test credentials and test data, so probes cannot leak or alter real records. Third, scope decisions made in advance: which probe families apply, which data the application may touch, and who approves the findings. garak's function generator is designed to be used programmatically rather than from the CLI, with Single and Multiple variants, so the team should decide which variant matches how the application handles concurrent requests. Without these decisions, the scan produces numbers nobody can act on.

How long does a garak scan run, and what makes it longer?

Scan time is set by the number of probe attempts multiplied by the time each application call takes. garak makes 5 generations per prompt by default, so the generation count alone multiplies the work for every probe. The main drivers are:

  • The number of probes and the detectors that run against each output.
  • The generation count, which the team can change in configuration.
  • The latency of the model and of every downstream service the application calls during one request.

Because the function generator runs the application's own code, slow retrieval or tool calls add time to every attempt. Ask for a duration estimate based on a timed dry run of a few prompts through the real function, not on a generic figure. The quote should state the probe set and generation count it assumes.

What does it cost to run garak against a Python application?

The garak tool is free. The maintainers describe it as a free tool, and it is licensed under Apache 2.0. Running a scan still has costs, and they sit elsewhere. Recurring costs include the model or endpoint calls the application makes during each attempt, which may be billed per token by a hosted provider, and the compute used to run the application and the scan. One-time costs include engineering time to build the entry point, prepare test data and review results, and any external services used for that work. Before you approve a budget, ask the provider to separate engineering effort, scan infrastructure, model usage and any ongoing retest work so you can see which lines recur.

When should a team bring in an implementation partner for this work?

Bring in a partner when the scan has to produce evidence that others will rely on, or when internal capacity cannot cover the work. Typical triggers include a customer security review that asks for test results, an application that calls regulated data or internal tools, a need for scheduled rescans in your own CI pipeline, or a tight deadline with no one who has run LLM security tests before. DeployOpen works on fixed-scope engagements, with scope, deliverables and timelines agreed in writing before work starts, and it offers retainers for ongoing testing. DeployOpen does not issue audit reports or certifications, so independent auditors remain responsible for any formal attestation. Ask a partner to show how the scope covers your entry point, data handling and retest plan.

Does a function scan test the same behavior as an HTTP endpoint scan?

Not exactly, and the difference matters for scope. A function scan calls the Python code directly, so it tests the application's pre-processing, prompt construction, filters and post-processing without needing a network endpoint. An HTTP scan through the REST generator tests what a client can reach over the network, including authentication, gateways and transport. Each approach misses something the other covers. Teams often run the function scan first to find problems in the application logic, then run an endpoint scan to confirm the deployed path behaves the same way. Ask the partner or your own team to document which layers each scan exercises, so the report does not overstate coverage.

How DeployOpen scopes and delivers a function generator scan

DeployOpen starts with a written scope agreed before any work begins. For a function generator scan, the scope names the Python function that garak will call, the application code on each side of it, the probes and detectors in play, the data the function may touch, and who on the client side approves test traffic. The first working session is a review of the application's pre-processing (input normalization, prompt assembly, retrieval, policy checks) and post-processing (output filtering, redaction, formatting, tool dispatch). Those steps decide what garak actually tests, so the review fixes the boundary of the scan before any probe runs.

With the boundary agreed, DeployOpen builds a function generator wrapper for the target. The wrapper imports the real application code, supplies any configuration the function needs, and keeps credentials for model providers and downstream services in the client's own secret store, not in a garak config file. Scans are staged: a short run with a small probe set to confirm the wrapper returns the expected text, then broader runs covering the agreed categories. Each stage produces the JSONL report and garak.log described in the main guide, and findings are mapped to the code path that produced them. Fixes are made in the client's repository or agreed with the client's engineers, and a retest confirms each one.

DeployOpen runs security testing for AI systems, including applications built on language models. It does not issue audit reports, attestations or certifications. Where a client needs evidence for an assessment, DeployOpen supplies the scan records, scope document and fix history, and the client's auditor decides what they support. Ask any provider for the written scope, the list of deliverables and the retest terms before agreeing on a quote.

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.