guardrails

package
v1.3.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 24, 2026 License: Apache-2.0 Imports: 13 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrGuardrailViolation = errors.New("guardrail_violation")

ErrGuardrailViolation indicates an input violated security policies.

Functions

func DetectPromptInjection

func DetectPromptInjection(text string) (bool, string)

DetectPromptInjection checks whether the given prompt attempts jailbreak or instruction override.

func IsValidLuhn

func IsValidLuhn(number string) bool

IsValidLuhn checks whether a sequence of digits passes the Luhn checksum. Discards formatting spaces and dashes before computing sum.

Types

type Action

type Action string

Action defines how guardrails handle violations.

const (
	ActionBlock  Action = "block"
	ActionRedact Action = "redact"
	ActionLog    Action = "log"
)

type Guardrails

type Guardrails struct {
	Enabled               bool
	PIIAction             Action
	PromptInjectionAction Action
	// Latent, when set, screens text in representation space after the regex checks.
	Latent       *LatentDetector
	LatentAction Action
}

Guardrails coordinates PII masking and prompt injection safety checks.

func New

func New(enabled bool, piiAction, injectionAction string) *Guardrails

New creates a configured Guardrails instance.

func (*Guardrails) InspectChatContext

func (g *Guardrails) InspectChatContext(ctx context.Context, chat *llm.ChatContext, vault *TokenVault) ([]Violation, error)

InspectChatContext validates and sanitizes instructions and messages in a ChatContext. Latent screening runs once over every text, after redaction.

func (*Guardrails) InspectPII

func (g *Guardrails) InspectPII(text string, vault *TokenVault) (string, []Violation, error)

InspectPII checks or redacts PII without applying prompt injection heuristics.

func (*Guardrails) InspectText

func (g *Guardrails) InspectText(ctx context.Context, text string, vault *TokenVault) (string, []Violation, error)

InspectText validates a standalone text string against security policies.

func (*Guardrails) InspectTexts

func (g *Guardrails) InspectTexts(ctx context.Context, texts []string) (int, []Violation, error)

InspectTexts screens many independent texts without redaction, batching the latent encoder calls; batch intake would otherwise pay one round trip per text. On a block it also returns the index of the offending text.

func (*Guardrails) WithLatent

func (g *Guardrails) WithLatent(d *LatentDetector, action string) *Guardrails

WithLatent adds representation-space screening; action is block or log.

type LatentCategory

type LatentCategory struct {
	Name      string           `json:"name"`
	Phrases   []string         `json:"phrases,omitempty"`
	Centroids []LatentCentroid `json:"centroids,omitempty"`
}

LatentCategory is one malicious-intent cluster. Phrases are encoded with whichever model serves the request; Centroids are precomputed vectors (e.g. JEPA cluster centres) that apply only to the model they were built with.

func DefaultLatentCategories

func DefaultLatentCategories() []LatentCategory

DefaultLatentCategories is the built-in seed set. Each phrase acts as its own centroid: averaging diverse jailbreaks blurs them into a vector close to nothing, while nearest-exemplar keeps every attack family sharp.

func LoadLatentCategories

func LoadLatentCategories(path string) ([]LatentCategory, error)

LoadLatentCategories reads a JSON array of categories from path.

type LatentCentroid

type LatentCentroid struct {
	Model  string    `json:"model"`
	Vector []float32 `json:"vector"`
}

LatentCentroid is a vector in one encoder's space.

type LatentDetector

type LatentDetector struct {
	// contains filtered or unexported fields
}

LatentDetector classifies prompts by distance to malicious centroids in representation space, catching paraphrased and obfuscated attacks that regexes miss.

func NewLatentDetector

func NewLatentDetector(enc latent.Encoder, threshold float64, categories []LatentCategory) (*LatentDetector, error)

NewLatentDetector validates categories and precomputed centroids up front so a bad categories file fails at startup rather than per request.

func (*LatentDetector) Classify

func (d *LatentDetector) Classify(ctx context.Context, texts []string) ([]LatentMatch, error)

Classify returns the best match at or above the threshold for each flagged text; clean texts produce no entry.

func (*LatentDetector) Warmup

func (d *LatentDetector) Warmup(ctx context.Context) error

Warmup encodes the phrase centroids for the encoder's current model so the first request does not pay for it.

type LatentMatch

type LatentMatch struct {
	Index    int
	Category string
	Score    float32
}

LatentMatch reports which input crossed the threshold and how close it came.

type PIISpan

type PIISpan struct {
	Category ViolationCategory
	Start    int
	End      int
	Value    string
}

PIISpan represents a range of text identified as sensitive information.

func DetectPII

func DetectPII(text string) []PIISpan

DetectPII scans the input text for sensitive patterns.

type StreamDesanitizer

type StreamDesanitizer struct {
	// contains filtered or unexported fields
}

StreamDesanitizer buffers partial placeholder sequences across stream chunks.

func NewStreamDesanitizer

func NewStreamDesanitizer(v *TokenVault) *StreamDesanitizer

NewStreamDesanitizer constructs a streaming desanitizer tied to a token vault.

func (*StreamDesanitizer) Flush

func (s *StreamDesanitizer) Flush() string

Flush returns any trailing buffered text.

func (*StreamDesanitizer) ProcessChunk

func (s *StreamDesanitizer) ProcessChunk(delta string) string

ProcessChunk transforms an incremental stream delta, buffering incomplete placeholders.

type TokenVault

type TokenVault struct {
	// contains filtered or unexported fields
}

TokenVault stores reversible anonymization mappings for a single session.

func NewTokenVault

func NewTokenVault() *TokenVault

NewTokenVault initializes an empty vault.

func (*TokenVault) Desanitize

func (v *TokenVault) Desanitize(text string) string

Desanitize replaces placeholders with original sensitive values in plain text.

func (*TokenVault) DesanitizeJSON

func (v *TokenVault) DesanitizeJSON(jsonText string) string

DesanitizeJSON replaces placeholders in JSON payloads, escaping replacement strings.

func (*TokenVault) GetOrCreate

func (v *TokenVault) GetOrCreate(category ViolationCategory, original string) string

GetOrCreate generates or returns an existing placeholder for the original string.

func (*TokenVault) Redact

func (v *TokenVault) Redact(text string) (string, []Violation)

Redact replaces PII spans in text with vault placeholders.

type Violation

type Violation struct {
	Category ViolationCategory
	Detail   string
	Value    string
}

Violation records a detected security rule hit.

type ViolationCategory

type ViolationCategory string

ViolationCategory categorizes the detected violation.

const (
	CategoryCreditCard      ViolationCategory = "credit_card"
	CategoryEmail           ViolationCategory = "email"
	CategoryPhone           ViolationCategory = "phone"
	CategorySSN             ViolationCategory = "ssn"
	CategoryIPAddress       ViolationCategory = "ip_address"
	CategoryPromptInjection ViolationCategory = "prompt_injection"
	CategoryLatentThreat    ViolationCategory = "latent_threat"
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL