Documentation
¶
Index ¶
- Constants
- Variables
- func AppCapabilityFor(input *ScriptInput) guardrails.Capability
- func CountAssistantMessages(messages []llms.MessageContent) int
- func CountUserMessages(messages []llms.MessageContent) int
- func DefinitionScreeners(filters []*models.Filter) []*models.Filter
- func DrainShadowGuardrails(ctx context.Context)
- func EventRecorder(filterScope string, appID, userID, llmID uint, vendor, modelName string) func(context.Context, string, *ScriptOutput)
- func GetAllText(messages []llms.MessageContent) string
- func GetAllUserMessages(messages []llms.MessageContent) []string
- func GetLastUserMessage(messages []llms.MessageContent) string
- func GetMessagesByRole(messages []llms.MessageContent, role llms.ChatMessageType) []string
- func GetSystemPrompt(messages []llms.MessageContent) string
- func HasImages(messages []llms.MessageContent) bool
- func MessageCount(messages []llms.MessageContent) int
- func OwnerSummary(eventType string, m map[string]any) (action, code, text string)
- func RecordComplianceEvents(ctx context.Context, output *ScriptOutput, filterName, filterScope string, ...)
- func RunToolInputFilters(ctx context.Context, filters []models.Filter, ...) (ToolCallArgs, *ToolBlock, error)
- func ScreenToolDefinitions(ctx context.Context, filters []*models.Filter, tools []llms.Tool, ...) ([]llms.Tool, error)
- func SetCapabilitySource(src CapabilitySource)
- func SetExceptionSource(src ExceptionSource)
- func SetJudgeCallForTesting(...) (restore func())
- func SetPromptTemplateSource(src PromptTemplateSource)
- type AppExceptions
- type CapabilitySource
- type ComplianceEventOutput
- type ErrToolDefinitionsBlocked
- type ExceptionSource
- type FilterRunner
- type GuardrailException
- type JudgeOpinion
- type LLMBudgetChecker
- type MessageTool
- type PromptTemplateSource
- type ScriptInput
- type ScriptOutput
- type ScriptRunner
- type ServiceInterface
- type ToolBlock
- type ToolCallArgs
- type ToolFilterIdentity
Constants ¶
const ( // ReasonDetected: the provider flagged the text. ReasonDetected = "guardrail_detected" // ReasonTooLargeToScan: a message or tool result is longer than the // filter scans (budget.max_scan_chars). ReasonTooLargeToScan = "guardrail_too_large_to_scan" // ReasonScanBudgetExceeded: the request had more text than the filter // scans per request (budget.max_pieces) or in its time (budget.time_ms). ReasonScanBudgetExceeded = "guardrail_scan_budget_exceeded" // the filter fails closed. ReasonUnavailable = "guardrail_unavailable" // ReasonUnscanned: text could not be screened for another reason (the // provider refused it, it could not be decoded). ReasonUnscanned = "guardrail_unscanned" // ReasonUnreadableRequest: the body reads differently to different JSON // parsers (a repeated or case-variant key), so it cannot be screened. ReasonUnreadableRequest = "guardrail_unreadable_request" )
Reason codes a guardrail block answers with (ScriptOutput.ReasonCode). They are stable: clients and runbooks branch on them.
const ( EnvVerdictCacheEntries = "GUARDRAIL_VERDICT_CACHE_ENTRIES" EnvVerdictCacheMaxBytes = "GUARDRAIL_VERDICT_CACHE_MAX_BYTES" // EnvVerdictCacheTTL is how long a verdict is reused; "0" switches the // cache off. A bare integer is read as seconds. EnvVerdictCacheTTL = "GUARDRAIL_VERDICT_CACHE_TTL" )
Environment variables (or AppConf.FilterLimits) that size the cache.
const ( JudgeBenign = "benign" JudgeSuspicious = "suspicious" JudgeAttack = "attack" )
Judge verdicts.
const ( // EnvLocalScanSlots is how many large in-process provider calls run at // once; the default is half of GOMAXPROCS. EnvLocalScanSlots = "GUARDRAIL_LOCAL_SCAN_SLOTS" // EnvLocalScanSmallSlots is how many small ones (at most // budget.single_call_chars of text) run at once, besides those; the // default is a quarter of GOMAXPROCS. EnvLocalScanSmallSlots = "GUARDRAIL_LOCAL_SCAN_SMALL_SLOTS" // EnvLocalScanQueueBytes is how much text one tenant may have waiting // for a slot. EnvLocalScanQueueBytes = "GUARDRAIL_LOCAL_SCAN_QUEUE_BYTES" )
Environment variables (or AppConf.FilterLimits) that size the limiter.
const ( // EnvLocalMaxScanBytes bounds what an in-process provider scans of one // segment: 8 MiB by default (about 2M tokens), 64 KiB to 64 MiB. EnvLocalMaxScanBytes = "GUARDRAIL_LOCAL_MAX_SCAN_BYTES" // EnvLocalScanMsPerMiB is the time per MiB of a call's text an // in-process provider is given beyond timeout_ms before the call is // cancelled and abandoned: 2000 by default, 100 to 60000. It leaves room // for slow hosts while bounding what one call can cost; text the scan // does not finish in time is unscanned. EnvLocalScanMsPerMiB = "GUARDRAIL_LOCAL_SCAN_MS_PER_MIB" )
Environment variables (or AppConf.FilterLimits) that bound in-process scans. The built-in library scans about 70-330 ms per MiB with every category on an M-series laptop (4uc.58); small edges and loaded hosts can be several times slower.
const ( // EnvShadowWorkers is how many shadow evaluations run at once per // process (default 4 per CPU Go uses, at least 8). EnvShadowWorkers = "GUARDRAIL_SHADOW_WORKERS" // EnvShadowQueueBytes bounds the text waiting for a worker (default // 64 MiB); one tenant may hold at most half of it. EnvShadowQueueBytes = "GUARDRAIL_SHADOW_QUEUE_BYTES" )
Environment variables (or AppConf.FilterLimits) that size the pool.
const ( ToolInputScope = "tool_input" ToolOutputScope = "tool_output" )
Filter scopes recorded against compliance events raised by tool filters.
const ( ToolInputBlockedEvent = "tool_input_blocked" ToolOutputBlockedEvent = "tool_output_blocked" )
Event types synthesised when a filter blocks without reporting an event of its own, so that every block is auditable.
const FilterIDKey = "filter_id"
FilterIDKey is the compliance event metadata key holding the ID of the guardrail filter that recorded the event. compliance_events stores only the filter's name, which an administrator can change; the ID lets the UI find the filter (for example to soften its verdict for one app).
const FormatToolCall = "tool_call"
FormatToolCall marks a ScriptInput whose RawInput is the arguments of a tool call the model asked a Studio chat to run, screened by the chat's request guardrails that scan tool calls before the call runs. Context tool_name and tool_call_id name the call, user_goal and system_prompt its goal. The guardrail never rewrites it: block keeps it from running.
const FormatToolResult = "tool_result"
FormatToolResult marks a ScriptInput whose RawInput is the output of a tool the model called (Studio chat), screened by the chat's request guardrails before the model sees it. Context tool_name and tool_call_id name the call.
const JudgeEventType = "guardrail.judge"
JudgeEventType is the compliance event recording one judge opinion.
const (
// JudgeMaxTokens bounds the judge's answer: one small JSON object.
JudgeMaxTokens = 64
)
Judge prompt bounds.
const JudgePromptVersion = "guardrail-judge/2"
JudgePromptVersion names the judge prompt. It is part of the key of a cached opinion, so changing the prompt or the answer format means a new version. guardrail-judge/2 tells the judge to use only the two keys and not to explain: newer models (Claude Sonnet 5.5) otherwise add keys or write a sentence as the reason, which the parser rightly refuses and JudgeMaxTokens cuts off. Wording here moves verdicts, not only the format: "the reason is exactly one of the listed words" made Sonnet 5.5 call a role-play attack benign every time, so any change is re-run on attacks and false positives before it ships (midsommar-clean-9u1j.63).
const OwnerVisibleKey = "owner_visible"
OwnerVisibleKey marks, in a compliance event's metadata, an event the App's owners may see in the portal (evidence.share_with_app_owners).
const ToolBlockedMessage = "blocked by policy"
ToolBlockedMessage is what a caller is told when a governance filter stops a tool call, on every transport. It is deliberately generic and identical for input and output blocks: the filter's own name and reason go to the logs and to the compliance event, so a caller cannot probe the filters to map the governance configuration or learn whether the downstream tool was reached.
Variables ¶
var ReservedEventKeys = []string{FilterIDKey, "alert", "alerts", "exception", "exceptions", "exception_id", "judge", "shadow", "segments", OwnerVisibleKey}
ReservedEventKeys are the compliance event metadata keys only the guardrail runner sets: consumers trust them to describe a guardrail filter's own verdict (the filter to soften, the alert topic to publish, the exception or judge that changed it, whether App owners may see it). A script filter's events are free-form, so these keys are removed from them; a script cannot pass its event off as another filter's. segments is among them because the UI reads segments[].exception and segments[].template, and only top-level keys are removed.
Functions ¶
func AppCapabilityFor ¶ added in v2.3.0
func AppCapabilityFor(input *ScriptInput) guardrails.Capability
AppCapabilityFor is the attested capability of the request's app; "" (acting, by Capability.Effective) when the request has no app, there is no source, or the app is unattested.
func CountAssistantMessages ¶
func CountAssistantMessages(messages []llms.MessageContent) int
CountAssistantMessages counts the number of assistant messages
func CountUserMessages ¶
func CountUserMessages(messages []llms.MessageContent) int
CountUserMessages counts the number of user messages
func DefinitionScreeners ¶ added in v2.3.0
DefinitionScreeners are the filters ScreenToolDefinitions runs: request guardrails that scan tool definitions.
func DrainShadowGuardrails ¶ added in v2.3.0
DrainShadowGuardrails stops the pool taking new evaluations and waits for the queued ones until ctx ends (graceful shutdown); what is still queued then is abandoned. An evaluation queued after it starts a new pool, so a process that embeds and restarts AI Studio keeps shadow filters working.
func EventRecorder ¶ added in v2.3.0
func EventRecorder(filterScope string, appID, userID, llmID uint, vendor, modelName string) func(context.Context, string, *ScriptOutput)
EventRecorder is a ScriptInput.RecordEvents that records a filter's events with the given attribution, as the call site does with the output it is handed. A shadow guardrail records through it when its background evaluation finishes.
func GetAllText ¶
func GetAllText(messages []llms.MessageContent) string
GetAllText concatenates all text content from all messages
func GetAllUserMessages ¶
func GetAllUserMessages(messages []llms.MessageContent) []string
GetAllUserMessages returns all user message contents
func GetLastUserMessage ¶
func GetLastUserMessage(messages []llms.MessageContent) string
GetLastUserMessage extracts the content of the last user message
func GetMessagesByRole ¶
func GetMessagesByRole(messages []llms.MessageContent, role llms.ChatMessageType) []string
GetMessagesByRole returns all messages with the specified role
func GetSystemPrompt ¶
func GetSystemPrompt(messages []llms.MessageContent) string
GetSystemPrompt extracts the content of the system message
func HasImages ¶
func HasImages(messages []llms.MessageContent) bool
HasImages checks if any message contains image content
func MessageCount ¶
func MessageCount(messages []llms.MessageContent) int
MessageCount returns the total number of messages
func OwnerSummary ¶ added in v2.3.0
OwnerSummary is what an App's owner sees of a guardrail compliance event (evidence.share_with_app_owners): the action taken, the reason code the caller got (empty when the request went on) and a sentence naming the cause and where it was. It reads only the metadata fields that carry no text: never an excerpt, a score or a detector.
func RecordComplianceEvents ¶
func RecordComplianceEvents(ctx context.Context, output *ScriptOutput, filterName, filterScope string, appID, userID, llmID uint, vendor, modelName string)
RecordComplianceEvents converts script output compliance events to model events enriched with context from the filter execution site, then records them asynchronously.
func RunToolInputFilters ¶
func RunToolInputFilters( ctx context.Context, filters []models.Filter, service services.ServiceInterface, args ToolCallArgs, id ToolFilterIdentity, ) (ToolCallArgs, *ToolBlock, error)
RunToolInputFilters executes the request-side filters attached to a tool against the arguments bound for it, returning the arguments to actually call the tool with. A non-nil ToolBlock means the tool must not be called.
func ScreenToolDefinitions ¶ added in v2.3.0
func ScreenToolDefinitions(ctx context.Context, filters []*models.Filter, tools []llms.Tool, scope map[string]interface{}, record func(context.Context, string, *ScriptOutput), svc services.ServiceInterface) ([]llms.Tool, error)
ScreenToolDefinitions runs the definition-scanning guardrails among filters over tools, in order, and returns the tools that remain: a flagged tool is dropped (remove) or the whole list refused (*ErrToolDefinitionsBlocked), per each filter's tool_definitions action. scope is the script context (session, user, app ids: the tenant of the verdict cache); record records each filter's compliance events.
func SetCapabilitySource ¶ added in v2.3.0
func SetCapabilitySource(src CapabilitySource)
SetCapabilitySource sets where the guardrails read an app's capability; nil leaves every app unattested.
func SetExceptionSource ¶ added in v2.3.0
func SetExceptionSource(src ExceptionSource)
SetExceptionSource sets where the guardrails read an app's exceptions; nil turns exceptions off.
func SetJudgeCallForTesting ¶ added in v2.3.0
func SetJudgeCallForTesting(fn func(ctx context.Context, llm *models.LLM, model, system, user string) (llmclient.Completion, error)) (restore func())
SetJudgeCallForTesting replaces the LLM call the guardrail judge makes, for tests in other packages (hub and edge integration tests), and clears the judge's opinion cache. It returns the restore function. Not for production use.
func SetPromptTemplateSource ¶ added in v2.3.0
func SetPromptTemplateSource(src PromptTemplateSource)
SetPromptTemplateSource sets where the guardrails read an app's approved templates; nil turns templates off.
Types ¶
type AppExceptions ¶ added in v2.3.0
type AppExceptions = guardrails.AppExceptions
GuardrailException and AppExceptions are the runtime view of an app's exceptions (in guardrails, so the sources need not import this package).
type CapabilitySource ¶ added in v2.3.0
type CapabilitySource interface {
// AppCapability returns the app's attested capability; "" when it has
// none or it cannot be read (treated as acting).
AppCapability(ctx context.Context, appID uint) guardrails.Capability
}
CapabilitySource serves an app's attested guardrail capability, independently of whether it has exceptions: the LLM second opinion's soften mode needs the floor of apps that have none. Studio serves it from the database (services.GuardrailExceptionSource), edges from the snapshot's checksummed capability list.
type ComplianceEventOutput ¶
type ComplianceEventOutput = engine.ComplianceEventOutput
ComplianceEventOutput represents a compliance event reported by a filter script.
type ErrToolDefinitionsBlocked ¶ added in v2.3.0
type ErrToolDefinitionsBlocked struct {
Filter, Message string
}
ErrToolDefinitionsBlocked is a tool list a guardrail refused.
func (*ErrToolDefinitionsBlocked) Error ¶ added in v2.3.0
func (e *ErrToolDefinitionsBlocked) Error() string
type ExceptionSource ¶ added in v2.3.0
type ExceptionSource interface {
// AppExceptions returns the app's approved exceptions; nil for none.
AppExceptions(ctx context.Context, appID uint) *AppExceptions
// Hit records that an exception applied to a request.
Hit(id uint)
}
ExceptionSource serves an app's approved guardrail exceptions. Studio sets one (services.GuardrailExceptionSource); edge gateways set one from the configuration snapshot.
type FilterRunner ¶
type FilterRunner interface {
RunScript(input *ScriptInput, serviceRef services.ServiceInterface) (*ScriptOutput, error)
}
FilterRunner executes one filter, whatever its kind, against the same input and with the same output contract as a script. Every call site that runs filters goes through NewFilterRunner, so a guardrail filter is attached, scoped, streamed, audited and synced to edges exactly like a script filter.
func NewFilterRunner ¶
func NewFilterRunner(filter *models.Filter) FilterRunner
NewFilterRunner returns the runner for a filter: the Tengo script runner for a script filter, the guardrail runner for a guardrail filter.
type GuardrailException ¶ added in v2.3.0
type GuardrailException = guardrails.Exception
GuardrailException and AppExceptions are the runtime view of an app's exceptions (in guardrails, so the sources need not import this package).
type JudgeOpinion ¶ added in v2.3.0
JudgeOpinion is the judge's parsed answer.
func (JudgeOpinion) Benign ¶ added in v2.3.0
func (o JudgeOpinion) Benign() bool
Benign reports whether the judge found the text benign.
type LLMBudgetChecker ¶ added in v2.3.0
LLMBudgetChecker is implemented by a runner service that can check an LLM's own budget (services.Service on the hub, the gateway adapter on an edge). The judge is called only when the judge LLM's budget allows it: a service that cannot say gets no judge calls, so judge spend is never unmetered.
type MessageTool ¶ added in v2.3.0
type MessageTool = engine.MessageTool
MessageTool is the tool behind one tool-result message.
type PromptTemplateSource ¶ added in v2.3.0
type PromptTemplateSource interface {
// ApprovedTemplates returns the app's approved templates; nil for none.
ApprovedTemplates(ctx context.Context, appID uint) []*templates.Template
// Matched records that a template matched a request.
Matched(t *templates.Template)
}
PromptTemplateSource serves an app's approved prompt templates to the request guardrails. Studio sets one (services.PromptTemplateSource).
type ScriptInput ¶
type ScriptInput = engine.ScriptInput
ScriptInput provides rich context to scripts including messages, metadata, and vendor info
type ScriptOutput ¶
type ScriptOutput = engine.ScriptOutput
ScriptOutput represents the result of script execution
type ScriptRunner ¶
type ScriptRunner struct {
// contains filtered or unexported fields
}
ScriptRunner manages script execution with thread safety
func NewScriptRunner ¶
func NewScriptRunner(source []byte) *ScriptRunner
NewScriptRunner creates a new script runner
func (*ScriptRunner) RunScript ¶
func (sr *ScriptRunner) RunScript(input *ScriptInput, serviceRef services.ServiceInterface) (output *ScriptOutput, err error)
RunScript executes a filter script and converts any panic raised by the script engine into an ordinary error.
Tengo panics instead of returning an error for faults it does not model — integer divide by zero being the common one. Filter scripts run on the caller's own goroutine, so an unrecovered panic unwinds through the HTTP handler and takes down the whole process: the AI Studio API server, or a gateway serving every other tenant's traffic. Recovering here means each call site's existing error handling applies instead, so a malformed script costs one failed request rather than the process.
The build-tagged runScript implementations hold the actual behaviour: a pass-through in CE, the Tengo VM in enterprise builds.
type ServiceInterface ¶
type ServiceInterface = services.ServiceInterface
ServiceInterface allows scripts to interact with system services
type ToolBlock ¶
ToolBlock describes a tool call halted by a filter. The reason is for logs and compliance records only - it is deliberately never returned to the caller, which sees a generic refusal.
func RunToolOutputFilters ¶
func RunToolOutputFilters( ctx context.Context, filters []models.Filter, service services.ServiceInterface, body string, id ToolFilterIdentity, ) (string, *ToolBlock, error)
RunToolOutputFilters executes the response-side filters attached to a tool against the body it returned, returning the body to hand back to the caller. A non-nil ToolBlock means the body must not be returned.
type ToolCallArgs ¶
type ToolCallArgs struct {
OperationID string `json:"operation_id"`
Parameters map[string][]string `json:"parameters"`
Payload map[string]interface{} `json:"payload"`
Headers map[string][]string `json:"headers"`
}
ToolCallArgs is the request shape a tool input filter sees, and may rewrite. It mirrors the body of the REST tool endpoint so that REST, MCP and chat tool calls all present scripts with a single contract.
type ToolFilterIdentity ¶
type ToolFilterIdentity struct {
AppID uint
UserID uint
ToolID uint
ToolName string
SessionID string
CallID string
IsChat bool
}
ToolFilterIdentity carries the call context a script can inspect and that compliance events are attributed to. Every field is best effort: the MCP path has no app when the caller authenticated with an OAuth bearer token, and the REST path has no chat session.
Source Files
¶
- block_reason.go
- compliance_recorder.go
- filter_runner.go
- guardrail_breaker.go
- guardrail_cache.go
- guardrail_exceptions.go
- guardrail_judge.go
- guardrail_judge_run.go
- guardrail_judge_soften.go
- guardrail_local.go
- guardrail_scan.go
- guardrail_shadow.go
- guardrail_templates.go
- helpers.go
- interface.go
- judge_testing.go
- owner_summary.go
- run.go
- scripting.go
- tool_definitions.go
- tool_filters.go
- types.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package engine is the hook through which the enterprise edition supplies the filter script runtime, and the types scripts exchange with it.
|
Package engine is the hook through which the enterprise edition supplies the filter script runtime, and the types scripts exchange with it. |