ai

package
v0.0.0-...-dac86b4 Latest Latest
Warning

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

Go to latest
Published: Feb 16, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ComponentPrompt

func ComponentPrompt(spec ComponentSpec) string

ComponentPrompt builds a prompt for generating a single component.

func ContextEnrichedPrompt

func ContextEnrichedPrompt(spec ComponentSpec, availableModules []string, availableServices []string) string

ContextEnrichedPrompt enriches a component generation prompt with available module types and services so the AI can generate components that integrate with the existing system.

func DynamicComponentPrompt

func DynamicComponentPrompt(spec ComponentSpec) string

DynamicComponentPrompt builds a prompt for generating a component in dynamic format. Dynamic components are flat packages with exported functions that can be loaded by the Yaegi interpreter at runtime.

func EstimateCost

func EstimateCost(model string, inputTokens, outputTokens int) float64

EstimateCost estimates the cost of an LLM call based on model and token counts. For unknown models, it uses the claude-sonnet rates as a conservative default.

func ExamplePromptSection

func ExamplePromptSection(examples map[string]string) string

ExamplePromptSection builds a prompt section with example configs.

func GeneratePrompt

func GeneratePrompt(req GenerateRequest) string

GeneratePrompt builds a workflow generation prompt from the request.

func LoadExampleConfigs

func LoadExampleConfigs(exampleDir string) (map[string]string, error)

LoadExampleConfigs reads example YAML files from the given directory and returns them as a map of filename to content.

func MissingComponentsPrompt

func MissingComponentsPrompt(moduleTypes []string) string

MissingComponentsPrompt builds a prompt for identifying missing components.

func SuggestPrompt

func SuggestPrompt(useCase string) string

SuggestPrompt builds a prompt for workflow suggestions.

func SystemPrompt

func SystemPrompt() string

SystemPrompt returns the system prompt describing the workflow engine capabilities.

Types

type CombinedHandler

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

CombinedHandler wraps both the AI query handler and deploy handler into a single http.Handler for config-driven delegate dispatch.

func NewCombinedHandler

func NewCombinedHandler(ai *Handler, deploy *DeployHandler) *CombinedHandler

NewCombinedHandler creates a handler that delegates to both AI and deploy handlers.

func (*CombinedHandler) ServeHTTP

