interceptors

package
v0.0.13 Latest Latest
Warning

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

Go to latest
Published: Dec 7, 2025 License: MIT Imports: 19 Imported by: 0

README

Interceptors

This package provides a comprehensive set of interceptors for dspy-go modules, agents, and tools. Interceptors follow the middleware pattern, allowing you to add cross-cutting concerns like logging, caching, security, and structured output parsing without modifying your core logic.

Architecture

Interceptors in dspy-go follow the gRPC interceptor pattern, providing a clean and composable way to add functionality to module execution. Each interceptor can:

  • Inspect and modify inputs before execution
  • Inspect and modify outputs after execution
  • Handle errors and implement fallback logic
  • Collect metrics and perform logging
  • Implement security policies

Available Interceptors

Standard Interceptors (standard.go)

Logging Interceptors

  • LoggingModuleInterceptor() - Logs module execution with timing
  • LoggingAgentInterceptor() - Logs agent execution with timing
  • LoggingToolInterceptor() - Logs tool execution with arguments

Tracing Interceptors

  • TracingModuleInterceptor() - Adds distributed tracing spans
  • TracingAgentInterceptor() - Traces agent execution
  • TracingToolInterceptor() - Traces tool calls

Metrics Interceptors

  • MetricsModuleInterceptor() - Collects performance metrics
  • MetricsAgentInterceptor() - Tracks agent metrics
  • MetricsToolInterceptor() - Monitors tool usage
Performance Interceptors (performance.go)

Caching

  • CachingModuleInterceptor(cache, ttl) - Caches module results
  • CachingToolInterceptor(cache, ttl) - Caches tool results
  • MemoryCache - In-memory cache implementation with TTL

Timeouts

  • TimeoutModuleInterceptor(duration) - Enforces execution timeouts
  • TimeoutAgentInterceptor(duration) - Agent timeout protection
  • TimeoutToolInterceptor(duration) - Tool execution limits

Circuit Breakers

  • CircuitBreakerModuleInterceptor(cb) - Prevents cascade failures
  • CircuitBreakerAgentInterceptor(cb) - Agent circuit protection
  • CircuitBreakerToolInterceptor(cb) - Tool failure isolation

Retry Logic

  • RetryModuleInterceptor(config) - Retry failed executions
  • RetryAgentInterceptor(config) - Agent retry with backoff
  • RetryToolInterceptor(config) - Tool call retries
Security Interceptors (security.go)

Rate Limiting

  • RateLimitingAgentInterceptor(limit, window) - Agent rate limits
  • RateLimitingToolInterceptor(limit, window) - Tool call limits

Input Validation

  • ValidationModuleInterceptor(config) - Validates module inputs
  • ValidationAgentInterceptor(config) - Agent input validation
  • ValidationToolInterceptor(config) - Tool argument validation

Authorization

  • AuthorizationInterceptor - Policy-based access control
  • ModuleAuthorizationInterceptor() - Module access control
  • AgentAuthorizationInterceptor() - Agent authorization
  • ToolAuthorizationInterceptor() - Tool permission checks

Input Sanitization

  • SanitizingModuleInterceptor() - Sanitizes module inputs
  • SanitizingAgentInterceptor() - Agent input sanitization
  • SanitizingToolInterceptor() - Tool argument sanitization
XML Interceptors (xml.go, xml_config.go)

Structured Output Processing

  • XMLFormatModuleInterceptor(config) - Injects XML formatting instructions
  • XMLParseModuleInterceptor(config) - Parses XML responses to structured data
  • XMLModuleInterceptor(config) - Combined format + parse interceptor

Configuration Options

  • DefaultXMLConfig() - Balanced settings for general use
  • StrictXMLConfig() - Strict parsing, no fallback
  • FlexibleXMLConfig() - Allows missing fields, has fallback
  • PerformantXMLConfig() - Optimized for speed
  • SecureXMLConfig() - Enhanced security restrictions

Helper Functions

  • ApplyXMLInterceptors(module, config) - Apply to InterceptableModule
  • CreateXMLInterceptorChain(config, additional...) - Build interceptor chains

Usage Patterns

Basic Interceptor Application
import "github.com/darwishdev/dspy-go/pkg/interceptors"

// Apply single interceptor
module.SetInterceptors([]core.ModuleInterceptor{
    interceptors.LoggingModuleInterceptor(),
})

