Two technicians push a rod into one numbered channel on a reactor loading face covered in identical holes, with the article title about generating Nuclei templates with an LLM
Cover based on a photo by Ed Westcott, US Department of Energy, via Wikimedia Commons, Public domain

You can generate Nuclei templates with an LLM in under a minute, and getting one past nuclei -validate is the easy part. That is the trap. Validation proves the YAML parses into Nuclei's schema. It says nothing about which hosts the template will flag. A model-written template that matches every catch-all page on the internet validates just as cleanly as one that finds the bug you care about.

This guide tests that gap on a small lab. Every scan result below came from Nuclei v3.11.1, the current release on the Nuclei GitHub releases page, installed from the official nuclei_3.11.1_linux_amd64.zip with its published SHA-256 checksum. The targets were two HTTP servers we wrote and ran on localhost: one with a planted bug, one catch-all front end that answers 200 to everything. We rechecked template keys, matcher behavior and CLI flags against the ProjectDiscovery docs and the v3.11.1 source on November 24, 2026. The drafts were written for this guide to show mistakes models commonly make in Nuclei YAML. They are not a captured model transcript, and no model was called in the lab. Nuclei's output is the evidence.

Authorized work only. Run custom templates against your own lab or against assets your written scope covers, at rates the program allows. A template is a set of requests; a bad one sends them to hosts you did not mean to test.

If you already have Nuclei results and need to sort them, that is a different job, covered in Nuclei LLM triage. This post is about writing the template in the first place. The same draft-then-test loop works for Semgrep rules, Nmap NSE scripts and Burp BChecks.

Why generate Nuclei templates with an LLM

The public nuclei-templates repository covers known CVEs and common exposures. The checks that matter on a specific engagement are usually narrower: an internal admin route on the app you are testing, a debug header one build leaks, a version string that marks the vulnerable release. Nobody else has written those templates, so you write them.

Models are good at the outline of a Nuclei template: id, an info block, an http request with {{BaseURL}} in the path, a list of matchers. They are less reliable on the semantics. Two defaults catch them most often:

  • Multiple matchers are OR'd unless you say otherwise. The matchers docs state that "the default condition is to follow OR operation in between all the matchers." A model that lists a status check and a body check usually means "both". Nuclei reads "either".
  • Words inside one matcher are OR'd too. "When no condition is specified, OR is used as the default."

Neither mistake produces an error. Both produce findings.

Can Nuclei's built-in AI use your own model?

ProjectDiscovery documents two AI template features, and neither takes a custom model endpoint (checked against v3.11.1).

The CLI flag -ai (alias -prompt) "generate[s] and run[s] template using ai prompt", per nuclei -h. The Running Nuclei docs say it is "powered by the ProjectDiscovery API" and needs a ProjectDiscovery API key. In the v3.11.1 source, the endpoint is a constant, https://api.projectdiscovery.io/v1/template/ai, in pkg/catalog/loader/ai_loader.go. There is no flag or environment variable that points it elsewhere. Without a key, it stops before sending anything:

$ nuclei -duc -ai "detect unauthenticated csv export at /admin/export"
[FTL] To utilize the `-ai` flag, please configure your API key with the `-auth` flag or set the `PDCP_API_KEY` environment variable

The docs also note that generated templates are stored "in your ProjectDiscovery cloud account" and that each user gets 100 generations a day. The second feature, AI assistance in the cloud Template Editor, is a hosted product with its own model.

Both work if you are content with ProjectDiscovery's model and cloud. If you want a different model, or you can't send a description of a client's endpoint to another vendor's cloud, the route is a general-purpose LLM plus Nuclei's own checks. That is what the rest of this guide does.

How to test LLM Nuclei template validation

Ask three questions, in order:

  1. Does it validate? nuclei -validate -t template.yaml catches unknown keys, bad enum values and DSL functions that don't exist.
  2. Does it match the host you know is vulnerable?
  3. Does it stay quiet on a host that looks similar but isn't? This is the one that -validate can't answer, and the one that decides whether your report is right.

You need a lab with both kinds of host before you ask the model for anything.

Step 1: Build a lab with a vulnerable host and a catch-all host

We wrote two small Python HTTP servers and bound both to 127.0.0.1:

HostWhat it isGET /admin/export returns
127.0.0.1:8081A synthetic ledger-api 2.4.1 with a planted bug: the CSV export needs no login200, Content-Type: text/csv, X-Ledger-Version: 2.4.1, a CSV header row and two rows of fake ledger data
127.0.0.1:8082A single-page-app front end that serves its HTML shell for every path200, Content-Type: text/html, a page whose nav bar links to "Export"

