Overview
BanCode is an output scanner that detects and blocks code snippets in LLM responses by delegating to the input-side InputBanCode scanner.
Description
The BanCode output scanner is a thin wrapper around the corresponding input scanner InputBanCode. It intercepts LLM outputs and checks whether they contain code snippets that should be blocked. Internally, the scanner creates an instance of InputBanCode with the same configuration parameters and delegates the scanning of the output text to it. This design pattern keeps the code DRY while providing a consistent output scanner interface. The scanner uses a classification model to detect code presence and compares against a configurable threshold to determine whether the output should be flagged.
Usage
Use this scanner when you need to prevent an LLM from returning code in its responses. This is useful in scenarios where code generation is not desired, such as customer support chatbots, educational tools that should explain concepts without providing ready-made code, or compliance-sensitive applications where code output could pose a security risk.
Code Reference
Source Location
Signature
class BanCode(Scanner):
def __init__(
self,
*,
model: Model | None = None,
threshold: float = 0.9,
use_onnx: bool = False,
) -> None: ...
def scan(self, prompt: str, output: str) -> tuple[str, bool, float]: ...
Import
from llm_guard.output_scanners import BanCode
I/O Contract
Inputs
| Name |
Type |
Required |
Description
|
| prompt |
str |
Yes |
The input prompt
|
| output |
str |
Yes |
The LLM output to scan for code snippets
|
Constructor Parameters
| Name |
Type |
Required |
Default |
Description
|
| model |
None |
No |
None |
Custom classification model to use for code detection
|
| threshold |
float |
No |
0.9 |
Confidence threshold above which code is flagged
|
| use_onnx |
bool |
No |
False |
Whether to use ONNX runtime for inference
|
Outputs
| Name |
Type |
Description
|
| sanitized_output |
str |
The output (potentially modified)
|
| is_valid |
bool |
Whether the output passed the scan (True if no code detected)
|
| risk_score |
float |
Risk score (-1.0 to 1.0)
|
Usage Examples
Basic Usage
from llm_guard.output_scanners import BanCode
scanner = BanCode(threshold=0.9)
prompt = "Explain how sorting works"
output = "Sorting arranges elements in order. Here is an example:\ndef bubble_sort(arr):\n for i in range(len(arr)):\n for j in range(len(arr)-1):\n if arr[j] > arr[j+1]:\n arr[j], arr[j+1] = arr[j+1], arr[j]"
sanitized_output, is_valid, risk_score = scanner.scan(prompt, output)
if not is_valid:
print(f"Code detected in output (risk score: {risk_score})")
Related Pages
Page Connections
Double-click a node to navigate. Hold to expand connections.