// Apply multiple interceptors
module.SetInterceptors([]core.ModuleInterceptor{
    interceptors.LoggingModuleInterceptor(),
    interceptors.MetricsModuleInterceptor(),
    interceptors.XMLModuleInterceptor(interceptors.DefaultXMLConfig()),
})
Interceptor Chaining
// Build comprehensive processing pipeline
chain := []core.ModuleInterceptor{
    interceptors.LoggingModuleInterceptor(),                    // Log requests
    interceptors.ValidationModuleInterceptor(validationConfig), // Validate inputs
    interceptors.RetryModuleInterceptor(retryConfig),          // Retry on failure
    interceptors.XMLFormatModuleInterceptor(xmlConfig),        // Format request
    interceptors.CachingModuleInterceptor(cache, 5*time.Minute), // Cache results
    interceptors.XMLParseModuleInterceptor(xmlConfig),         // Parse response
    interceptors.MetricsModuleInterceptor(),                   // Collect metrics
}

module.SetInterceptors(chain)
XML Structured Output
// Configure XML interceptor for structured responses
xmlConfig := interceptors.DefaultXMLConfig().
    WithStrictParsing(true).
    WithCustomTag("user_query", "query").
    WithTypeHints(true)

// Apply XML interceptors
xmlInterceptor := interceptors.XMLModuleInterceptor(xmlConfig)
module.SetInterceptors([]core.ModuleInterceptor{xmlInterceptor})

// Module will automatically:
// 1. Inject XML formatting instructions into prompts
// 2. Parse XML responses into structured fields
Performance Optimization
// Create memory cache
cache := interceptors.NewMemoryCache()

// Create circuit breaker
cb := interceptors.NewCircuitBreaker(5, 30*time.Second, 10)

// Build performance-focused chain
perfChain := []core.ModuleInterceptor{
    interceptors.CachingModuleInterceptor(cache, 10*time.Minute),
    interceptors.TimeoutModuleInterceptor(30*time.Second),
    interceptors.CircuitBreakerModuleInterceptor(cb),
    interceptors.RetryModuleInterceptor(interceptors.RetryConfig{
        MaxAttempts: 3,
        Delay:       100*time.Millisecond,
        Backoff:     2.0,
    }),
}

module.SetInterceptors(perfChain)
Security Configuration
// Configure validation
validationConfig := interceptors.DefaultValidationConfig()
validationConfig.MaxInputSize = 1024 * 1024  // 1MB limit
validationConfig.ForbiddenPatterns = append(
    validationConfig.ForbiddenPatterns,
    `(?i)custom_dangerous_pattern`,
)

// Configure authorization
authInterceptor := interceptors.NewAuthorizationInterceptor()
authInterceptor.SetPolicy("sensitive_module", interceptors.AuthorizationPolicy{
    RequiredRoles: []string{"admin", "power_user"},
    RequireAuth:   true,
})

// Build security chain
secChain := []core.ModuleInterceptor{
    authInterceptor.ModuleAuthorizationInterceptor(),
    interceptors.ValidationModuleInterceptor(validationConfig),
    interceptors.SanitizingModuleInterceptor(),
    interceptors.RateLimitingAgentInterceptor(100, time.Minute),
}

module.SetInterceptors(secChain)

Configuration Examples

XML Configuration
// Custom XML configuration
xmlConfig := interceptors.DefaultXMLConfig().
    WithStrictParsing(false).           // Allow missing fields
    WithFallback(true).                 // Enable text fallback
    WithValidation(true).               // Validate XML syntax
    WithMaxDepth(10).                   // Limit nesting depth
    WithMaxSize(1024*1024).            // 1MB size limit
    WithTimeout(30*time.Second).        // Parse timeout
    WithCustomTag("question", "q").     // Custom tag mapping
    WithTypeHints(true).               // Include type hints
    WithPreserveWhitespace(false)      // Trim whitespace
Retry Configuration
retryConfig := interceptors.RetryConfig{
    MaxAttempts: 3,                    // Retry up to 3 times
    Delay:       100*time.Millisecond, // Initial delay
    MaxBackoff:  5*time.Second,        // Maximum delay
    Backoff:     2.0,                  // Exponential backoff
}
Validation Configuration
validationConfig := interceptors.ValidationConfig{
    MaxInputSize:     10*1024*1024,    // 10MB limit
    MaxStringLength:  100000,          // 100KB per string
    ForbiddenPatterns: []string{       // Security patterns
        `(?i)<script[^>]*>.*?</script>`,
        `(?i)javascript:`,
        `\$\{.*\}`,
    },
    RequiredFields: []string{"user_id"}, // Required fields
    AllowHTML:      false,               // Block HTML content
}

