{"modulePath":"github.com/GoCodeAlone/workflow","version":"v0.87.0","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package ai\n\n## Functions\n\n```go\nfunc ComponentPrompt(spec ComponentSpec) string\n```\nComponentPrompt builds a prompt for generating a single component.\n\n```go\nfunc ContextEnrichedPrompt(spec ComponentSpec, availableModules []string, availableServices []string) string\n```\nContextEnrichedPrompt enriches a component generation prompt with available module types and services so the AI can generate components that integrate with the existing system.\n\n```go\nfunc DynamicComponentPrompt(spec ComponentSpec) string\n```\nDynamicComponentPrompt 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.\n\n```go\nfunc EstimateCost(model string, inputTokens, outputTokens int) float64\n```\nEstimateCost 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.\n\n```go\nfunc ExamplePromptSection(examples map[string]string) string\n```\nExamplePromptSection builds a prompt section with example configs.\n\n```go\nfunc GeneratePrompt(req GenerateRequest) string\n```\nGeneratePrompt builds a workflow generation prompt from the request.\n\n```go\nfunc LoadExampleConfigs(exampleDir string) (map[string]string, error)\n```\nLoadExampleConfigs reads example YAML files from the given directory and returns them as a map of filename to content.\n\n```go\nfunc MissingComponentsPrompt(moduleTypes []string) string\n```\nMissingComponentsPrompt builds a prompt for identifying missing components.\n\n```go\nfunc SuggestPrompt(useCase string) string\n```\nSuggestPrompt builds a prompt for workflow suggestions.\n\n```go\nfunc SystemPrompt() string\n```\nSystemPrompt returns the system prompt describing the workflow engine capabilities.\n\n## Types\n\n```go\ntype AIModelRegistry struct {\n\t// contains filtered or unexported fields\n}\n```\nAIModelRegistry manages AI providers, model metadata, default model assignments per use-case, and per-user/tenant overrides.\n\n```go\nfunc NewAIModelRegistry() *AIModelRegistry\n```\nNewAIModelRegistry creates an empty registry.\n\n```go\nfunc (r *AIModelRegistry) GetDefault(useCase string) string\n```\nGetDefault returns the default model for a use-case, or empty string if not set.\n\n```go\nfunc (r *AIModelRegistry) GetModel(modelID string) (ModelInfo, bool)\n```\nGetModel returns metadata for a specific model ID.\n\n```go\nfunc (r *AIModelRegistry) GetOverride(key string) (ModelOverride, bool)\n```\nGetOverride returns the override for a given key, if any.\n\n```go\nfunc (r *AIModelRegistry) GetProvider(name string) (AIProvider, bool)\n```\nGetProvider returns a registered provider by name.\n\n```go\nfunc (r *AIModelRegistry) ListModels() []ModelInfo\n```\nListModels returns metadata for all indexed models across all providers.\n\n```go\nfunc (r *AIModelRegistry) ListProviders() []string\n```\nListProviders returns the names of all registered providers.\n\n```go\nfunc (r *AIModelRegistry) ProviderForModel(modelID string) (AIProvider, bool)\n```\nProviderForModel returns the provider that owns a given model ID.\n\n```go\nfunc (r *AIModelRegistry) RegisterProvider(provider AIProvider) error\n```\nRegisterProvider adds an AI provider and indexes all its models.\n\n```go\nfunc (r *AIModelRegistry) RemoveOverride(key string)\n```\nRemoveOverride removes an override by key.\n\n```go\nfunc (r *AIModelRegistry) SetDefault(useCase, modelID string) error\n```\nSetDefault sets the preferred model for a use-case (e.g., \"completion\", \"classification\").\n\n```go\nfunc (r *AIModelRegistry) SetOverride(key string, override ModelOverride)\n```\nSetOverride sets a per-tenant/user override for a model. The key should be formatted as \"tenantID:modelID\".\n\n```go\ntype AIProvider interface {\n\t// Name returns the provider's unique identifier (e.g., \"anthropic\", \"openai\").\n\tName() string\n\n\t// Models returns metadata about all models available from this provider.\n\tModels() []ModelInfo\n\n\t// Complete sends a completion request and returns the full response.\n\tComplete(ctx context.Context, req CompletionRequest) (*CompletionResponse, error)\n\n\t// CompleteStream sends a completion request and returns a channel of streaming chunks.\n\tCompleteStream(ctx context.Context, req CompletionRequest) (\u003c-chan StreamChunk, error)\n\n\t// SupportsToolUse returns whether this provider supports function/tool calling.\n\tSupportsToolUse() bool\n\n\t// ToolComplete sends a completion request with tool definitions and returns the response.\n\tToolComplete(ctx context.Context, req ToolCompletionRequest) (*ToolCompletionResponse, error)\n}\n```\nAIProvider defines a pluggable AI model provider that can be registered with the AIModelRegistry. Providers supply completion and streaming APIs with optional tool-use support.\n\n```go\ntype CombinedHandler struct {\n\t// contains filtered or unexported fields\n}\n```\nCombinedHandler wraps both the AI query handler and deploy handler into a single http.Handler for config-driven delegate dispatch.\n\n```go\nfunc NewCombinedHandler(ai *Handler, deploy *DeployHandler) *CombinedHandler\n```\nNewCombinedHandler creates a handler that delegates to both AI and deploy handlers.\n\n```go\nfunc (h *CombinedHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)\n```\nServeHTTP implements http.Handler, routing to the appropriate sub-handler.\n\n```go\ntype CompletionRequest struct {\n\tModel        string         `json:\"model\"`\n\tMessages     []Message      `json:\"messages\"`\n\tMaxTokens    int            `json:\"maxTokens\"`\n\tTemperature  float64        `json:\"temperature\"`\n\tSystemPrompt string         `json:\"systemPrompt,omitempty\"`\n\tMetadata     map[string]any `json:\"metadata,omitempty\"`\n}\n```\nCompletionRequest is the input for a non-streaming completion call.\n\n```go\nfunc ApplyOverride(req CompletionRequest, override ModelOverride) CompletionRequest\n```\nApplyOverride merges an override into a CompletionRequest, returning a modified copy.\n\n```go\ntype CompletionResponse struct {\n\tID           string     `json:\"id\"`\n\tModel        string     `json:\"model\"`\n\tContent      string     `json:\"content\"`\n\tUsage        TokenUsage `json:\"usage\"`\n\tFinishReason string     `json:\"finishReason\"`\n}\n```\nCompletionResponse is the output of a completion call.\n\n```go\ntype ComponentFormat string\n```\nComponentFormat specifies the target format for generated component code.\n\n```go\nconst (\n\t// FormatModule generates code implementing the modular.Module interface (struct-based).\n\tFormatModule ComponentFormat = \"module\"\n\t// FormatDynamic generates code as a flat package with exported functions\n\t// compatible with the Yaegi dynamic interpreter.\n\tFormatDynamic ComponentFormat = \"dynamic\"\n)\n```\n\n```go\ntype ComponentSpec struct {\n\tName        string `json:\"name\"`\n\tType        string `json:\"type\"`\n\tDescription string `json:\"description\"`\n\tInterface   string `json:\"interface\"` // e.g., \"modular.Module\", \"MessageHandler\"\n\tGoCode      string `json:\"goCode\"`    // Generated Go source\n}\n```\nComponentSpec describes a workflow component that may need to be created.\n\n```go\ntype CostTracker struct {\n\t// contains filtered or unexported fields\n}\n```\nCostTracker tracks AI usage costs per execution and per tenant.\n\n```go\nfunc NewCostTracker() *CostTracker\n```\nNewCostTracker creates a new CostTracker.\n\n```go\nfunc (ct *CostTracker) GetExecutionCost(executionID string) float64\n```\nGetExecutionCost returns the accumulated cost for an execution.\n\n```go\nfunc (ct *CostTracker) GetTenantCost(tenantID string) float64\n```\nGetTenantCost returns the accumulated cost for a tenant.\n\n```go\nfunc (ct *CostTracker) Record(executionID, tenantID string, cost float64)\n```\nRecord adds cost for an execution and tenant.\n\n```go\ntype DeployHandler struct {\n\t// contains filtered or unexported fields\n}\n```\nDeployHandler provides HTTP handlers for the AI deploy API.\n\n```go\nfunc NewDeployHandler(deploy *DeployService) *DeployHandler\n```\nNewDeployHandler creates a new deploy API handler.\n\n```go\nfunc (h *DeployHandler) HandleDeploy(w http.ResponseWriter, r *http.Request)\n```\nHandleDeploy 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.\n\n```go\nfunc (h *DeployHandler) HandleDeployComponent(w http.ResponseWriter, r *http.Request)\n```\nHandleDeployComponent handles POST /api/ai/deploy/component. It deploys a single component to the dynamic registry.\n\n```go\nfunc (h *DeployHandler) RegisterRoutes(mux *http.ServeMux)\n```\nRegisterRoutes registers the deploy API routes on a ServeMux.\n\n```go\nfunc (h *DeployHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)\n```\nServeHTTP implements http.Handler for config-driven delegate dispatch.\n\n```go\ntype DeployService struct {\n\t// contains filtered or unexported fields\n}\n```\nDeployService bridges AI code generation with the dynamic component system. It generates components in dynamic format and loads them into the Yaegi interpreter at runtime.\n\n```go\nfunc NewDeployService(ai *Service, registry *dynamic.ComponentRegistry, pool *dynamic.InterpreterPool) *DeployService\n```\nNewDeployService creates a DeployService that connects the AI service to the dynamic component registry.\n\n```go\nfunc (d *DeployService) DeployComponent(ctx context.Context, spec ComponentSpec) error\n```\nDeployComponent takes a ComponentSpec, generates dynamic-format code if needed, validates it, and loads it into the dynamic component registry.\n\n```go\nfunc (d *DeployService) GenerateAndDeploy(ctx context.Context, intent string) (*config.WorkflowConfig, error)\n```\nGenerateAndDeploy takes a natural language intent, generates the workflow config and any required components, loads the components into the dynamic registry, and returns the config.\n\n```go\nfunc (d *DeployService) SaveConfig(cfg *config.WorkflowConfig, path string) error\n```\nSaveConfig writes a WorkflowConfig to a YAML file.\n\n```go\ntype GenerateRequest struct {\n\tIntent      string            `json:\"intent\"`      // Natural language description\n\tContext     map[string]string `json:\"context\"`     // Additional context\n\tConstraints []string          `json:\"constraints\"` // Requirements/constraints\n}\n```\nGenerateRequest contains the input for workflow generation.\n\n```go\ntype GenerateResponse struct {\n\tWorkflow    *config.WorkflowConfig `json:\"workflow\"`\n\tComponents  []ComponentSpec        `json:\"components\"`\n\tExplanation string                 `json:\"explanation\"`\n}\n```\nGenerateResponse contains the output of workflow generation.\n\n```go\ntype GuardrailConfig struct {\n\tMaxTokens          int           `yaml:\"max_tokens\" json:\"max_tokens\"`\n\tBlockPatterns      []string      `yaml:\"block_patterns\" json:\"block_patterns\"`\n\tTrackCost          bool          `yaml:\"track_cost\" json:\"track_cost\"`\n\tCostBudgetPerExec  float64       `yaml:\"cost_budget_per_execution\" json:\"cost_budget_per_execution\"`\n\tMaskPII            bool          `yaml:\"mask_pii\" json:\"mask_pii\"`\n\tMaxRetries         int           `yaml:\"max_retries\" json:\"max_retries\"`\n\tTimeout            time.Duration `yaml:\"timeout\" json:\"timeout\"`\n\tRateLimitPerMinute int           `yaml:\"rate_limit_per_minute\" json:\"rate_limit_per_minute\"`\n}\n```\nGuardrailConfig defines safety constraints for AI/LLM steps.\n\n```go\nfunc DefaultGuardrailConfig() GuardrailConfig\n```\nDefaultGuardrailConfig returns a GuardrailConfig with sensible defaults.\n\n```go\ntype GuardrailResult struct {\n\tAllowed       bool     `json:\"allowed\"`\n\tReasons       []string `json:\"reasons,omitempty\"`\n\tMaskedInput   string   `json:\"masked_input,omitempty\"`\n\tEstimatedCost float64  `json:\"estimated_cost,omitempty\"`\n}\n```\nGuardrailResult contains the outcome of guardrail checks.\n\n```go\ntype Guardrails struct {\n\t// contains filtered or unexported fields\n}\n```\nGuardrails enforces safety constraints on AI/LLM operations.\n\n```go\nfunc NewGuardrails(config GuardrailConfig) (*Guardrails, error)\n```\nNewGuardrails creates a new Guardrails instance from config. It compiles all block patterns at initialization time and returns an error if any pattern is invalid.\n\n```go\nfunc (g *Guardrails) CheckInput(ctx context.Context, input string) (*GuardrailResult, error)\n```\nCheckInput validates input before sending to an LLM. It checks token limits, block patterns, cost budget, and optionally masks PII.\n\n```go\nfunc (g *Guardrails) CheckOutput(ctx context.Context, output string) (*GuardrailResult, error)\n```\nCheckOutput validates LLM output before returning to the user. It checks block patterns and optionally masks PII in the response.\n\n```go\nfunc (g *Guardrails) GetCost(executionID string) float64\n```\nGetCost returns the total cost for an execution.\n\n```go\nfunc (g *Guardrails) GetTenantCost(tenantID string) float64\n```\nGetTenantCost returns the total cost for a tenant in the current period.\n\n```go\nfunc (g *Guardrails) MaskPII(input string) string\n```\nMaskPII replaces PII patterns with masked versions.\n\n```go\nfunc (g *Guardrails) RecordCost(executionID, tenantID string, cost float64) error\n```\nRecordCost 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.\n\n```go\ntype Handler struct {\n\t// contains filtered or unexported fields\n}\n```\nHandler provides HTTP handlers for the AI service API.\n\n```go\nfunc NewHandler(service *Service) *Handler\n```\nNewHandler creates a new AI API handler.\n\n```go\nfunc (h *Handler) HandleComponent(w http.ResponseWriter, r *http.Request)\n```\nHandleComponent handles POST /api/ai/component\n\n```go\nfunc (h *Handler) HandleGenerate(w http.ResponseWriter, r *http.Request)\n```\nHandleGenerate handles POST /api/ai/generate\n\n```go\nfunc (h *Handler) HandleProviders(w http.ResponseWriter, r *http.Request)\n```\nHandleProviders handles GET /api/ai/providers\n\n```go\nfunc (h *Handler) HandleSuggest(w http.ResponseWriter, r *http.Request)\n```\nHandleSuggest handles POST /api/ai/suggest\n\n```go\nfunc (h *Handler) RegisterRoutes(mux *http.ServeMux)\n```\nRegisterRoutes registers the AI API routes on a ServeMux.\n\n```go\nfunc (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request)\n```\nServeHTTP 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.\n\n```go\ntype Message struct {\n\tRole    string `json:\"role\"` // \"user\", \"assistant\", \"system\"\n\tContent string `json:\"content\"`\n}\n```\nMessage is a single message in a conversation.\n\n```go\ntype ModelInfo struct {\n\tID              string   `json:\"id\"`\n\tName            string   `json:\"name\"`\n\tProvider        string   `json:\"provider\"`\n\tContextWindow   int      `json:\"contextWindow\"`\n\tMaxOutput       int      `json:\"maxOutput\"`\n\tSupportsTools   bool     `json:\"supportsTools\"`\n\tSupportsVision  bool     `json:\"supportsVision\"`\n\tCostPer1KInput  float64  `json:\"costPer1KInput\"`\n\tCostPer1KOutput float64  `json:\"costPer1KOutput\"`\n\tOverridable     []string `json:\"overridable\"`\n}\n```\nModelInfo describes a model's capabilities and pricing.\n\n```go\ntype ModelOverride struct {\n\tMaxTokens   *int     `json:\"maxTokens,omitempty\"`\n\tTemperature *float64 `json:\"temperature,omitempty\"`\n\tEnabled     *bool    `json:\"enabled,omitempty\"`\n}\n```\nModelOverride allows per-tenant or per-user overrides for model parameters.\n\n```go\ntype Provider string\n```\nProvider identifies an AI backend.\n\n```go\nconst (\n\tProviderAnthropic Provider = \"anthropic\"\n\tProviderCopilot   Provider = \"copilot\"\n\tProviderAuto      Provider = \"auto\"\n)\n```\n\n```go\ntype Service struct {\n\t// contains filtered or unexported fields\n}\n```\nService coordinates multiple AI generator backends with provider selection, caching, and rate limiting.\n\n```go\nfunc NewService() *Service\n```\nNewService creates a new AI service.\n\n```go\nfunc (s *Service) ClearCache()\n```\nClearCache clears the suggestion cache.\n\n```go\nfunc (s *Service) GenerateComponent(ctx context.Context, spec ComponentSpec) (string, error)\n```\nGenerateComponent generates Go source code for a component.\n\n```go\nfunc (s *Service) GenerateWorkflow(ctx context.Context, req GenerateRequest) (*GenerateResponse, error)\n```\nGenerateWorkflow creates a workflow config from a natural language request.\n\n```go\nfunc (s *Service) IdentifyMissingComponents(ctx context.Context, cfg *config.WorkflowConfig) ([]ComponentSpec, error)\n```\nIdentifyMissingComponents analyzes a config for non-built-in module types.\n\n```go\nfunc (s *Service) Providers() []Provider\n```\nProviders returns the list of registered provider names.\n\n```go\nfunc (s *Service) RegisterGenerator(provider Provider, gen WorkflowGenerator)\n```\nRegisterGenerator registers an AI generator for a provider.\n\n```go\nfunc (s *Service) SetPreferred(provider Provider)\n```\nSetPreferred sets the preferred provider. Use ProviderAuto to auto-select.\n\n```go\nfunc (s *Service) SuggestWorkflow(ctx context.Context, useCase string) ([]WorkflowSuggestion, error)\n```\nSuggestWorkflow returns cached or fresh suggestions for a use case.\n\n```go\ntype StreamChunk struct {\n\tContent string `json:\"content,omitempty\"`\n\tDone    bool   `json:\"done\"`\n\tError   error  `json:\"-\"`\n}\n```\nStreamChunk is one piece of a streaming completion response.\n\n```go\ntype TokenUsage struct {\n\tInputTokens  int `json:\"inputTokens\"`\n\tOutputTokens int `json:\"outputTokens\"`\n}\n```\nTokenUsage tracks input and output token counts.\n\n```go\ntype ToolCall struct {\n\tID    string         `json:\"id\"`\n\tName  string         `json:\"name\"`\n\tInput map[string]any `json:\"input\"`\n}\n```\nToolCall represents a single tool invocation requested by the model.\n\n```go\ntype ToolCompletionRequest struct {\n\tCompletionRequest\n\tTools []ToolDefinition `json:\"tools\"`\n}\n```\nToolCompletionRequest extends CompletionRequest with tool definitions.\n\n```go\ntype ToolCompletionResponse struct {\n\tCompletionResponse\n\tToolCalls []ToolCall `json:\"toolCalls,omitempty\"`\n}\n```\nToolCompletionResponse extends CompletionResponse with tool calls.\n\n```go\ntype ToolDefinition struct {\n\tName        string         `json:\"name\"`\n\tDescription string         `json:\"description\"`\n\tInputSchema map[string]any `json:\"inputSchema\"`\n}\n```\nToolDefinition describes a tool that the model can invoke.\n\n```go\ntype ValidationConfig struct {\n\tMaxRetries        int  `json:\"maxRetries\"`\n\tCompileCheck      bool `json:\"compileCheck\"`\n\tRequiredFuncCheck bool `json:\"requiredFuncCheck\"`\n}\n```\nValidationConfig configures the validation loop behavior.\n\n```go\nfunc DefaultValidationConfig() ValidationConfig\n```\nDefaultValidationConfig returns sensible defaults.\n\n```go\ntype ValidationResult struct {\n\tValid    bool     `json:\"valid\"`\n\tErrors   []string `json:\"errors,omitempty\"`\n\tWarnings []string `json:\"warnings,omitempty\"`\n}\n```\nValidationResult holds the outcome of source code validation.\n\n```go\ntype Validator struct {\n\t// contains filtered or unexported fields\n}\n```\nValidator validates and optionally fixes AI-generated component source code.\n\n```go\nfunc NewValidator(config ValidationConfig, pool *dynamic.InterpreterPool) *Validator\n```\nNewValidator creates a Validator with the given config and interpreter pool.\n\n```go\nfunc (v *Validator) BuildFixPrompt(spec ComponentSpec, source string, errors []string) string\n```\nBuildFixPrompt 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.\n\n```go\nfunc (v *Validator) ValidateAndFix(ctx context.Context, aiService *Service, spec ComponentSpec, source string) (string, *ValidationResult, error)\n```\nValidateAndFix 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.\n\n```go\nfunc (v *Validator) ValidateSource(source string) *ValidationResult\n```\nValidateSource checks the given source code for correctness. It validates imports, optionally compiles with Yaegi, and checks for required exported functions.\n\n```go\ntype WorkflowGenerator interface {\n\t// GenerateWorkflow creates a complete workflow config from a natural language request.\n\tGenerateWorkflow(ctx context.Context, req GenerateRequest) (*GenerateResponse, error)\n\n\t// GenerateComponent generates Go source code for a component specification.\n\tGenerateComponent(ctx context.Context, spec ComponentSpec) (string, error)\n\n\t// SuggestWorkflow returns workflow suggestions for a given use case description.\n\tSuggestWorkflow(ctx context.Context, useCase string) ([]WorkflowSuggestion, error)\n\n\t// IdentifyMissingComponents analyzes a workflow config and returns specs for\n\t// components that need to be created.\n\tIdentifyMissingComponents(ctx context.Context, cfg *config.WorkflowConfig) ([]ComponentSpec, error)\n}\n```\nWorkflowGenerator defines the interface for AI-powered workflow generation. Implementations include direct LLM clients and Copilot SDK wrappers.\n\n```go\ntype WorkflowSuggestion struct {\n\tName        string                 `json:\"name\"`\n\tDescription string                 `json:\"description\"`\n\tConfig      *config.WorkflowConfig `json:\"config\"`\n\tConfidence  float64                `json:\"confidence\"`\n}\n```\nWorkflowSuggestion represents a suggested workflow with confidence score.\n\n","path":"github.com/GoCodeAlone/workflow/ai","name":"ai","synopsis":"","isRedistributable":true}