The second host is the important one. Catch-all front ends, soft-404 pages and WAF block pages that return 200 are everywhere, and they are where loose templates produce false positives. Each server is under 30 lines of Python's http.server, and neither holds real data.

Step 2: The prompt for writing Nuclei YAML with AI

A prompt that gives the model enough to work with:

Write one Nuclei v3 HTTP template. Target: GET {{BaseURL}}/admin/export. Vulnerable response: HTTP 200, Content-Type text/csv, body starts with the header row account_id,amount,currency,memo, response header X-Ledger-Version: 2.4.1. Not vulnerable: an HTML app shell returned with HTTP 200 for every path. Require all matchers to pass. Extract the X-Ledger-Version value. Use only keys documented for Nuclei v3. Return YAML only.

Paste in a captured vulnerable response and a captured catch-all response if you have them, with secrets removed. Describing the negative case is the line most prompts leave out, and the one that matters most.

Step 3: The first draft validates and flags the wrong host

A typical first draft, from a vaguer prompt ("write a Nuclei template that detects an unauthenticated /admin/export endpoint and extracts the version"):

id: ledger-unauth-export

info:
  name: Ledger API - Unauthenticated CSV Export
  author: lab
  severity: high
  description: Checks whether /admin/export returns ledger data without authentication.
  tags: lab,ledger,exposure

http:
  - method: GET
    path:
      - "{{BaseURL}}/admin/export"

    matchers:
      - type: status
        status:
          - 200

      - type: word
        words:
          - "account_id"
          - "Export"

    extractors:
      - type: regex
        name: version
        regex:
          - "X-Ledger-Version: ([0-9.]+)"

It looks careful. Nuclei agrees it is valid:

$ nuclei -duc -validate -t ledger-export-draft.yaml
[INF] All templates validated successfully

Then we ran it against both lab hosts:

$ nuclei -duc -t ledger-export-draft.yaml -l targets.txt
[INF] Templates loaded for current scan: 1
[INF] Targets loaded for current scan: 2
[ledger-unauth-export] [http] [high] http://127.0.0.1:8081/admin/export
[ledger-unauth-export] [http] [high] http://127.0.0.1:8082/admin/export
[INF] Scan completed in 3.433837ms. 2 matches found.

Two high-severity findings, one of them false. Three things went wrong, and none of them is a syntax error:

  • No matchers-condition. The status matcher and the word matcher are OR'd, so any 200 response matches. The catch-all host returns 200 for everything.
  • An OR'd word list. Even with the matchers AND'd, "Export" appears in the catch-all's nav bar, and one word is enough.
  • The extractor looks in the wrong place. Extractors default to the response body, and X-Ledger-Version is a header. The finding on the real host has no version in it.

The obvious one-line fix is not enough. Adding only matchers-condition: and to this draft still flagged both hosts in our lab, because the catch-all passes both the status check and the "Export" word.

Step 4: Fix the matchers and the extractor

id: ledger-unauth-export

info:
  name: Ledger API - Unauthenticated CSV Export
  author: lab
  severity: high
  description: Checks whether /admin/export returns ledger data without authentication.
  tags: lab,ledger,exposure

http:
  - method: GET
    path:
      - "{{BaseURL}}/admin/export"

    matchers-condition: and
    matchers:
      - type: status
        status:
          - 200

      - type: word
        part: header
        words:
          - "text/csv"

      - type: word
        part: body
        words:
          - "account_id,amount,currency"

      - type: word
        part: body
        words:
          - "<html"
        negative: true

    extractors:
      - type: regex
        name: version
        part: header
        group: 1
        regex:
          - "X-Ledger-Version: ([0-9.]+)"
$ nuclei -duc -t ledger-export-fixed.yaml -l targets.txt
[ledger-unauth-export:version] [http] [high] http://127.0.0.1:8081/admin/export ["2.4.1"]
[INF] Scan completed in 2.642963ms. 1 matches found.

One finding, on the right host, with the version attached. What changed:

  • matchers-condition: and makes every matcher required.
  • The body word is the CSV header row, not a word that also appears in navigation. Matching on something only the vulnerable response can contain is the whole job of a matcher.
  • part: header with text/csv rules out HTML shells. The negative: true matcher on <html is a cheap second guard; the matchers docs document negative for every matcher type.
  • The extractor now reads part: header. group: 1 returns only the captured version. Per the extractors docs, without a group a regex extractor "will hold the full match".