Best Practices

1. Interceptor Ordering

Order interceptors carefully for correct behavior:

// Recommended order:
[]core.ModuleInterceptor{
    // 1. Security (first line of defense)
    authInterceptor,
    validationInterceptor,
    sanitizationInterceptor,

    // 2. Observability
    loggingInterceptor,
    tracingInterceptor,

    // 3. Reliability
    retryInterceptor,
    circuitBreakerInterceptor,

    // 4. Performance
    cachingInterceptor,
    timeoutInterceptor,

    // 5. Content Processing
    xmlFormatInterceptor,
    xmlParseInterceptor,

    // 6. Metrics (capture final state)
    metricsInterceptor,
}
2. Error Handling
// Use fallback-enabled configurations in production
xmlConfig := interceptors.FlexibleXMLConfig() // Has fallback

// Implement graceful degradation
validationConfig := interceptors.DefaultValidationConfig()
validationConfig.ForbiddenPatterns = []string{} // Start permissive
3. Performance Monitoring
// Always include metrics for production
chain := []core.ModuleInterceptor{
    interceptors.MetricsModuleInterceptor(),
    // ... other interceptors
}

// Use caching for expensive operations
cache := interceptors.NewMemoryCache()
cachingInterceptor := interceptors.CachingModuleInterceptor(cache, 10*time.Minute)
4. Security Layers
// Implement defense in depth
securityChain := []core.ModuleInterceptor{
    authInterceptor,      // Authentication/authorization
    validationInterceptor, // Input validation
    sanitizationInterceptor, // Input sanitization
    rateLimitInterceptor, // Rate limiting
}

Performance Characteristics

Based on benchmarks:

  • XML Parsing: ~3,663 ns/op (327K ops/sec)
  • Full XML Pipeline: ~5,727 ns/op (209K ops/sec)
  • Memory Usage: ~3.5KB/op for parsing, ~7.8KB/op for full pipeline
  • Caching: Near-zero overhead for cache hits
  • Logging: Minimal overhead with structured logging

Extension Points

The interceptor system is designed for extensibility:

Custom Interceptors
func CustomModuleInterceptor(config CustomConfig) core.ModuleInterceptor {
    return func(ctx context.Context, inputs map[string]any, info *core.ModuleInfo, handler core.ModuleHandler, opts ...core.Option) (map[string]any, error) {
        // Pre-processing
        modifiedInputs := preprocessInputs(inputs, config)

        // Execute
        outputs, err := handler(ctx, modifiedInputs, opts...)

        // Post-processing
        finalOutputs := postprocessOutputs(outputs, config)

        return finalOutputs, err
    }
}
Custom Configurations
type CustomConfig struct {
    Setting1 string
    Setting2 int
    // ... other settings
}

func DefaultCustomConfig() CustomConfig {
    return CustomConfig{
        Setting1: "default",
        Setting2: 42,
    }
}

This interceptor system provides a powerful, composable foundation for building robust, secure, and high-performance language model applications with dspy-go.

Documentation

Overview

Package interceptors provides middleware components for dspy-go modules and agents.

Package interceptors provides middleware components for dspy-go modules and agents.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ApplyXMLInterceptors

func ApplyXMLInterceptors(module core.Module, config XMLConfig) error

ApplyXMLInterceptors applies XML format and parse interceptors to a module. This is a convenience function for modules that implement InterceptableModule.

func CachingModuleInterceptor

func CachingModuleInterceptor(cache Cache, ttl time.Duration) core.ModuleInterceptor

CachingModuleInterceptor creates an interceptor that caches module results. It uses input data and module info to generate cache keys.

func CachingToolInterceptor

func CachingToolInterceptor(cache Cache, ttl time.Duration) core.ToolInterceptor

CachingToolInterceptor creates an interceptor that caches tool results.

func ChainOfThoughtStructuredInterceptor

func ChainOfThoughtStructuredInterceptor(config ChainOfThoughtStructuredConfig) core.ModuleInterceptor

ChainOfThoughtStructuredInterceptor creates an interceptor specifically for ChainOfThought. It ensures the reasoning field is always included in the output schema.

func CircuitBreakerAgentInterceptor

func CircuitBreakerAgentInterceptor(cb *CircuitBreaker) core.AgentInterceptor

CircuitBreakerAgentInterceptor creates an interceptor that implements circuit breaker pattern for agents.