func (h *CombinedHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler, routing to the appropriate sub-handler.

type ComponentFormat

type ComponentFormat string

ComponentFormat specifies the target format for generated component code.

const (
	// FormatModule generates code implementing the modular.Module interface (struct-based).
	FormatModule ComponentFormat = "module"
	// FormatDynamic generates code as a flat package with exported functions
	// compatible with the Yaegi dynamic interpreter.
	FormatDynamic ComponentFormat = "dynamic"
)

type ComponentSpec

type ComponentSpec struct {
	Name        string `json:"name"`
	Type        string `json:"type"`
	Description string `json:"description"`
	Interface   string `json:"interface"` // e.g., "modular.Module", "MessageHandler"
	GoCode      string `json:"goCode"`    // Generated Go source
}

ComponentSpec describes a workflow component that may need to be created.

type CostTracker

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

CostTracker tracks AI usage costs per execution and per tenant.

func NewCostTracker

func NewCostTracker() *CostTracker

NewCostTracker creates a new CostTracker.

func (*CostTracker) GetExecutionCost

func (ct *CostTracker) GetExecutionCost(executionID string) float64

GetExecutionCost returns the accumulated cost for an execution.

func (*CostTracker) GetTenantCost

func (ct *CostTracker) GetTenantCost(tenantID string) float64

GetTenantCost returns the accumulated cost for a tenant.

func (*CostTracker) Record

func (ct *CostTracker) Record(executionID, tenantID string, cost float64)

Record adds cost for an execution and tenant.

type DeployHandler

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

DeployHandler provides HTTP handlers for the AI deploy API.

func NewDeployHandler

func NewDeployHandler(deploy *DeployService) *DeployHandler

NewDeployHandler creates a new deploy API handler.

func (*DeployHandler) HandleDeploy

func (h *DeployHandler) HandleDeploy(w http.ResponseWriter, r *http.Request)

HandleDeploy handles POST /api/ai/deploy. It takes an intent string, generates the workflow and components, deploys components to the dynamic registry, and returns the result.

func (*DeployHandler) HandleDeployComponent

func (h *DeployHandler) HandleDeployComponent(w http.ResponseWriter, r *http.Request)

HandleDeployComponent handles POST /api/ai/deploy/component. It deploys a single component to the dynamic registry.

func (*DeployHandler) RegisterRoutes

func (h *DeployHandler) RegisterRoutes(mux *http.ServeMux)

RegisterRoutes registers the deploy API routes on a ServeMux.

func (*DeployHandler) ServeHTTP

func (h *DeployHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler for config-driven delegate dispatch.

type DeployService

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

DeployService bridges AI code generation with the dynamic component system. It generates components in dynamic format and loads them into the Yaegi interpreter at runtime.

func NewDeployService

func NewDeployService(ai *Service, registry *dynamic.ComponentRegistry, pool *dynamic.InterpreterPool) *DeployService

NewDeployService creates a DeployService that connects the AI service to the dynamic component registry.

func (*DeployService) DeployComponent

func (d *DeployService) DeployComponent(ctx context.Context, spec ComponentSpec) error

DeployComponent takes a ComponentSpec, generates dynamic-format code if needed, validates it, and loads it into the dynamic component registry.

func (*DeployService) GenerateAndDeploy

func (d *DeployService) GenerateAndDeploy(ctx context.Context, intent string) (*config.WorkflowConfig, error)

GenerateAndDeploy takes a natural language intent, generates the workflow config and any required components, loads the components into the dynamic registry, and returns the config.

func (*DeployService) SaveConfig

func (d *DeployService) SaveConfig(cfg *config.WorkflowConfig, path string) error

SaveConfig writes a WorkflowConfig to a YAML file.

type GenerateRequest

type GenerateRequest struct {
	Intent      string            `json:"intent"`      // Natural language description
	Context     map[string]string `json:"context"`     // Additional context
	Constraints []string          `json:"constraints"` // Requirements/constraints
}

GenerateRequest contains the input for workflow generation.

type GenerateResponse

type GenerateResponse struct {
	Workflow    *config.WorkflowConfig `json:"workflow"`
	Components  []ComponentSpec        `json:"components"`
	Explanation string                 `json:"explanation"`
}

GenerateResponse contains the output of workflow generation.

type GuardrailConfig

type GuardrailConfig struct {
	MaxTokens          int           `yaml:"max_tokens" json:"max_tokens"`
	BlockPatterns      []string      `yaml:"block_patterns" json:"block_patterns"`
	TrackCost          bool          `yaml:"track_cost" json:"track_cost"`
	CostBudgetPerExec  float64       `yaml:"cost_budget_per_execution" json:"cost_budget_per_execution"`
	MaskPII            bool          `yaml:"mask_pii" json:"mask_pii"`
	MaxRetries         int           `yaml:"max_retries" json:"max_retries"`
	Timeout            time.Duration `yaml:"timeout" json:"timeout"`
	RateLimitPerMinute int           `yaml:"rate_limit_per_minute" json:"rate_limit_per_minute"`
}

GuardrailConfig defines safety constraints for AI/LLM steps.

func DefaultGuardrailConfig

func DefaultGuardrailConfig() GuardrailConfig

DefaultGuardrailConfig returns a GuardrailConfig with sensible defaults.

type GuardrailResult

type GuardrailResult struct {
	Allowed       bool     `json:"allowed"`
	Reasons       []string `json:"reasons,omitempty"`
	MaskedInput   string   `json:"masked_input,omitempty"`
	EstimatedCost float64  `json:"estimated_cost,omitempty"`
}

GuardrailResult contains the outcome of guardrail checks.

type Guardrails

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

Guardrails enforces safety constraints on AI/LLM operations.

func NewGuardrails

func NewGuardrails(config GuardrailConfig) (*Guardrails, error)

NewGuardrails creates a new Guardrails instance from config. It compiles all block patterns at initialization time and returns an error if any pattern is invalid.

func (*Guardrails) CheckInput

func (g *Guardrails) CheckInput(ctx context.Context, input string) (*GuardrailResult, error)

CheckInput validates input before sending to an LLM. It checks token limits, block patterns, cost budget, and optionally masks PII.

func (*Guardrails) CheckOutput

func (g *Guardrails) CheckOutput(ctx context.Context, output string) (*GuardrailResult, error)

CheckOutput validates LLM output before returning to the user. It checks block patterns and optionally masks PII in the response.

func (*Guardrails) GetCost

func (g *Guardrails) GetCost(executionID string) float64

GetCost returns the total cost for an execution.

func (*Guardrails) GetTenantCost

func (g *Guardrails) GetTenantCost(tenantID string) float64

GetTenantCost returns the total cost for a tenant in the current period.

func (*Guardrails) MaskPII

func (g *Guardrails) MaskPII(input string) string

MaskPII replaces PII patterns with masked versions.

func (*Guardrails) RecordCost

func (g *Guardrails) RecordCost(executionID, tenantID string, cost float64) error

RecordCost records the cost of an AI operation. If cost tracking is enabled and the execution's accumulated cost would exceed the budget, it returns an error.

type Handler

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

Handler provides HTTP handlers for the AI service API.

func NewHandler

func NewHandler(service *Service) *Handler

NewHandler creates a new AI API handler.

func (*Handler) HandleComponent

func (h *Handler) HandleComponent(w http.ResponseWriter, r *http.Request)

HandleComponent handles POST /api/ai/component

func (*Handler) HandleGenerate

func (h *Handler) HandleGenerate(w http.ResponseWriter, r *http.Request)

HandleGenerate handles POST /api/ai/generate

func (*Handler) HandleProviders

func (h *Handler) HandleProviders(w http.ResponseWriter, r *http.Request)

HandleProviders handles GET /api/ai/providers

func (*Handler) HandleSuggest

func (h *Handler) HandleSuggest(w http.ResponseWriter, r *http.Request)

HandleSuggest handles POST /api/ai/suggest

func (*Handler) RegisterRoutes

func (h *Handler) RegisterRoutes(mux *http.ServeMux)

RegisterRoutes registers the AI API routes on a ServeMux.

func (*Handler) ServeHTTP

func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler for config-driven delegate dispatch. It handles both query (GET) and command (POST) operations for AI, dispatching based on the last path segment.

type Provider

type Provider string

Provider identifies an AI backend.

const (
	ProviderAnthropic Provider = "anthropic"
	ProviderCopilot   Provider = "copilot"
	ProviderAuto      Provider = "auto"
)

type Service

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

Service coordinates multiple AI generator backends with provider selection, caching, and rate limiting.

func NewService

func NewService() *Service

NewService creates a new AI service.

func (*Service) ClearCache

func (s *Service) ClearCache()

ClearCache clears the suggestion cache.

func (*Service) GenerateComponent

func (s *Service) GenerateComponent(ctx context.Context, spec ComponentSpec) (string, error)

GenerateComponent generates Go source code for a component.

func (*Service) GenerateWorkflow

func (s *Service) GenerateWorkflow(ctx context.Context, req GenerateRequest) (*GenerateResponse, error)

GenerateWorkflow creates a workflow config from a natural language request.

func (*Service) IdentifyMissingComponents

func (s *Service) IdentifyMissingComponents(ctx context.Context, cfg *config.WorkflowConfig) ([]ComponentSpec, error)

IdentifyMissingComponents analyzes a config for non-built-in module types.

func (*Service) Providers

func (s *Service) Providers() []Provider

Providers returns the list of registered provider names.

func (*Service) RegisterGenerator

func (s *Service) RegisterGenerator(provider Provider, gen WorkflowGenerator)

RegisterGenerator registers an AI generator for a provider.

func (*Service) SetPreferred

func (s *Service) SetPreferred(provider Provider)

SetPreferred sets the preferred provider. Use ProviderAuto to auto-select.

func (*Service) SuggestWorkflow

func (s *Service) SuggestWorkflow(ctx context.Context, useCase string) ([]WorkflowSuggestion, error)

SuggestWorkflow returns cached or fresh suggestions for a use case.

type ValidationConfig

type ValidationConfig struct {
	MaxRetries        int  `json:"maxRetries"`
	CompileCheck      bool `json:"compileCheck"`
	RequiredFuncCheck bool `json:"requiredFuncCheck"`
}

ValidationConfig configures the validation loop behavior.

func DefaultValidationConfig

func DefaultValidationConfig() ValidationConfig

DefaultValidationConfig returns sensible defaults.

type ValidationResult

type ValidationResult struct {
	Valid    bool     `json:"valid"`
	Errors   []string `json:"errors,omitempty"`
	Warnings []string `json:"warnings,omitempty"`
}

ValidationResult holds the outcome of source code validation.

type Validator

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

Validator validates and optionally fixes AI-generated component source code.

func NewValidator

func NewValidator(config ValidationConfig, pool *dynamic.InterpreterPool) *Validator

NewValidator creates a Validator with the given config and interpreter pool.

func (*Validator) BuildFixPrompt

func (v *Validator) BuildFixPrompt(spec ComponentSpec, source string, errors []string) string

BuildFixPrompt formats a prompt that includes the original spec, the failing source code, and the list of errors so the AI can produce a corrected version.

func (*Validator) ValidateAndFix

func (v *Validator) ValidateAndFix(ctx context.Context, aiService *Service, spec ComponentSpec, source string) (string, *ValidationResult, error)

ValidateAndFix runs a validation loop that attempts to fix invalid source code by asking the AI service to regenerate with error context. It returns the final source, validation result, and any error encountered.

func (*Validator) ValidateSource

func (v *Validator) ValidateSource(source string) *ValidationResult

ValidateSource checks the given source code for correctness. It validates imports, optionally compiles with Yaegi, and checks for required exported functions.

type WorkflowGenerator

type WorkflowGenerator interface {
	// GenerateWorkflow creates a complete workflow config from a natural language request.
	GenerateWorkflow(ctx context.Context, req GenerateRequest) (*GenerateResponse, error)

	// GenerateComponent generates Go source code for a component specification.
	GenerateComponent(ctx context.Context, spec ComponentSpec) (string, error)

	// SuggestWorkflow returns workflow suggestions for a given use case description.
	SuggestWorkflow(ctx context.Context, useCase string) ([]WorkflowSuggestion, error)

	// IdentifyMissingComponents analyzes a workflow config and returns specs for
	// components that need to be created.
	IdentifyMissingComponents(ctx context.Context, cfg *config.WorkflowConfig) ([]ComponentSpec, error)
}

WorkflowGenerator defines the interface for AI-powered workflow generation. Implementations include direct LLM clients and Copilot SDK wrappers.

type WorkflowSuggestion

type WorkflowSuggestion struct {
	Name        string                 `json:"name"`
	Description string                 `json:"description"`
	Config      *config.WorkflowConfig `json:"config"`
	Confidence  float64                `json:"confidence"`
}

WorkflowSuggestion represents a suggested workflow with confidence score.

Directories

Path Synopsis
Package examples contains complete examples of AI-generated workflows.
Package examples contains complete examples of AI-generated workflows.

Jump to

Keyboard shortcuts

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