Documentation
¶
Overview ¶
Package shrike is the Go SDK for the Shrike platform — AI governance for every AI interaction.
Shrike evaluates every prompt against policy before it reaches the model, deciding in real time what is allowed, blocked, or escalated. The same backend cognitive pipeline that governs a customer-facing chatbot also governs autonomous, tool-using agents.
Drop-in provider wrappers ¶
Wrap your existing LLM client and every prompt is scanned before it is sent. Each wrapper lives in its own subpackage so provider dependencies are only pulled in when you import the one you use:
- github.com/shrike-security/shrike-guard-go/openai (ShrikeOpenAI)
- github.com/shrike-security/shrike-guard-go/anthropic (ShrikeAnthropic)
- github.com/shrike-security/shrike-guard-go/gemini (ShrikeGemini)
A minimal OpenAI example:
client, err := shrikeopenai.NewClient(shrikeopenai.ClientOptions{
OpenAIAPIKey: os.Getenv("OPENAI_API_KEY"),
ShrikeAPIKey: os.Getenv("SHRIKE_API_KEY"),
})
resp, err := client.CreateChatCompletion(ctx, req) // scanned before send
Fail-closed by default ¶
When the Shrike backend cannot decide (timeout, network error, backend 5xx), the SDK blocks the request and returns a *ScanError — the Zero Trust posture. Opt into fail-open only when availability must outrank enforcement, via scanner.WithFailMode(shrike.FailModeOpen).
Other packages ¶
- scanner — the low-level scan client (Scan, ScanSQL, ScanFile, DeclareScope, ScanA2AMessage, ScanAgentCard) plus IsBlocked, the single proceed-vs-refuse decision helper.
- pii — client-side PII redaction and rehydration; PII never leaves the caller's process.
- api — the quota-free sandbox scan client.
SystemPrompt returns the canonical "Working with Shrike" system-prompt block, byte-for-byte identical across the Go, TypeScript, and Python SDKs.
Index ¶
- Constants
- Variables
- func GetPIIPatternCount() int
- func GetRedactionSummary(redactions []RedactionEntry) map[string]int
- func HashContent(content string) string
- func RehydratePII(text string, redactions []RedactionEntry) string
- func Retry(ctx context.Context, cfg RetryConfig, fn func() error) error
- func SyncPIIPatterns(ctx context.Context, opts SyncPIIPatternsOptions) error
- func SystemPrompt() string
- func UpdatePIIPatterns(patterns []PIIPattern)
- type BlockedError
- type CacheStats
- type CircuitBreaker
- type CircuitBreakerConfig
- type CircuitBreakerStats
- type CircuitState
- type Config
- type ConfigError
- type ContentCache
- type FailMode
- type PIIPattern
- type RedactionEntry
- type RedactionResult
- type RetryConfig
- type ScanError
- type ShrikeError
- type SyncPIIPatternsOptions
Constants ¶
const ( // DefaultCacheTTL is the default time-to-live for cached scan results. DefaultCacheTTL = 5 * time.Minute // DefaultCacheMaxSize is the default maximum number of cached entries. DefaultCacheMaxSize = 1000 )
Default cache configuration.
const ( // DefaultScanTimeout is the default timeout for scan requests. DefaultScanTimeout = 10 * time.Second // DefaultEndpoint is the default Shrike API endpoint (uses load balancer for scalability). // Override with WithEndpoint() for VPC deployments. DefaultEndpoint = "https://api.shrikesecurity.com/agent" // SDKName identifies this SDK in API requests. SDKName = "go" // SDKUserAgent is the user agent string for this SDK. SDKUserAgent = "shrike-guard-go" )
Default configuration values.
const DefaultSyncTimeout = 5 * time.Second
DefaultSyncTimeout is how long SyncPIIPatterns waits for the backend before keeping the fallback patterns.
const SystemPromptVersion = "1.0"
SystemPromptVersion is the version string for the canonical block. Integrators can pin behavior against this without pinning the whole SDK.
const Version = "1.2.0"
Version is the SDK version.
Variables ¶
var ( // ErrCircuitOpen is returned when the circuit breaker is in open state. ErrCircuitOpen = errors.New("shrike: circuit breaker is open") // ErrTooManyRequests is returned when too many requests are in-flight // during the half-open state. ErrTooManyRequests = errors.New("shrike: too many requests in half-open state") )
Circuit breaker errors.
var DefaultFailMode = FailModeClosed
DefaultFailMode is the default fail mode. Set to FailModeClosed to match the Shrike platform's Zero Trust contract: when the scanner cannot decide, the request is blocked. Override at the call site with WithFailMode(FailModeOpen) if you need availability over enforcement.
Functions ¶
func GetPIIPatternCount ¶ added in v1.2.0
func GetPIIPatternCount() int
GetPIIPatternCount returns the current number of active PII patterns.
func GetRedactionSummary ¶ added in v1.2.0
func GetRedactionSummary(redactions []RedactionEntry) map[string]int
GetRedactionSummary returns a count of redactions grouped by PII type (no raw PII values). Safe to log.
func HashContent ¶
HashContent computes a SHA256 hash of the content for use as a cache key.
func RehydratePII ¶ added in v1.2.0
func RehydratePII(text string, redactions []RedactionEntry) string
RehydratePII restores indexed tokens in text back to their original PII values using the redaction map returned by RedactPII. All occurrences of each token are replaced (LLMs may repeat tokens in their output).
restored := shrike.RehydratePII(llmOutput, redacted.Redactions)
func Retry ¶
func Retry(ctx context.Context, cfg RetryConfig, fn func() error) error
Retry executes fn with exponential backoff retry. It respects context cancellation and does not retry circuit breaker errors.
func SyncPIIPatterns ¶ added in v1.2.0
func SyncPIIPatterns(ctx context.Context, opts SyncPIIPatternsOptions) error
SyncPIIPatterns fetches canonical PII patterns from the Shrike backend and applies them to the client-side redactor.
Never returns an error that blocks scans — pattern sync is a quality feature. The returned error is informational only; the redactor is guaranteed to remain in a usable state regardless of the outcome.
err := shrike.SyncPIIPatterns(ctx, shrike.SyncPIIPatternsOptions{
Endpoint: "https://api.shrikesecurity.com",
APIKey: os.Getenv("SHRIKE_API_KEY"),
})
func SystemPrompt ¶
func SystemPrompt() string
SystemPrompt returns the canonical "Working with Shrike" system-prompt block. Drop it into your agent's system prompt as the first non-role paragraph:
prompt := "You are a support agent for Acme Corp.\n\n" + shrike.SystemPrompt() + "\n\nWhen customers ask about refunds, first verify..."
func UpdatePIIPatterns ¶ added in v1.2.0
func UpdatePIIPatterns(patterns []PIIPattern)
UpdatePIIPatterns replaces the active PII pattern list (e.g. with a backend-fetched canonical set). Thread-safe.
Types ¶
type BlockedError ¶
type BlockedError struct {
ShrikeError
// ThreatType is the type of threat detected (e.g., 'prompt_injection', 'pii')
ThreatType string
// Confidence is the bucketed confidence level ("high"/"medium"/"low").
// Buckets protect IP by not exposing exact detection thresholds.
Confidence string
// Violations is the sanitized list of specific violations detected.
Violations []map[string]interface{}
}
BlockedError is returned when a prompt is blocked by Shrike security checks.
This error indicates that the prompt was scanned and determined to be unsafe.
func NewBlockedError ¶
func NewBlockedError(message, threatType, confidence string, violations []map[string]interface{}) *BlockedError
NewBlockedError creates a new BlockedError.
func (*BlockedError) Error ¶
func (e *BlockedError) Error() string
type CacheStats ¶
CacheStats provides read-only cache statistics.
type CircuitBreaker ¶
type CircuitBreaker struct {
// contains filtered or unexported fields
}
CircuitBreaker implements the three-state circuit breaker pattern.
func NewCircuitBreaker ¶
func NewCircuitBreaker(cfg CircuitBreakerConfig) *CircuitBreaker
NewCircuitBreaker creates a new circuit breaker with the given config.
func (*CircuitBreaker) Execute ¶
func (cb *CircuitBreaker) Execute(fn func() error) error
Execute runs fn through the circuit breaker.
func (*CircuitBreaker) ExecuteWithContext ¶
func (cb *CircuitBreaker) ExecuteWithContext(ctx context.Context, fn func(context.Context) error) error
ExecuteWithContext runs fn with context through the circuit breaker.
func (*CircuitBreaker) State ¶
func (cb *CircuitBreaker) State() CircuitState
State returns the current circuit breaker state.
func (*CircuitBreaker) Stats ¶
func (cb *CircuitBreaker) Stats() CircuitBreakerStats
Stats returns circuit breaker statistics.
type CircuitBreakerConfig ¶
type CircuitBreakerConfig struct {
// FailureThreshold is the number of consecutive failures before opening.
// Default: 5
FailureThreshold uint32
// SuccessThreshold is the number of successes in half-open before closing.
// Default: 2
SuccessThreshold uint32
// Timeout is the duration the circuit stays open before transitioning
// to half-open. Default: 30s
Timeout time.Duration
// MaxHalfOpenRequests is the max concurrent requests allowed in half-open.
// Default: 3
MaxHalfOpenRequests uint32
// OnStateChange is called when the circuit breaker state changes.
OnStateChange func(from, to CircuitState)
}
CircuitBreakerConfig configures the circuit breaker.
func DefaultCircuitBreakerConfig ¶
func DefaultCircuitBreakerConfig() CircuitBreakerConfig
DefaultCircuitBreakerConfig returns sensible defaults for SDK use.
type CircuitBreakerStats ¶
type CircuitBreakerStats struct {
State CircuitState
FailureCount uint32
SuccessCount uint32
LastStateChange time.Time
LastFailureTime time.Time
}
CircuitBreakerStats provides read-only stats about the circuit breaker.
type CircuitState ¶
type CircuitState int
CircuitState represents the state of the circuit breaker.
const ( // CircuitClosed is the normal operating state. CircuitClosed CircuitState = iota // CircuitOpen is the failing state — requests are rejected. CircuitOpen // CircuitHalfOpen is the recovery testing state. CircuitHalfOpen )
func (CircuitState) String ¶
func (s CircuitState) String() string
type Config ¶
type Config struct {
// APIKey is the Shrike API key for authentication.
APIKey string
// Endpoint is the Shrike API endpoint URL.
Endpoint string
// FailMode defines behavior when scan operations fail.
FailMode FailMode
// ScanTimeout is the timeout for scan requests.
ScanTimeout time.Duration
}
Config holds configuration for Shrike clients.
func DefaultConfig ¶
DefaultConfig returns a configuration with default values.
type ConfigError ¶
type ConfigError struct {
ShrikeError
}
ConfigError is returned when there's a configuration error in the SDK.
func NewConfigError ¶
func NewConfigError(message string) *ConfigError
NewConfigError creates a new ConfigError.
type ContentCache ¶
type ContentCache struct {
// contains filtered or unexported fields
}
ContentCache is a thread-safe LRU cache with TTL expiry. It uses SHA256 content hashes as keys to deduplicate scan requests.
func NewContentCache ¶
func NewContentCache(ttl time.Duration, maxSize int) *ContentCache
NewContentCache creates a new content cache.
func (*ContentCache) Clear ¶
func (c *ContentCache) Clear()
Clear removes all entries from the cache.
func (*ContentCache) Get ¶
func (c *ContentCache) Get(contentHash string) (interface{}, bool)
Get retrieves a cached value by content hash. Returns nil, false if not found or expired.
func (*ContentCache) Set ¶
func (c *ContentCache) Set(contentHash string, value interface{})
Set stores a value in the cache. Evicts the oldest entry if at capacity.
func (*ContentCache) Stats ¶
func (c *ContentCache) Stats() CacheStats
Stats returns cache statistics.
type FailMode ¶
type FailMode string
FailMode defines behavior when scan operations fail (timeout, network error, backend 5xx).
const ( // FailModeOpen allows the request to proceed when the scanner cannot decide. // Use this when availability is strictly prioritized over enforcement // (e.g. non-production experiments, internal tools where outages must not // block users). Note: a fail-open SDK provides no guard during backend // outages, which is when adversarial pressure is highest. FailModeOpen FailMode = "open" // FailModeClosed blocks the request and returns an error when the scanner // cannot decide. This is the Zero Trust posture promised by the Shrike // platform — if the guard cannot evaluate the action, the action does not // proceed. This is the default (see DefaultFailMode). FailModeClosed FailMode = "closed" )
type PIIPattern ¶ added in v1.2.0
type PIIPattern struct {
Name string // e.g. "email"
Regex *regexp.Regexp // compiled detector
Prefix string // e.g. "EMAIL" → [EMAIL_1], [EMAIL_2]
}
PIIPattern is one PII detection rule.
type RedactionEntry ¶ added in v1.2.0
type RedactionEntry struct {
Token string // [EMAIL_1]
Original string // john@acme.com
Type string // email
Position int // char offset in original text
}
RedactionEntry is one redacted span: token in redacted text + original PII value.
type RedactionResult ¶ added in v1.2.0
type RedactionResult struct {
RedactedText string
Redactions []RedactionEntry
PIIDetected bool
RedactionCount int
}
RedactionResult is the outcome of RedactPII.
func RedactPII ¶ added in v1.2.0
func RedactPII(text string) RedactionResult
RedactPII redacts PII from text, replacing matches with indexed tokens ([EMAIL_1], [EMAIL_2], ...) and returning a reversible redaction map.
r := shrike.RedactPII("Email john@acme.com")
// r.RedactedText == "Email [EMAIL_1]"
// r.Redactions[0].Original == "john@acme.com"
type RetryConfig ¶
type RetryConfig struct {
// MaxAttempts is the maximum number of attempts (including the first).
// Default: 3
MaxAttempts int
// InitialBackoff is the delay before the first retry.
// Default: 200ms
InitialBackoff time.Duration
// MaxBackoff is the maximum delay between retries.
// Default: 5s
MaxBackoff time.Duration
// Multiplier is the backoff multiplier between retries.
// Default: 2.0
Multiplier float64
// IsRetryable determines whether an error should be retried.
// Default: retries all errors except ErrCircuitOpen and ErrTooManyRequests
IsRetryable func(error) bool
}
RetryConfig configures retry behavior with exponential backoff.
func DefaultRetryConfig ¶
func DefaultRetryConfig() RetryConfig
DefaultRetryConfig returns sensible defaults.
type ScanError ¶
type ScanError struct {
ShrikeError
}
ScanError is returned when a scan operation fails and fail_mode is 'closed' (the default; fail-closed).
This error is returned when: - The Shrike API times out - A network error occurs - The API returns an unexpected error
When fail_mode is explicitly set to 'open', these errors are silently handled and the request is allowed to proceed (use this only when availability must outrank enforcement).
func NewScanError ¶
NewScanError creates a new ScanError.
type ShrikeError ¶
ShrikeError is the base error type for all Shrike SDK errors.
func (*ShrikeError) Error ¶
func (e *ShrikeError) Error() string
type SyncPIIPatternsOptions ¶ added in v1.2.0
type SyncPIIPatternsOptions struct {
// Endpoint is the Shrike backend base URL (e.g. https://api.shrikesecurity.com).
// SyncPIIPatterns appends /api/pii/patterns.
Endpoint string
// APIKey is sent as "Authorization: Bearer <key>" when non-empty.
// The endpoint is currently unauthenticated, but sending the key keeps
// the client forward-compatible.
APIKey string
// Timeout is the HTTP timeout. Zero falls back to DefaultSyncTimeout.
Timeout time.Duration
// HTTPClient lets callers inject a custom *http.Client (for testing,
// custom transports, instrumented round-trippers). Zero falls back to
// a client with the configured Timeout.
HTTPClient *http.Client
}
SyncPIIPatternsOptions configures a SyncPIIPatterns call.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package anthropic provides a Shrike-protected Anthropic client wrapper.
|
Package anthropic provides a Shrike-protected Anthropic client wrapper. |
|
Package api provides API clients for Shrike backend services.
|
Package api provides API clients for Shrike backend services. |
|
examples
|
|
|
openai
command
Example of using ShrikeOpenAI client.
|
Example of using ShrikeOpenAI client. |
|
Package gemini provides a Shrike-protected Google Gemini client wrapper.
|
Package gemini provides a Shrike-protected Google Gemini client wrapper. |
|
internal
|
|
|
testutil
Package testutil provides testing utilities for the Shrike SDK.
|
Package testutil provides testing utilities for the Shrike SDK. |
|
Package openai provides a Shrike-protected OpenAI client wrapper.
|
Package openai provides a Shrike-protected OpenAI client wrapper. |
|
Package pii provides client-side PII redaction and rehydration.
|
Package pii provides client-side PII redaction and rehydration. |
|
Package scanner provides the HTTP client for the Shrike scan API.
|
Package scanner provides the HTTP client for the Shrike scan API. |