func CircuitBreakerModuleInterceptor

func CircuitBreakerModuleInterceptor(cb *CircuitBreaker) core.ModuleInterceptor

CircuitBreakerModuleInterceptor creates an interceptor that implements circuit breaker pattern for modules.

func CircuitBreakerToolInterceptor

func CircuitBreakerToolInterceptor(cb *CircuitBreaker) core.ToolInterceptor

CircuitBreakerToolInterceptor creates an interceptor that implements circuit breaker pattern for tools.

func CreateXMLInterceptorChain

func CreateXMLInterceptorChain(config XMLConfig, additionalInterceptors ...core.ModuleInterceptor) []core.ModuleInterceptor

CreateXMLInterceptorChain creates a chain of XML and other interceptors.

func LoggingAgentInterceptor

func LoggingAgentInterceptor() core.AgentInterceptor

LoggingAgentInterceptor creates an interceptor that logs agent execution. It logs before and after agent execution with timing information.

func LoggingModuleInterceptor

func LoggingModuleInterceptor() core.ModuleInterceptor

LoggingModuleInterceptor creates an interceptor that logs module execution. It logs before and after module execution with timing information.

func LoggingToolInterceptor

func LoggingToolInterceptor() core.ToolInterceptor

LoggingToolInterceptor creates an interceptor that logs tool execution. It logs before and after tool execution with timing and argument information.

func MetricsAgentInterceptor

func MetricsAgentInterceptor() core.AgentInterceptor

MetricsAgentInterceptor creates an interceptor that collects performance metrics for agents.

func MetricsModuleInterceptor

func MetricsModuleInterceptor() core.ModuleInterceptor

MetricsModuleInterceptor creates an interceptor that collects performance metrics for modules. It tracks execution duration, success/failure rates, and token usage.

func MetricsToolInterceptor

func MetricsToolInterceptor() core.ToolInterceptor

MetricsToolInterceptor creates an interceptor that collects performance metrics for tools.

func NativeFunctionCallingInterceptor

func NativeFunctionCallingInterceptor(config FunctionCallingConfig) core.ModuleInterceptor

NativeFunctionCallingInterceptor creates a module interceptor that uses native LLM function calling instead of text-based action parsing.

This interceptor transforms the ReAct pattern by: 1. Converting tools from the registry into LLM function schemas 2. Using GenerateWithFunctions instead of Generate 3. Returning structured tool calls that bypass XML/text parsing

Benefits over text-based parsing: - No hallucinated observations (LLM only returns one tool call) - Strongly typed arguments from the LLM - Provider-optimized tool selection - Eliminates parsing errors and ambiguity

Usage:

config := interceptors.FunctionCallingConfig{
    ToolRegistry:      registry,
    IncludeFinishTool: true,
}
interceptor := interceptors.NativeFunctionCallingInterceptor(config)
react.Predict.SetInterceptors([]core.ModuleInterceptor{interceptor})

func ParseXMLAction

func ParseXMLAction(actionStr string, config XMLConfig) (toolName string, arguments map[string]interface{}, err error)

ParseXMLAction parses an action string from ReAct module into tool name and arguments. This provides a centralized, robust XML parsing implementation for action strings. It handles security limits, entity escaping, and fallback logic.

func RateLimitingAgentInterceptor

func RateLimitingAgentInterceptor(limit int, window time.Duration) core.AgentInterceptor

RateLimitingAgentInterceptor creates an interceptor that enforces rate limiting on agent execution. It limits the number of agent executions per time window per agent ID.

func RateLimitingToolInterceptor

func RateLimitingToolInterceptor(limit int, window time.Duration) core.ToolInterceptor

RateLimitingToolInterceptor creates an interceptor that enforces rate limiting on tool execution. It limits the number of tool calls per time window per tool name.

func RetryAgentInterceptor

func RetryAgentInterceptor(config RetryConfig) core.AgentInterceptor

RetryAgentInterceptor creates an interceptor that retries failed agent executions.

func RetryModuleInterceptor

func RetryModuleInterceptor(config RetryConfig) core.ModuleInterceptor

RetryModuleInterceptor creates an interceptor that retries failed module executions.

func RetryToolInterceptor

func RetryToolInterceptor(config RetryConfig) core.ToolInterceptor

RetryToolInterceptor creates an interceptor that retries failed tool executions.

func SanitizingAgentInterceptor

func SanitizingAgentInterceptor() core.AgentInterceptor