A kval extractor is shorter for a single header. Header names are lowercased with dashes turned into underscores, so this also returned ["2.4.1"] on the vulnerable host:

    extractors:
      - type: kval
        name: version
        kval:
          - x_ledger_version

To see which response parts and header variables exist, run one host with -debug -svd (show variable dump). In our run the dump listed body, header, all_headers, content_type, status_code and x_ledger_version.

One flag that sounds more useful than it was: -ms (matcher status) prints a [failed] line for non-matching hosts. In v3.11.1 that line showed 127.0.0.1 without a port, so with two lab hosts on one IP it didn't say which one failed.

Diagram of LLM Nuclei template validation: an LLM draft passes nuclei -validate but matches both the vulnerable lab host and a catch-all host, while the fixed template with matchers-condition and and a header extractor matches only the vulnerable host and extracts version 2.4.1
Both templates validate. Only the fixed one tells the vulnerable host from the catch-all host and extracts the version. Image: RedRouter, Original

Step 5: What nuclei -validate catches, and what it doesn't

We fed -validate five more mistakes we see in model output. Each line is from v3.11.1.

Invented key. Models often write negate: true. The real key is negative:

[ERR] ... yaml: unmarshal errors:\n  line 21: field negate not found in type matchers.Matcher
[FTL] Could not validate templates: errors occurred during template validation

Invented DSL function. str_contains(body, "account_id") in a dsl matcher:

[ERR] ... could not compile DSL expression "str_contains(body, \"account_id\")": Undefined function str_contains

The real helper is contains. nuclei -ldf lists every DSL function signature.

Bad enum values. severity: severe failed with Invalid severity: severe. type: contains on a matcher failed with Invalid matcher type: contains.

A wrong part name passes. This is the one to remember. A word matcher with part: headers (plural) validated successfully. Against the vulnerable host it found nothing:

[INF] Scan completed in 2.860608ms. No results found.

The same template with part: header matched. There is no headers part in the variable dump, so the matcher had nothing to look at and failed quietly. -validate does not check part names. Only a run against a host you know is vulnerable catches it.

Old protocol key. requests: instead of http: validated and ran, with a warning at scan time: Found 1 templates loaded with deprecated protocol syntax, update before v3 for continued support. Use http:.

Common mistakes when you generate Nuclei templates with an LLM

  • Missing matchers-condition: and. Multiple matchers are OR'd by default. A status: 200 matcher on its own will match every catch-all page.
  • Generic words. Match on strings only the vulnerable response contains: a header row, an error code, a specific JSON key. Not "admin", "Export" or "success".
  • Wrong part. Matchers and extractors default to body. Headers need part: header. Plural or invented part names validate and then match nothing.
  • Regex extractors without group. You get the whole match, label included.
  • Invented keys and functions. negate, str_contains and similar fail validation, which is the easy case. Check the matchers and extractors references for anything you haven't used before.
  • Testing only the positive case. A template that matches the vulnerable host proves half the claim. Run it against a catch-all or patched host too.
  • Treating a match as a finding. A match says a matcher fired. Whether that is a reportable issue is a separate judgment; the AI bug bounty workflow covers where that check sits.

What to send the model

  • Send: the request, a scrubbed vulnerable response, a scrubbed "looks similar but isn't" response, your Nuclei version, and the exact error from -validate or the list of hosts that matched when they shouldn't have.
  • Scrub: hostnames, cookies, tokens, customer data in bodies. Replace them with lab placeholders, get the template working on your lab, then run it on scope.
  • Don't send raw JSONL. Nuclei's JSONL includes the full request and response for each finding by default. -omit-raw (-or) drops them.
  • Check retention. On RedRouter, zero data retention is an opt-in setting, off by default. The data handling docs explain what is stored and how to turn it on.

Automating the draft, validate and scan loop

The checking half is two Nuclei commands, so it scripts easily. This checker runs -validate, scans both lab hosts with -jsonl -omit-raw, and compares the matched URLs with the one you expect. We ran it on every template in this post:

import json, subprocess

TARGETS = "targets.txt"  # http://127.0.0.1:8081 and http://127.0.0.1:8082
EXPECTED = {"http://127.0.0.1:8081/admin/export"}

