> For the complete documentation index, see [llms.txt](https://ai.ortusbooks.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ai.ortusbooks.com/main-components/middleware/llm-guard.md).

# LLMGuardMiddleware

Use a second model as a security classifier for injection and harmful content

Class: `bxModules.bxai.models.middleware.security.LLMGuardMiddleware`

Uses a second model (judge) to classify inbound and/or outbound content for security risk. Complements heuristic sanitization with semantic classification.

## Features

* Input judging in `beforeLLMCall`
* Optional output judging in `afterLLMCall`
* Configurable fail-open or fail-closed behavior
* Confidence threshold and category gating
* Prompt fencing to isolate untrusted content
* Verdict caching (in-memory static or named BoxLang cache)
* Re-entrancy guard for nested judge calls

## Constructor

```javascript
middleware = new bxModules.bxai.models.middleware.security.LLMGuardMiddleware(
    judge         : {},
    checkInput    : true,
    checkOutput   : false,
    failMode      : "open",
    threshold     : 0.7,
    categories    : [ "INJECTION", "HARMFUL" ],
    timeout       : 10,
    cacheEnabled  : true,
    cacheName     : "",
    maxCacheSize  : 1000,
    promptTemplate: ""
)
```

## Configuration

| Option           | Type    | Default                   | Description                                            |
| ---------------- | ------- | ------------------------- | ------------------------------------------------------ |
| `judge`          | struct  | `{}`                      | Judge settings: provider/model/apiKey/params/options   |
| `checkInput`     | boolean | `true`                    | Judge user content before main model call              |
| `checkOutput`    | boolean | `false`                   | Judge model output after call                          |
| `failMode`       | string  | `"open"`                  | On judge failure: `open` (allow) or `closed` (block)   |
| `threshold`      | numeric | `0.7`                     | Minimum confidence to act on non-safe verdict          |
| `categories`     | array   | `["INJECTION","HARMFUL"]` | Verdict categories treated as blockable                |
| `timeout`        | numeric | `10`                      | Judge timeout in seconds                               |
| `cacheEnabled`   | boolean | `true`                    | Enable verdict caching                                 |
| `cacheName`      | string  | `""`                      | Named BoxLang cache; empty uses static in-memory cache |
| `maxCacheSize`   | numeric | `1000`                    | In-memory cache size cap                               |
| `promptTemplate` | string  | `""`                      | Custom classifier prompt; empty uses default           |

## Hooks Used

* `beforeLLMCall`
* `afterLLMCall`

## Verdict Contract

The judge is expected to return strict JSON:

```json
{ "verdict": "SAFE|INJECTION|HARMFUL", "confidence": 0.0, "reason": "..." }
```

## Example

```javascript
guard = new bxModules.bxai.models.middleware.security.LLMGuardMiddleware(
    judge: {
        provider: "ollama",
        model   : "llama-guard3",
        params  : { temperature: 0, max_tokens: 256 }
    },
    checkInput : true,
    checkOutput: true,
    failMode   : "closed",
    threshold  : 0.8
)

agent = aiAgent( middleware: [ guard ] )
```

## Notes

* Blocking uses `BXAI.SecurityViolation` throws.
* Judge calls are marked internal to avoid recursive security middleware re-entry.
* Invalid `failMode` throws `InvalidFailMode` during construction.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://ai.ortusbooks.com/main-components/middleware/llm-guard.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