SanitizingAgentInterceptor creates an interceptor that sanitizes agent inputs.

func SanitizingModuleInterceptor

func SanitizingModuleInterceptor() core.ModuleInterceptor

SanitizingModuleInterceptor creates an interceptor that sanitizes module inputs.

func SanitizingToolInterceptor

func SanitizingToolInterceptor() core.ToolInterceptor

SanitizingToolInterceptor creates an interceptor that sanitizes tool arguments.

func StructuredOutputInterceptor

func StructuredOutputInterceptor(config StructuredOutputConfig) core.ModuleInterceptor

StructuredOutputInterceptor creates a module interceptor that uses native JSON output capabilities instead of text-based parsing.

This interceptor transforms the Predict module by: 1. Converting output signature fields into a JSON schema 2. Using GenerateWithJSON instead of Generate + parsing 3. Mapping the JSON response directly to output fields

Benefits over text-based parsing: - No parsing errors from malformed prefixes - Strongly typed output from the LLM - Works with any signature without custom prefix configuration - More reliable extraction of multiple output fields

Usage:

config := interceptors.DefaultStructuredOutputConfig()
interceptor := interceptors.StructuredOutputInterceptor(config)
predict.SetInterceptors([]core.ModuleInterceptor{interceptor})

Or use the convenience method on Predict:

predict := modules.NewPredict(signature).WithStructuredOutput()

func TimeoutAgentInterceptor

func TimeoutAgentInterceptor(timeout time.Duration) core.AgentInterceptor

TimeoutAgentInterceptor creates an interceptor that enforces timeouts on agent execution.

func TimeoutModuleInterceptor

func TimeoutModuleInterceptor(timeout time.Duration) core.ModuleInterceptor

TimeoutModuleInterceptor creates an interceptor that enforces timeouts on module execution.

func TimeoutToolInterceptor

func TimeoutToolInterceptor(timeout time.Duration) core.ToolInterceptor

TimeoutToolInterceptor creates an interceptor that enforces timeouts on tool execution.

func TracingAgentInterceptor

func TracingAgentInterceptor() core.AgentInterceptor

TracingAgentInterceptor creates an interceptor that adds distributed tracing to agent execution.

func TracingModuleInterceptor

func TracingModuleInterceptor() core.ModuleInterceptor

TracingModuleInterceptor creates an interceptor that adds distributed tracing to module execution. It integrates with the existing span system in core.ExecutionState.

func TracingToolInterceptor

func TracingToolInterceptor() core.ToolInterceptor

TracingToolInterceptor creates an interceptor that adds distributed tracing to tool execution.

func ValidationAgentInterceptor

func ValidationAgentInterceptor(config ValidationConfig) core.AgentInterceptor

ValidationAgentInterceptor creates an interceptor that validates agent inputs.

func ValidationModuleInterceptor

func ValidationModuleInterceptor(config ValidationConfig) core.ModuleInterceptor

ValidationModuleInterceptor creates an interceptor that validates module inputs. It checks input size, string lengths, and forbidden patterns.

func ValidationToolInterceptor

func ValidationToolInterceptor(config ValidationConfig) core.ToolInterceptor

ValidationToolInterceptor creates an interceptor that validates tool arguments.

func WithAuthorizationContext

func WithAuthorizationContext(ctx context.Context, authCtx *AuthorizationContext) context.Context

WithAuthorizationContext adds authorization context to the request context.

func XMLFormatModuleInterceptor

func XMLFormatModuleInterceptor(config XMLConfig) core.ModuleInterceptor

XMLFormatModuleInterceptor modifies module inputs to request XML-formatted responses. This interceptor operates on the input side, injecting XML formatting instructions into the prompt to guide the LLM to produce structured XML output.

func XMLModuleInterceptor

func XMLModuleInterceptor(config XMLConfig) core.ModuleInterceptor

XMLModuleInterceptor creates a combined interceptor that both formats requests and parses responses. This is a convenience function that chains the format and parse interceptors.

func XMLParseModuleInterceptor

func XMLParseModuleInterceptor(config XMLConfig) core.ModuleInterceptor

XMLParseModuleInterceptor extracts structured data from XML responses. This interceptor operates on the output side, parsing XML-formatted LLM responses into structured field values according to the module's signature.

Types

type AuthorizationContext

type AuthorizationContext struct {
	UserID      string
	Roles       []string
	Permissions []string
	Scopes      []string
	APIKey      string
}

