When a custom garak generator is the right fix for an in-house endpoint
Your team's model or gateway sits behind a protocol that garak's built-in generators and the REST generator cannot call, so the first decision is whether a custom generator is really needed. garak is built from plugins in five categories: probes, detectors, evaluators, generators and harnesses. A generator is the class that sends each prompt to the target and returns the output, and the detectors and evaluators judge what comes back. Everything else in a scan stays the same whichever generator you use, so the work is confined to the code that talks to your endpoint.
Start with the REST generator. It connects to any REST endpoint that returns plaintext or JSON and is configured with a short YAML file, so a plain HTTP endpoint with a bearer token usually needs no code at all. Write a custom generator when the transport is not plain request and response over HTTP, such as a proprietary binary protocol, a vendor SDK that owns the connection, a session handshake that must be negotiated before each call, or a WebSocket flow with ordering rules the REST generator cannot express. Also consider a custom generator when the endpoint needs request signing, short-lived tokens refreshed mid-scan, or per-call logic the YAML file cannot hold. If the only gap is a field name or a header, change the configuration first.
Confirm before you start that your environment meets the basics. garak is licensed under Apache 2.0, is installed from PyPI with pip, and the PyPI package requires Python 3.11 or newer. Check the current requirements in the garak user guide and the latest release notes in the garak releases page, because the generator base interface is the part of the codebase most likely to change between versions. Your first commitment is to pin the garak version your custom class was written against.
How a garak scan reaches your endpoint through a custom generator
A scan starts at the garak command line, where the harness loads each probe with its recommended detectors and sends prompts through the custom generator class. The generator reads credentials from a secrets source at run time, so no key sits in a config file, and calls your proprietary endpoint from the scanner host. Responses return to the detectors, and the results land in the JSONL report and garak.log. Check that the trust boundary is crossed only by the generator, and that secrets never appear in the logs or reports.
Data flow from the garak harness through a custom generator to an internal endpoint, with outputs written on the scanner host.
Choosing between REST, WebSocket, built-in and custom generators
The REST generator is the first option to try when your endpoint accepts an HTTP request and returns plaintext or JSON. You describe the endpoint in a short YAML file, including the URL, headers and where the prompt and reply sit, and garak sends each prompt through it without any Python code. Because the configuration is a file, it can be reviewed and versioned with the rest of your scan setup.
- Fits: chat endpoints that accept a static bearer token or API key in a header and a JSON body with the prompt in a known field.
- Reply handling: plaintext replies, or JSON replies where the generated text sits at a predictable path.
- Reviewable setup: URL, headers, request template and response extraction live in one file that security reviewers can read.
- Cannot handle: request signing computed per request, such as a timestamp-based signature over the body, multi-step session handshakes, or token refresh driven by earlier responses.
- Secrets risk: the YAML file is where keys get pasted by mistake, so confirm in the user guide how the generator reads credentials from the environment or another source.
Before choosing this tab, check that your authentication can be expressed as a static header and that the reply text is at a stable location in the response.
A WebSocket generator would suit applications that stream replies over a persistent connection instead of answering each HTTP request. Whether garak ships one, under what name, and with which configuration keys depends on the version you run, so confirm this in the garak user guide at docs.garak.ai before you plan a scan around it. Do not assume a generator exists because the REST option does.
- Possible fit: chat products that open a socket and stream tokens, if the installed version includes a WebSocket generator.
- Confirm first: the generator name, the configuration keys, how messages are framed, and how streamed fragments are joined into one reply.
- Version pinning: generators change between releases, so check the release notes for the exact version your team pins.
- Cannot handle: custom handshakes or signed connection requests, unless the generator exposes hooks for them.
- Fallback: if no generator covers your protocol, the custom generator class is the route.
Ask the question in writing before scoping the work: which version includes the generator, which keys it reads, and how the end of a streamed reply is detected.
garak ships generators for several model providers and local runtimes, so a model served by one of them can be tested without writing code. This tab applies when the thing under test is a model reached through a supported provider or gateway, not the application built around it. The supported list in the garak README includes Hugging Face Hub models, Replicate text models, OpenAI API models, AWS Bedrock foundation models, models via LiteLLM, and gguf models through llama.cpp.
- Hosted APIs: OpenAI API models and AWS Bedrock foundation models, for teams calling those providers directly.
- Model hubs: Hugging Face Hub models and Replicate text models.
- Gateways and local files: models reached through LiteLLM and gguf models run through llama.cpp.
- Cannot handle: your application's own routing, retrieval, tool calls or guardrails, because those sit outside the model call.
- Gateway option: if your in-house model is already behind a LiteLLM proxy, the proxy may let you reuse the built-in path, but confirm that the proxy supports your model and API shape first.
Decide early whether you are testing a model or the application around it, because the built-in list only helps with the first.
A custom generator class is a Python plugin that garak loads like any other plugin. You write the code that builds the request, authenticates, retries on failure, and turns the response into the text garak evaluates. This is the right option when the endpoint uses a proprietary protocol, a vendor SDK with its own client, or signed requests and session handshakes that a REST file cannot express.
- Fits: private RPC or binary protocols, internal SDKs, and authentication that changes per request or per session.
- Owns: request construction, credential handling, retry and backoff behavior, and parsing of replies.
- Ongoing cost: your team maintains this code and must update it when the endpoint or the garak plugin interface changes between releases.
- Verification burden: a wrong parse can make every probe look safe, so test the generator against known replies before trusting scan results.
- Simpler alternative: if the target is a Python function in the same process, garak's function generator avoids a network call entirely.
Before writing code, confirm the endpoint's authentication model, rate limits and reply format with the team that owns the service.
Build the generator class step by step
This sequence takes a proprietary endpoint from an agreed protocol description to a generator class that garak can load, authenticate against, retry safely and test without touching production. Each step ends with a check, so problems surface before the first real scan.
Confirm protocol, SDK and owners
Before writing code, the team that will run the scan meets the owners of the endpoint and the SDK or protocol it uses. Record the request and response shape, the streaming behavior, the error codes, the rate limits, the authentication method and who issues test credentials. Confirm which environment is the approved scan target and whether a non-production copy exists. This step is done when a short written note lists the request format, the response fields garak must read, and the named owner for credential issuance and incident contact.
Pin the garak release and read the base class
Install the garak release you will use in your scan environment, since the PyPI package requires Python 3.11 or newer, and pin that exact version in your project. Open the generator base class in the source tree of that pinned release, not in a newer branch, and note its constructor arguments, the method signature for generating output, and how it reports the generator name. Check the release notes on the project's releases page for changes to generator interfaces. Done when the pinned version is recorded in your repository and you can point to the base class methods your subclass will override.
Implement the constructor and generate method
Create a subclass of the base generator in a module within your plugin package. The constructor sets the endpoint URL, timeouts and model or tenant identifiers from configuration, and the generate method takes a prompt, calls the endpoint through the SDK or protocol client, and returns the text garak expects. Keep the parsing of the response in one small function so it can be tested alone. Done when a unit test sends a fixed prompt through a stubbed client and receives the expected text back, with no network call.
Load credentials from the environment or a vault
Read tokens, client certificates and API keys from environment variables or from your secrets manager at construction time, never from the YAML or JSON config that garak loads and may copy into reports. Do not accept secret values as command-line arguments, since shell history and process listings expose them. Ask your security team which secrets manager and rotation process apply to the scan host. Done when a config file containing only the endpoint name and a credential reference runs successfully, and a search of the config directory and the generated garak.log finds no secret value.
Add retry and backoff handling
Wrap the endpoint call in retry logic that handles timeouts, throttling responses and transient server errors, and that retries with increasing delays and a fixed maximum number of attempts. Retry only errors that are safe to repeat, and fail the attempt clearly on authentication errors so a revoked token does not produce a run full of silent empty results. Respect any rate limit the endpoint owner gave you in step one. Done when a test that simulates a throttling error and then a success returns the success, and a test with persistent authentication failure stops with a readable error in the log.
Register the plugin and configure it
Make the generator discoverable to garak by following the plugin layout and registration method described for the pinned release, and confirm the generator name appears in the list of available generators. Add a configuration file that names the generator, the endpoint settings and the credential reference, keeping it free of secrets. Done when the garak command-line help or generator listing shows your class under its name, and the configuration file passes a parse check without errors.
Test against a blank or known-response target
Run a scan using the blank generator or a stub target that returns fixed answers before pointing the plugin at the real endpoint. Use a small probe selection so the output is easy to inspect. Confirm that the JSONL report records one entry per attempt with the expected prompt and response, and that garak.log shows the run without any secret values. Then run a dry check against the approved non-production endpoint with a handful of prompts. Done when the report contains the expected attempts, the log is clean of credentials, and the team has agreed in writing that the endpoint may receive the full scan.
Handling authentication, retries and backoff without hiding failures
Token handling and retry policy in a custom generator decide whether a scan measures the model or measures your endpoint's availability. Acquire tokens through a method on the generator that caches the access token with its expiry time, refreshes it shortly before expiry, and forces one re-acquisition when the endpoint rejects a request with an authentication error. Keep the client secret or signing key out of the generator's YAML options: read it from an environment variable or your secrets manager at call time, and confirm with your security team where the token cache lives on the scanning host, since garak.log and the JSONL report should never contain a token or a secret value. Test the refresh path directly, because a scan that runs for hours will hit expiry long after a short smoke test passes.
Classify errors before you retry them. Timeouts, HTTP 429 responses and 5xx responses are usually transient, so retry them with exponential backoff and jitter, and honor any Retry-After header the target returns. Authentication failures, 400-series validation errors and malformed responses are usually permanent, so fail the attempt immediately and report it. Retry budgets multiply with garak's default of 5 generations per prompt: if each generation may retry four times with backoff, one prompt can cost up to 25 requests and a long delay, which changes scan duration and can trip the rate limits of the endpoint you are testing. Agree the per-request retry cap and total wait with the scan settings before the first full run, and confirm the endpoint's rate limits with its owner.
Silent retries hide outages. If the generator retries until a response arrives and returns an empty string on exhaustion, the JSONL report will record that attempt as an ordinary output, and a detector may score it as a pass, so a degraded endpoint looks like a secure model. Raise a clear exception or return an explicit error marker when retries are exhausted, log each retry with its status code and attempt count to garak.log, and review the failure counts before reading any pass rate. Ask the owner of the endpoint whether they publish status or error metrics you can compare against the scan window, so a spike in errors during a run can be explained rather than read as a security result.
Keeping secrets out of configs, code and reports
A custom generator touches the most sensitive part of a scan: the credentials that reach the target. The cards below cover where those credentials live at runtime, how they stay out of files and logs, and how the scanner's own access is limited and rotated.
Load credentials at runtime
Have the generator read the API key or token from an environment variable or from your secrets manager when the scan starts, not from a constant in the class. Confirm with your platform team who injects the value into the scanner's runtime (a CI secret, a Kubernetes secret mounted as an environment variable, or a vault agent) and that it is never printed during initialization. Check that a missing variable fails the run with a clear error instead of sending unauthenticated requests.
No keys in YAML or code
Keep the generator's YAML configuration limited to non-secret settings such as the endpoint name, model identifier and timeouts, and reference the credential by name only. Scan the repository and the scanner's configuration directory with a secret detection tool before commit, since a key pasted once into a config file is recoverable from version history. Treat any key that has ever been committed as compromised and rotate it.
Redact the debug log
The garak.log file is continued across runs and is the first file a support engineer opens, so it must not hold authorization headers, session cookies or full request bodies that contain tokens. Review what your generator logs at debug level, mask header values before they reach the logger, and test the redaction by running a scan at verbose settings against a dummy key and searching the log for that string.
Scope the target service account
Create a dedicated service account for the scanner with only the permissions the test needs, usually invoke rights on the chat or completion route and no access to administrative, user-management or data export endpoints. Use a non-production or staging tenant where your environment allows it. Ask the application owner to confirm which roles the account holds and what rate limits and audit logs apply to it.
Rotate scanner tokens
Give scanner tokens a defined lifetime and a rotation owner, and make the generator handle expiry by reloading the secret rather than failing silently mid-scan. Short-lived tokens issued by your identity provider are preferable to long-lived static keys where the endpoint supports them. Confirm how a rotation during a scheduled rescan is coordinated so that a run does not start with an expired credential.
Check the JSONL report
Each run writes a JSONL report of every attempt, so prompts, responses and any echoed request metadata end up in a file that may be shared with auditors or stored for a long time. Before a report leaves the scan host, search it for the credential prefix and for sensitive test content, and confirm your generator does not write headers into the attempt record. Agree with compliance how long reports are kept and who may read them.
garak READMEQuestions teams ask before writing a custom generator
How long does it take to build and test a custom garak generator?
There is no fixed duration that applies to every endpoint, because the effort depends mostly on how the endpoint behaves and how much of it is documented. A generator for a plain JSON API with clear authentication is a small class that is wrapped around one call, while a proprietary SDK with session handling, streaming responses and multi-turn state takes longer to map correctly. The testing effort is often larger than the coding effort: each request and response shape has to be checked against the real endpoint in a non-production environment, and error paths such as expired tokens, rate limits and timeouts need to be exercised. Ask any partner for a written estimate that lists the endpoint features in scope and the test cases that will prove each one works.
Can an internal engineer write a custom garak generator without outside help?
Yes, if the engineer is comfortable with Python and has the endpoint's documentation and a test account. garak is a command-line tool installed from PyPI with pip, and the PyPI package requires Python 3.11 or newer, so the development environment needs that version first. A generator is a Python class that garak loads by name, so the main learning curve is understanding how garak passes prompts in and collects responses, and how it handles retries. Teams usually choose outside help when the protocol is unusual, when the endpoint has security controls that need to be handled carefully, or when nobody on the team has time to maintain the result over the coming releases.
What does the endpoint owner need to provide for a custom generator?
The work depends on the endpoint owner providing accurate information and a safe place to test. The useful inputs are:
- Written documentation of the request and response format, including error codes and any streaming behavior.
- A test credential with the least privilege needed to call the endpoint, issued for this purpose.
- A non-production environment that behaves like production, so scans do not generate load, logs or data changes in live systems.
- A named contact who can explain undocumented behavior and approve changes.
If any of these are missing, the generator usually has to be built on assumptions that surface later as failed scans.
Do custom garak generators need maintenance across garak upgrades?
Yes, a custom generator should be treated as code that your team owns and retests after changes. The generator depends on garak's plugin interface, and that interface can change between releases, so each garak upgrade should be followed by a run of the generator's tests against a non-production endpoint. The endpoint can also change independently of garak, for example when a new authentication method is introduced or a response field is renamed. Plan for both kinds of change, record the garak version used for each scan so results stay comparable, and assign an owner for the generator in the same way you would for any internal library.
How should secrets and retries be handled in a custom generator?
Credentials should be read at runtime from an environment variable or a secrets manager rather than written into a YAML config or committed to source control, and the generator should never print them to garak.log or the JSONL report. Retries should use exponential backoff with a limit on attempts, and they should respect any rate limit the endpoint returns, so a scan does not trigger lockouts or overload a shared service. Treat each retry as a logged event so that a failed attempt can be told apart from an undesirable model output. These choices are easy to get wrong in a first version, which is why reviewing the generator's secret handling is a standard part of the work.
How should a fixed-price engagement for a custom generator be scoped?
A fixed-price engagement is scoped in writing before work starts, with the scope, deliverables and timeline agreed in advance. DeployOpen does not publish a price list, and a quote follows from that written scope. To compare quotes, ask each provider to state the endpoint protocol and authentication method covered, the garak version targeted, the test environment used, the number of test cases, whether the generator is documented and handed over with source code, and whether a retest after a garak upgrade is included. Ask separately about ongoing maintenance, because that cost recurs and is not part of the initial build.
What is the difference between a custom generator and the REST generator?
The REST generator is the right choice when the endpoint accepts plaintext or JSON over HTTP and the configuration can describe the request and response in a short YAML file. garak's REST generator connects to any REST endpoint that returns plaintext or JSON, so a custom generator is only needed when that configuration cannot express the protocol, such as a proprietary binary format, an SDK that manages its own session, or a WebSocket flow that needs custom handling. Before writing code, test the REST generator against the endpoint, because a working configuration is cheaper to maintain than a custom class.
Limits to confirm in your environment before you commit
A custom generator ties your scanner to one garak release, one endpoint and one set of credentials. The cards below cover the limits to confirm before the build starts, so the generator you write still works when the release, the network or the SDK license changes.
Generator API in your pinned release
A custom generator subclasses garak's generator base class and relies on its method signatures, configuration handling and loading behavior. Those details can change between releases, so the first check is which garak version you will pin. Read the user guide and the releases page for the version you chose, and confirm the generator interface matches the sample you plan to copy. Record the pinned version next to the generator code so upgrades are deliberate.
garak user guidePython 3.11 on scan hosts
The garak PyPI package requires Python 3.11 or newer, and your generator runs inside that interpreter. Check every host that will run scans, including CI runners and any jump box, not only the machine where the generator was first tested. If your SDK pins an older Python or conflicts with garak's dependencies, resolve that before the build, because a virtual environment per tool is easier to manage than a shared one.
Network path from scanner to endpoint
Your generator makes outbound calls from the scan host to the in-house endpoint, often across segments, proxies or service meshes. Confirm that the scan host can reach the endpoint address and port, that TLS certificates chain to a trusted authority on that host, and that any egress rules allow the call. Also confirm where the scanner is allowed to run, because a scan host outside the production network may not be able to reach the target at all.
Concurrency and rate limits
Each garak run sends many prompts, and by default makes 5 generations per prompt, so a single scan can produce heavy request volume. Ask the endpoint owners how many concurrent requests the service accepts, what rate limits apply per key or per tenant, and whether scan traffic will count against production quotas. Your backoff and retry logic should respect those limits, and the owners should agree on a window in which scans may run.
SDK license for this use
If your generator wraps a vendor SDK or a third-party client library, the license of that SDK governs whether you may call it from a security testing tool, and whether you may share the wrapper with other teams. Read the license terms, check any restrictions on automated use or redistribution, and confirm with the owner of the SDK or your legal team where the terms are unclear. garak's own Apache 2.0 license does not change the terms of code you wrap.
Offline installs on air-gapped hosts
Air-gapped scan hosts cannot pull garak or its dependencies from PyPI at install time. Plan an offline install: mirror or download the garak package and its dependencies, the SDK your generator imports, and a Python 3.11 runtime, then transfer them through your approved channel. Test the generator from the offline install, because a missing transitive dependency often appears only after the network is closed off.
garak on PyPIHow to verify the generator before it touches a scan that matters
Verify the generator in four stages, each cheaper to fix than the one after it. Start with unit tests against a mocked endpoint that simulate the proprietary protocol or SDK responses your team has recorded: a normal reply, a malformed payload, an authentication failure, a timeout and a rate-limit response. These tests confirm that your generator's _call_model logic raises or retries the way you designed it, without any live traffic. Keep the mocks in the same repository as the generator so that changes to the client library produce a failing test rather than a silent change in scan results.
Next, run the blank generator that ships with garak to confirm the plumbing: how garak loads your class, passes the configured options, collects outputs and writes them to the report. Then run a small probe subset against a non-production instance of the endpoint, with a low generation count and one or two probes whose detectors you already understand. Confirm that the number of attempts in the report matches what you requested, and that retries appear as retries rather than as extra attempts that inflate failure rates. Ask the owner of the non-production endpoint to confirm that it behaves like production for authentication and content filtering, because a mismatch there makes the baseline misleading.
Then inspect the outputs directly. Search garak.log and the JSONL report for API keys, bearer tokens, session cookies and internal hostnames, since logs are continued across runs and are often copied into tickets. Check that a failed call produces an error that garak records clearly and that the probe is not marked as passing on an empty response. Finally, write down a documented baseline: the garak version, generator class and config file hash, probe list, generation count, endpoint version and the resulting report. Later changes to the generator or the endpoint can then be compared against that record, and any shift in scores can be explained rather than guessed at.
How DeployOpen scopes and delivers a custom garak generator
DeployOpen approaches a custom garak generator as a fixed-scope piece of work: the endpoint's protocol, authentication and failure behavior are agreed in writing before any code is written. The generator is then built, tested against the live endpoint and documented so your team can run and maintain it after handover. Ongoing support is available as a retainer when the endpoint keeps changing.
How we scope
- Document the in-house endpoint's protocol, request and response shape, and any SDK it depends on
- Agree how the generator will obtain credentials, refresh tokens and read secrets from your secret store
- Set retry, backoff and timeout behavior and the garak versions the generator must support, in writing
How we build
- Write the generator class against the garak generator interface, with the endpoint call isolated for testing
- Test the generator with the blank generator and mocked responses before connecting it to the live endpoint
- Run a short live scan against a non-production endpoint to confirm responses, errors and rate limits behave as expected
How we hand over
- Deliver the generator code, its configuration template and the list of environment variables it reads
- Provide a runbook covering credential rotation, retry settings, log locations and common error messages
- Walk your engineers through a scan run so they can rerun, debug and extend the generator without us
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 for changes to the endpoint or garak
- Confirm with your team which garak release and Python version your hosts run before the scope is signed

