## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(collapse = TRUE, comment = "#>", eval = TRUE)

## -----------------------------------------------------------------------------
library(llmshieldr)

## -----------------------------------------------------------------------------
guardrails <- policy()
guardrails$thresholds

## -----------------------------------------------------------------------------
guardrails <- add_rule(
  guardrails,
  id = "llm02.ticket_id",
  pattern = "\\bTICKET-[0-9]{6}\\b",
  owasp = "llm02",
  severity = "medium",
  action = "redact",
  description = "Internal support ticket identifier."
)

scan_prompt("Summarize TICKET-123456 for the support team.", guardrails)

## -----------------------------------------------------------------------------
contains_student_address <- function(text) {
  grepl("\\bstudent\\b", text, ignore.case = TRUE) &&
    grepl("\\bhome address\\b", text, ignore.case = TRUE)
}

education <- policy("education_safe")
education <- add_rule(
  education,
  id = "llm02.student.address",
  fn = contains_student_address,
  owasp = "llm02",
  severity = "high",
  action = "redact",
  description = "Student home address reference."
)

scan_prompt("The student home address appears in the form.", education)

## -----------------------------------------------------------------------------
ticket_span_rule <- function(text) {
  hit <- regexpr("\\bTICKET-[0-9]{6}\\b", text, perl = TRUE)
  if (identical(as.integer(hit[[1]]), -1L)) {
    return(FALSE)
  }
  start <- as.integer(hit[[1]])
  end <- start + as.integer(attr(hit, "match.length")) - 1L
  list(
    rule_id = "llm02.ticket_id.fn",
    owasp = "llm02",
    severity = "medium",
    action = "redact",
    description = "Internal support ticket identifier.",
    match = substr(text, start, end),
    start = start,
    end = end
  )
}

## -----------------------------------------------------------------------------
pharma <- policy("pharma_gxp")
pharma <- add_rule(
  pharma,
  id = "llm02.site_id",
  pattern = "\\bSITE-[0-9]{3}\\b",
  owasp = "llm02",
  severity = "medium",
  action = "redact",
  description = "Clinical trial site identifier."
)

## -----------------------------------------------------------------------------
finance <- policy("finance_strict")
finance <- add_rule(
  finance,
  id = "llm09.promissory_return",
  pattern = "(?i)guaranteed\\s+(alpha|profit|return)",
  owasp = "llm09",
  severity = "critical",
  action = "block",
  description = "Promissory investment performance claim."
)

## -----------------------------------------------------------------------------
list_rules(guardrails)