AuthorizationContext holds authorization information.

type AuthorizationInterceptor

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

AuthorizationInterceptor creates authorization interceptors.

func NewAuthorizationInterceptor

func NewAuthorizationInterceptor() *AuthorizationInterceptor

NewAuthorizationInterceptor creates a new authorization interceptor.

func (*AuthorizationInterceptor) AgentAuthorizationInterceptor

func (ai *AuthorizationInterceptor) AgentAuthorizationInterceptor() core.AgentInterceptor

AgentAuthorizationInterceptor creates an interceptor that enforces authorization on agents.

func (*AuthorizationInterceptor) ModuleAuthorizationInterceptor

func (ai *AuthorizationInterceptor) ModuleAuthorizationInterceptor() core.ModuleInterceptor

ModuleAuthorizationInterceptor creates an interceptor that enforces authorization on modules.

func (*AuthorizationInterceptor) SetPolicy

func (ai *AuthorizationInterceptor) SetPolicy(resource string, policy AuthorizationPolicy)

SetPolicy sets an authorization policy for a specific resource.

func (*AuthorizationInterceptor) ToolAuthorizationInterceptor

func (ai *AuthorizationInterceptor) ToolAuthorizationInterceptor() core.ToolInterceptor

ToolAuthorizationInterceptor creates an interceptor that enforces authorization on tools.

type AuthorizationPolicy

type AuthorizationPolicy struct {
	RequiredRoles       []string
	RequiredPermissions []string
	RequiredScopes      []string
	RequireAuth         bool
	CustomRules         map[string]string
	AllowedModules      []string
	AllowedAgents       []string
	AllowedTools        []string
}

AuthorizationPolicy defines what operations are allowed.

type Cache

type Cache interface {
	Get(key string) (interface{}, bool)
	Set(key string, value interface{}, ttl time.Duration)
	Delete(key string)
	Clear()
}

Cache interface allows for different caching implementations.

type CacheEntry

type CacheEntry struct {
	Result    interface{}
	ExpiresAt time.Time
}

CacheEntry represents a cached result with expiration.

type ChainOfThoughtStructuredConfig

type ChainOfThoughtStructuredConfig struct {
	StructuredOutputConfig

	// ReasoningFieldName is the name of the field containing the reasoning.
	// Defaults to "reasoning" if empty.
	ReasoningFieldName string

	// IncludeReasoningInOutput determines if reasoning should be in the final output.
	IncludeReasoningInOutput bool
}

ChainOfThoughtStructuredConfig extends StructuredOutputConfig for CoT-specific settings.

func DefaultChainOfThoughtStructuredConfig

func DefaultChainOfThoughtStructuredConfig() ChainOfThoughtStructuredConfig

DefaultChainOfThoughtStructuredConfig returns defaults for ChainOfThought.

type CircuitBreaker

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

CircuitBreaker implements the circuit breaker pattern.

func NewCircuitBreaker

func NewCircuitBreaker(failureThreshold int, resetTimeout time.Duration, requestThreshold int) *CircuitBreaker

NewCircuitBreaker creates a new circuit breaker.

func (*CircuitBreaker) Allow

func (cb *CircuitBreaker) Allow() bool

Allow checks if a request should be allowed through the circuit breaker.

func (*CircuitBreaker) GetState

func (cb *CircuitBreaker) GetState() CircuitState

GetState returns the current circuit breaker state.

func (*CircuitBreaker) RecordFailure

func (cb *CircuitBreaker) RecordFailure()

RecordFailure records a failed request.

func (*CircuitBreaker) RecordSuccess

func (cb *CircuitBreaker) RecordSuccess()

RecordSuccess records a successful request.

type CircuitState

type CircuitState int

CircuitState represents the current state of the circuit breaker.

const (
	CircuitClosed CircuitState = iota
	CircuitOpen
	CircuitHalfOpen
)

type FunctionCallingConfig

type FunctionCallingConfig struct {
	// ToolRegistry provides the available tools for function calling.
	ToolRegistry *tools.InMemoryToolRegistry

	// StrictMode requires the LLM to always call a function (no free-form text).
	// When false, the LLM may respond with text instead of a function call.
	StrictMode bool

	// IncludeFinishTool adds a special "Finish" tool that signals task completion.
	// This is essential for ReAct loops to know when to stop.
	IncludeFinishTool bool

	// FinishToolDescription customizes the Finish tool's description.
	// Defaults to a standard description if empty.
	FinishToolDescription string
}