def check(template):
    v = subprocess.run(["nuclei", "-duc", "-nc", "-validate", "-t", template],
                       capture_output=True, text=True)
    if v.returncode != 0:
        errors = [l for l in (v.stdout + v.stderr).splitlines() if "ERR" in l or "FTL" in l]
        return False, "nuclei -validate failed:\n" + "\n".join(errors)
    s = subprocess.run(["nuclei", "-duc", "-nc", "-silent", "-jsonl", "-omit-raw",
                        "-t", template, "-l", TARGETS], capture_output=True, text=True)
    hits = [json.loads(l) for l in s.stdout.splitlines() if l.startswith("{")]
    matched = {h["matched-at"] for h in hits}
    extracted = sorted({x for h in hits for x in h.get("extracted-results") or []})
    if matched != EXPECTED:
        return False, (f"Validates, but matched {sorted(matched) or 'nothing'}; "
                       f"expected only {sorted(EXPECTED)}. Extracted: {extracted or 'nothing'}")
    if not extracted:
        return False, "Matches the right host, but the version extractor returned nothing."
    return True, f"OK: matched {sorted(matched)}, extracted {extracted}"

Its output on the drafts above:

ledger-export-draft.yaml
Validates, but matched ['http://127.0.0.1:8081/admin/export', 'http://127.0.0.1:8082/admin/export']; expected only ['http://127.0.0.1:8081/admin/export']. Extracted: nothing

ledger-export-fixed.yaml
OK: matched ['http://127.0.0.1:8081/admin/export'], extracted ['2.4.1']

The model half feeds that message back. This sketch uses the OpenAI Python SDK with RedRouter's https://redrouter.org/v1 base URL from the quickstart. We did not run it against the API for this post:

import os
from openai import OpenAI

llm = OpenAI(base_url="https://redrouter.org/v1", api_key=os.environ["REDROUTER_API_KEY"])
messages = [{"role": "user", "content": open("prompt.txt").read()}]

for attempt in range(4):
    reply = llm.chat.completions.create(model="glm-5.3-flash-red", messages=messages)
    yaml_text = reply.choices[0].message.content.strip().removeprefix("```yaml").strip("`").strip()
    open("candidate.yaml", "w").write(yaml_text + "\n")
    ok, note = check("candidate.yaml")
    print(note)
    if ok:
        break
    messages += [{"role": "assistant", "content": yaml_text},
                 {"role": "user", "content": note + "\nReturn the fixed template only."}]

Keep the loop pointed at your lab. Run the finished template on scope yourself, and read it before you do: the model chose every request it sends. If an agent will run templates during an engagement, give it a scope file and logs, as in the agent broker pattern.

On signing: Nuclei runs unsigned custom HTTP templates, and the template signing docs say it warns about them. Unsigned code protocol templates are blocked. With -debug, our v3.11.1 run logged Loading 1 unsigned templates for scan. Use with caution. Sign templates with -sign if your team shares them.

Choosing a model for Nuclei template generation

Use any model that follows a "YAML only" instruction and can take a few rounds of error messages. On RedRouter, GLM 5.3 Flash Red (glm-5.3-flash-red) is $0.25 per 1M input tokens, $0.13 per 1M cached input tokens and $1.00 per 1M output tokens. red-cyber-1 (Beta), the featured model for authorized penetration testing and red-team work, is $0.28 / $0.13 / $1.10 per 1M tokens. The models docs list current rates for every model; plans are on /pricing.

Template prompts describe exposures, payloads and exploit conditions in plain terms. RedRouter is built for that kind of authorized security work.

FAQ

Can I generate Nuclei templates with an LLM?

Yes, as a first draft. In our lab, a model-style draft passed nuclei -validate and flagged both a vulnerable host and a catch-all host. Adding matchers-condition: and, a specific body match, a header content-type check and a header extractor left one finding on the right host, with the version extracted.

Does nuclei -validate prove a template works?

No. It catches unknown keys, invalid severities, invalid matcher types and undefined DSL functions. It passed a template with part: headers (not a real part) that then matched nothing, and it passed a template that flagged a false positive. Run every template against a known-vulnerable host and a known-clean one.

How do I write Nuclei YAML with AI that doesn't flag false positives?

Describe the negative case in the prompt, require all matchers with matchers-condition: and, match on strings only the vulnerable response contains, and check part on every matcher and extractor. Then test on a catch-all host.

Can nuclei -ai use my own model or an OpenAI-compatible API?

Not as of v3.11.1. The -ai flag sends prompts to a fixed ProjectDiscovery endpoint and needs a ProjectDiscovery API key. To use another model, generate the template elsewhere and run nuclei -validate and a lab scan on it.

Why does my LLM Nuclei template match every host?

Usually because multiple matchers are OR'd by default, so a status: 200 matcher matches any page that returns 200. Add matchers-condition: and and a matcher on content only the vulnerable response has.

Sources