scripting

package
v2.3.0-unstable.7 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2026 License: AGPL-3.0 Imports: 32 Imported by: 2 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

View Source
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"
	// ReasonUnavailable: the provider could not be reached or answer, and
	// 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.

View Source
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.

View Source
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.

View Source
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.

View Source
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.

View Source
const (
	ToolInputScope  = "tool_input"
	ToolOutputScope = "tool_output"
)

Filter scopes recorded against compliance events raised by tool filters.

View Source
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.

View Source
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.

View Source
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.

View Source
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).

View Source
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

This section is empty.

Functions

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

func DefinitionScreeners(filters []*models.Filter) []*models.Filter

DefinitionScreeners are the filters ScreenToolDefinitions runs: request guardrails that scan tool definitions.

func DrainShadowGuardrails added in v2.3.0

func DrainShadowGuardrails(ctx context.Context)

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

func OwnerSummary(eventType string, m map[string]any) (action, code, text string)

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.

Types

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 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 MessageTool added in v2.3.0

type MessageTool = engine.MessageTool

MessageTool is the tool behind one tool-result message.

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

type ToolBlock struct {
	FilterName string
	Reason     string
}

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.

func (*ToolBlock) Error

func (b *ToolBlock) Error() string

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.

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.

Jump to

Keyboard shortcuts

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