FunctionCallingConfig configures the native function calling interceptor.

func DefaultFunctionCallingConfig

func DefaultFunctionCallingConfig() FunctionCallingConfig

DefaultFunctionCallingConfig returns sensible defaults for ReAct usage.

type FunctionCallingReActAdapter

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

FunctionCallingReActAdapter wraps the ReAct module to use native function calling. This is a higher-level helper that configures everything automatically.

func NewFunctionCallingReActAdapter

func NewFunctionCallingReActAdapter(registry *tools.InMemoryToolRegistry) *FunctionCallingReActAdapter

NewFunctionCallingReActAdapter creates an adapter that enables native function calling for ReAct.

func (*FunctionCallingReActAdapter) GetInterceptor

GetInterceptor returns the configured module interceptor.

func (*FunctionCallingReActAdapter) WithCustomFinishDescription

func (a *FunctionCallingReActAdapter) WithCustomFinishDescription(description string) *FunctionCallingReActAdapter

WithCustomFinishDescription sets a custom description for the Finish tool.

func (*FunctionCallingReActAdapter) WithStrictMode

WithStrictMode enables strict mode where the LLM must always call a function.

type MemoryCache

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

MemoryCache implements an in-memory cache with TTL support.

func NewMemoryCache

func NewMemoryCache() *MemoryCache

NewMemoryCache creates a new in-memory cache.

func (*MemoryCache) Clear

func (mc *MemoryCache) Clear()

Clear removes all items from the cache.

func (*MemoryCache) Delete

func (mc *MemoryCache) Delete(key string)

Delete removes a value from the cache.

func (*MemoryCache) Get

func (mc *MemoryCache) Get(key string) (interface{}, bool)

Get retrieves a value from the cache.

func (*MemoryCache) Set

func (mc *MemoryCache) Set(key string, value interface{}, ttl time.Duration)

Set stores a value in the cache with TTL.

func (*MemoryCache) Stop

func (mc *MemoryCache) Stop()

Stop terminates the cleanup goroutine and marks cache as stopped.

type ParsedSignature

type ParsedSignature struct {
	FieldMap    map[string]core.OutputField
	TagMap      map[string]string // tag -> field name
	RequiredSet map[string]bool
}

ParsedSignature caches parsing information for a signature.

type RateLimiter

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

RateLimiter tracks request rates per key (agent, tool, etc.).

func NewRateLimiter

func NewRateLimiter(limit int, window time.Duration) *RateLimiter

NewRateLimiter creates a new rate limiter with specified limit and time window.

func (*RateLimiter) Allow

func (rl *RateLimiter) Allow(key string) bool

Allow checks if a request should be allowed for the given key.

type RetryConfig

type RetryConfig struct {
	MaxAttempts int
	Delay       time.Duration
	MaxBackoff  time.Duration // Maximum delay between retries
	Backoff     float64       // Multiplier for delay between retries
}

RetryConfig holds configuration for retry operations.

type StructuredOutputAdapter

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

StructuredOutputAdapter provides a high-level interface for enabling structured output.

func NewStructuredOutputAdapter

func NewStructuredOutputAdapter() *StructuredOutputAdapter

NewStructuredOutputAdapter creates an adapter for structured JSON output.

func (*StructuredOutputAdapter) GetInterceptor

func (a *StructuredOutputAdapter) GetInterceptor() core.ModuleInterceptor

GetInterceptor returns the configured module interceptor.

func (*StructuredOutputAdapter) WithCustomInstructions

func (a *StructuredOutputAdapter) WithCustomInstructions(instructions string) *StructuredOutputAdapter

WithCustomInstructions adds custom instructions to the prompt.

func (*StructuredOutputAdapter) WithStrictSchema

func (a *StructuredOutputAdapter) WithStrictSchema() *StructuredOutputAdapter

WithStrictSchema enables strict schema validation.

func (*StructuredOutputAdapter) WithoutDescriptions

func (a *StructuredOutputAdapter) WithoutDescriptions() *StructuredOutputAdapter

WithoutDescriptions disables field descriptions in the schema.

type StructuredOutputConfig

type StructuredOutputConfig struct {
	// StrictSchema requires all output fields to be present in the response.
	// When false, missing fields are allowed and will be empty in the output.
	StrictSchema bool

	// IncludeDescriptions adds field descriptions to the JSON schema.
	// This helps the LLM understand what each field should contain.
	IncludeDescriptions bool

	// CustomInstructions are prepended to the prompt to guide JSON generation.
	CustomInstructions string
}

StructuredOutputConfig configures the structured output interceptor.

func DefaultStructuredOutputConfig

func DefaultStructuredOutputConfig() StructuredOutputConfig

DefaultStructuredOutputConfig returns sensible defaults.

type ValidationConfig

type ValidationConfig struct {
	MaxInputSize      int      // Maximum size of input data in bytes
	MaxStringLength   int      // Maximum length of string values
	ForbiddenPatterns []string // Regex patterns that should not be present
	RequiredFields    []string // Fields that must be present
	AllowHTML         bool     // Whether HTML is allowed in strings
}

ValidationConfig holds configuration for input validation.

func DefaultValidationConfig

func DefaultValidationConfig() ValidationConfig

DefaultValidationConfig returns a secure default validation configuration.

type XMLConfig

type XMLConfig struct {
	// StrictParsing requires all output fields to be present in XML
	StrictParsing bool

	// FallbackToText enables text fallback for malformed XML
	FallbackToText bool

	// ValidateXML performs XML syntax validation before parsing
	ValidateXML bool

	// MaxDepth limits XML nesting depth for security (default: 10)
	MaxDepth int

	// MaxSize limits XML response size in bytes (default: 1MB)
	MaxSize int64

	// Timeout for XML parsing operations
	ParseTimeout time.Duration

	// CustomTags allows overriding default XML tag names for fields
	CustomTags map[string]string

	// IncludeTypeHints adds type information to XML instructions
	IncludeTypeHints bool

	// PreserveWhitespace maintains whitespace in XML content
	PreserveWhitespace bool
}

XMLConfig holds configuration for XML interceptors.

func DefaultXMLConfig

func DefaultXMLConfig() XMLConfig

DefaultXMLConfig returns XMLConfig with sensible defaults.

func FlexibleXMLConfig

func FlexibleXMLConfig() XMLConfig

FlexibleXMLConfig creates a configuration with flexible parsing (allows fallback).

func PerformantXMLConfig

func PerformantXMLConfig() XMLConfig

PerformantXMLConfig creates a configuration optimized for performance.

func SecureXMLConfig

func SecureXMLConfig() XMLConfig

SecureXMLConfig creates a configuration with enhanced security settings.

func StrictXMLConfig

func StrictXMLConfig() XMLConfig

StrictXMLConfig creates a configuration with strict parsing requirements.

func (XMLConfig) GetTagName

func (c XMLConfig) GetTagName(fieldName string) string

GetTagName returns the XML tag name for a field.

func (XMLConfig) WithCustomTag

func (c XMLConfig) WithCustomTag(fieldName, tagName string) XMLConfig

WithCustomTag sets a custom XML tag for a field.

func (XMLConfig) WithFallback

func (c XMLConfig) WithFallback(fallback bool) XMLConfig

WithFallback enables/disables text fallback.

func (XMLConfig) WithMaxDepth

func (c XMLConfig) WithMaxDepth(depth int) XMLConfig

WithMaxDepth sets maximum XML nesting depth.

func (XMLConfig) WithMaxSize

func (c XMLConfig) WithMaxSize(size int64) XMLConfig

WithMaxSize sets maximum XML response size.

func (XMLConfig) WithPreserveWhitespace

func (c XMLConfig) WithPreserveWhitespace(preserve bool) XMLConfig

WithPreserveWhitespace enables/disables whitespace preservation.

func (XMLConfig) WithStrictParsing

func (c XMLConfig) WithStrictParsing(strict bool) XMLConfig

WithStrictParsing sets strict parsing mode.

func (XMLConfig) WithTimeout

func (c XMLConfig) WithTimeout(timeout time.Duration) XMLConfig

WithTimeout sets parsing timeout.

func (XMLConfig) WithTypeHints

func (c XMLConfig) WithTypeHints(hints bool) XMLConfig

WithTypeHints enables/disables type hints in XML instructions.

func (XMLConfig) WithValidation

func (c XMLConfig) WithValidation(validate bool) XMLConfig

WithValidation enables/disables XML validation.

type XMLParser

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

XMLParser handles the actual XML parsing logic.

func (*XMLParser) ParseXMLOutputs

func (p *XMLParser) ParseXMLOutputs(ctx context.Context, outputs map[string]any, signature core.Signature) (map[string]any, error)

ParseXMLOutputs extracts structured data from XML-formatted outputs.

Jump to

Keyboard shortcuts

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