nai

package
v0.0.0-...-36d6306 Latest Latest
Warning

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

Go to latest
Published: Jul 5, 2026 License: Apache-2.0 Imports: 17 Imported by: 0

Documentation

Index

Constants

View Source
const (
	AIParamTypeString  = "string"
	AIParamTypeNumber  = "number"
	AIParamTypeBoolean = "boolean"
	AIParamTypeArray   = "array"
	AIParamTypeObject  = "object"
)

Supported types for AI parameters

Variables

This section is empty.

Functions

func AIVar

func AIVar(path string, description string) string

AIVar creates a detailed description string for a variable that AI can understand. Usage in expressions: aivar("GetUser.response.body.id", "The user's unique ID") Returns a detailed string like: "[AI_REF: GetUser.response.body.id | User's ID | Use with get_variable]"

func AIVarFull

func AIVarFull(path, description, varType, source, example string) string

AIVarFull creates the most detailed description with source and example. Usage: aivar_full("ai_1.userId", "User ID to fetch", "number", "from user input", "123")

func AIVarTyped

func AIVarTyped(path, description, varType string) string

AIVarTyped creates a detailed description with type information. Usage: aivar_typed("GetUser.response.body.id", "User ID", "number")

func EnhanceToolDescriptionForAI

func EnhanceToolDescriptionForAI(
	toolName string,
	baseDescription string,
	params []AIParam,
	outputVars []string,
	prevToolOutputs map[string][]string,
) string

EnhanceToolDescriptionForAI takes a basic tool description and adds AI-friendly context including variable paths, types, and chain hints.

func ExtractAIParamNames

func ExtractAIParamNames(aiNodeName string, params []AIParam) []string

ExtractAIParamNames returns just the parameter names from a list of AIParams. Useful for getting required variable names.

func GenerateAIParamDescription

func GenerateAIParamDescription(aiNodeName string, params []AIParam) string

GenerateAIParamDescription creates a rich description string from AI parameters. This is used to tell the AI exactly what inputs are needed and their types. aiNodeName is the name of the AI agent node (e.g., "ai_1") - used for setting input variables.

func GenerateAIParamToolDescription

func GenerateAIParamToolDescription(toolNodeName string, baseDescription string, params []AIParam, outputVars []string) string

GenerateAIParamToolDescription creates a complete tool description including AI params. toolNodeName is the name of the tool being described (e.g., "GetUser") aiNodeName is typically "ai_1" - where input variables should be set

func GenerateChainDescription

func GenerateChainDescription(chains []ChainInfo) string

GenerateChainDescription creates a description showing how tools connect

func GenerateFlowOverview

func GenerateFlowOverview(tools []ToolOverview) string

GenerateFlowOverview creates a high-level overview of tool chain for AI

func ParseAIVarExpressions

func ParseAIVarExpressions(input string) string

ParseAIVarExpressions parses {{ aivar('path', 'desc') }} expressions and returns detailed strings

func ResolveAIParamPlaceholder

func ResolveAIParamPlaceholder(input string, aiNodeName string) string

ResolveAIParamPlaceholder converts an AI param expression to the actual variable reference. {{ ai('userId', 'User ID', 'number') }} -> {{ aiNodeName.userId }}

Types

type AIExprEnv

type AIExprEnv struct {
	VarMap     map[string]any
	AINodeName string // The AI node name (e.g., "ai_1") for context
}

AIExprEnv provides AI-aware expression functions for use with expr-lang. These functions help generate detailed variable descriptions that AI can understand.

func NewAIExprEnv

func NewAIExprEnv(varMap map[string]any, aiNodeName string) *AIExprEnv

NewAIExprEnv creates a new AI expression environment

func (*AIExprEnv) AI

func (e *AIExprEnv) AI(name, description, varType string) string

AI creates a detailed AI parameter description. Usage: ai("userId", "The user ID to fetch", "number") Returns: [AI_PARAM: name=userId | type=number | desc="The user ID to fetch" | set_with=ai_1.userId]

func (*AIExprEnv) AIChain

func (e *AIExprEnv) AIChain(sourcePath, paramName, targetTool string) string

AIChain creates an explicit chain instruction for the AI. Usage: aichain("GetPosts.response.body[0].id", "postId", "GetComments") Tells AI: "After GetPosts, get response.body[0].id and set it as postId before calling GetComments"

func (*AIExprEnv) AIDesc

func (e *AIExprEnv) AIDesc(path, description string) string

AIDesc creates a rich description of a variable path with context. Usage: aidesc("GetUser.response.body", "User profile data from the API")

func (*AIExprEnv) AIRef

func (e *AIExprEnv) AIRef(sourcePath, targetParam, varType string) string

AIRef creates a reference hint for chaining - tells AI where to get a value. Usage: airef("GetUser.response.body.id", "userId", "number") Means: "Get GetUser.response.body.id and use it as userId (which should be a number)"

func (*AIExprEnv) AIVar

func (e *AIExprEnv) AIVar(path string) string

AIVar creates a detailed variable reference for AI. Usage: aivar("GetUser.response.body.id") Returns a detailed description of the variable including its current value if available.

func (*AIExprEnv) GetEnvMap

func (e *AIExprEnv) GetEnvMap() map[string]any

GetEnvMap returns a map with all AI functions for expr-lang

type AIParam

type AIParam struct {
	Name        string // Variable name (e.g., "userId")
	Description string // Human-readable description (e.g., "The user ID to fetch")
	Type        string // Data type: "string", "number", "boolean", "array", "object"
	Required    bool   // Whether this parameter is required (default: true)
	SourceHint  string // Optional: Where to get this value (e.g., "GetUser.response.body.id")
}

AIParam represents a typed parameter that the AI needs to provide. Used with the {{ ai('name', 'description', 'type') }} or {{ ai('name', 'description', 'type', 'source') }} syntax for chaining.

func ParseAIParams

func ParseAIParams(input string) []AIParam

ParseAIParams extracts all AI parameters from a string containing {{ ai('name', 'description', 'type') }} or {{ ai('name', 'desc', 'type', 'source') }} expressions.

func ParseAIParamsFromMultiple

func ParseAIParamsFromMultiple(inputs ...string) []AIParam

ParseAIParamsFromMultiple extracts AI parameters from multiple strings and returns a deduplicated list.

type AIParamProvider

type AIParamProvider interface {
	// GetAIParams returns all AI parameters this node requires.
	GetAIParams() []AIParam
}

AIParamProvider is an interface that nodes can implement to declare typed AI parameters using the {{ ai('name', 'desc', 'type') }} syntax.

type AIProvider

type AIProvider interface {
	node.FlowNode

	// Execute runs the LLM with typed input and returns typed output.
	// This is the primary method for orchestrator-to-provider communication,
	// maintaining type safety for messages and tool calls.
	Execute(ctx context.Context, req *node.FlowNodeRequest, input AIProviderInput) (*mflow.AIProviderOutput, error)

	// GetModelString returns the model identifier string (e.g., "gpt-5.2")
	GetModelString() string

	// GetProviderString returns the provider name (e.g., "openai", "anthropic")
	GetProviderString() string

	// SetProviderFactory sets the LLM provider factory on the provider node
	SetProviderFactory(factory *scredential.LLMProviderFactory)

	// SetLLM sets a mock LLM model for testing purposes
	SetLLM(llm any)
}

AIProvider is the interface that LLM provider nodes must implement. This allows NodeAI to work with different provider implementations.

type AIProviderInput

type AIProviderInput struct {
	Messages []llm.Message
	Tools    []llm.Tool
}

AIProviderInput contains typed input for LLM execution. This is the typed interface for passing data from orchestrator to provider, avoiding type loss through VarMap (map[string]any).

type AIVarDetail

type AIVarDetail struct {
	Path        string `json:"path"`                  // Full variable path (e.g., "GetUser.response.body.id")
	Type        string `json:"type,omitempty"`        // Data type if known
	Description string `json:"description,omitempty"` // Human description
	Source      string `json:"source,omitempty"`      // Where this value comes from
	Example     string `json:"example,omitempty"`     // Example value
}

AIVarDetail represents a detailed description of a variable for AI understanding

func (AIVarDetail) ToAIString

func (d AIVarDetail) ToAIString() string

ToAIString converts AIVarDetail to a detailed string for AI understanding

func (AIVarDetail) ToJSON

func (d AIVarDetail) ToJSON() string

ToJSON converts AIVarDetail to JSON for structured AI consumption

type BuiltinToolExecution

type BuiltinToolExecution struct {
	*ChildExecution
	ToolName string
}

BuiltinToolExecution represents an execution of a built-in tool (get_variable, set_variable).

func NewBuiltinToolExecution

func NewBuiltinToolExecution(parentID, orchestratorID idwrap.IDWrap, toolName string, iterIndex int) *BuiltinToolExecution

NewBuiltinToolExecution creates a new isolated execution for a built-in tool.

type ChainInfo

type ChainInfo struct {
	FromTool  string // Source tool name (e.g., "GetUser")
	FromPath  string // Output path (e.g., "response.body.id")
	ToParam   string // Target parameter name (e.g., "userId")
	ToTool    string // Target tool name (e.g., "GetPosts")
	ParamType string // Expected type
}

ChainInfo represents how outputs from one tool connect to inputs of another

func BuildChainFromParams

func BuildChainFromParams(toolName string, params []AIParam) []ChainInfo

BuildChainFromParams analyzes AI params and builds chain info

type ChildExecution

type ChildExecution struct {
	ExecutionID idwrap.IDWrap
	ParentID    idwrap.IDWrap // Parent orchestrator's execution ID
	NodeID      idwrap.IDWrap
	Name        string
	Tracker     *tracking.VariableTracker
}

ChildExecution represents an isolated execution context for child operations (provider calls, tool calls) within the orchestrator. Each child gets its own tracker so its data doesn't leak into the parent orchestrator's output.

func NewChildExecution

func NewChildExecution(parentID, nodeID idwrap.IDWrap, name string) *ChildExecution

NewChildExecution creates a new isolated execution context for a child operation.

func (*ChildExecution) EmitStatus

func (e *ChildExecution) EmitStatus(
	logFunc func(runner.FlowNodeStatus),
	state mflow.NodeState,
	err error,
	iterContext *runner.IterationContext,
	iterIndex int,
	loopNodeID idwrap.IDWrap,
)

EmitStatus emits a FlowNodeStatus for this child execution.

func (*ChildExecution) GetInputData

func (e *ChildExecution) GetInputData() map[string]any

GetInputData returns the tracked input data as a tree structure.

func (*ChildExecution) GetOutputData

func (e *ChildExecution) GetOutputData() map[string]any

GetOutputData returns the tracked output data as a tree structure.

func (*ChildExecution) TrackInput

func (e *ChildExecution) TrackInput(key string, value any)

TrackInput records input data for this child execution.

func (*ChildExecution) TrackOutput

func (e *ChildExecution) TrackOutput(key string, value any)

TrackOutput records output data for this child execution.

type DescribableNode

type DescribableNode interface {
	// GetDescription returns a user-defined description of what this node does,
	// including required inputs and expected outputs.
	GetDescription() string
}

DescribableNode is an optional interface that nodes can implement to provide a user-defined description for AI tool discovery. This is used by PoC #2 to allow users to customize how tools are described to the AI.

type NodeAI

type NodeAI struct {
	FlowNodeID    idwrap.IDWrap
	Name          string
	Prompt        string
	MaxIterations int32
	// ProviderFactory creates LLM clients from credentials (passed to provider)
	ProviderFactory *scredential.LLMProviderFactory
	// EnableDiscoveryTool enables the discover_tools function (PoC #3)
	EnableDiscoveryTool bool
	// DiscoverToolCalls tracks how many times discover_tools was called (for metrics)
	DiscoverToolCalls int
}

NodeAI is an orchestrator node that manages the AI agent loop. It coordinates between the AI Provider (LLM executor), Memory (conversation history), and Tools (connected nodes). Like ForEach, it emits iteration status for each LLM call.

func New

func New(id idwrap.IDWrap, name string, prompt string, maxIterations int32, factory *scredential.LLMProviderFactory) *NodeAI

func (NodeAI) GetID

func (n NodeAI) GetID() idwrap.IDWrap

func (NodeAI) GetName

func (n NodeAI) GetName() string

func (*NodeAI) GetOutputVariables

func (n *NodeAI) GetOutputVariables() []string

GetOutputVariables implements node.VariableIntrospector. Returns the output paths this AI node produces. Note: During iterations, "iteration" is written for observability. After completion, "text" and "total_metrics" contain the final result.

func (*NodeAI) GetRequiredVariables

func (n *NodeAI) GetRequiredVariables() []string

GetRequiredVariables implements node.VariableIntrospector. It extracts all variable references from the Prompt field.

func (NodeAI) RunAsync

func (n NodeAI) RunAsync(ctx context.Context, req *node.FlowNodeRequest, resultChan chan node.FlowNodeResult)

func (NodeAI) RunSync

type NodeTool

type NodeTool struct {
	TargetNode node.FlowNode
	Req        *node.FlowNodeRequest
}

NodeTool wraps any FlowNode to be used by LLM agents.

func NewNodeTool

func NewNodeTool(target node.FlowNode, req *node.FlowNodeRequest) *NodeTool

func (*NodeTool) AsTool

func (nt *NodeTool) AsTool() llm.Tool

AsTool returns the llm.Tool representation of this node tool.

func (*NodeTool) Execute

func (nt *NodeTool) Execute(ctx context.Context, args string) (string, error)

Execute runs the tool and returns a string result (for LLM consumption)

func (*NodeTool) ExecuteWithDetails

func (nt *NodeTool) ExecuteWithDetails(ctx context.Context, args string) ToolExecuteResult

ExecuteWithDetails runs the tool and returns full execution details including AuxiliaryID

type NodeToolExecution

type NodeToolExecution struct {
	*ChildExecution
	ToolName string
}

NodeToolExecution represents an execution of a node tool (HTTP, etc.).

func NewNodeToolExecution

func NewNodeToolExecution(parentID, toolNodeID idwrap.IDWrap, toolName string) *NodeToolExecution

NewNodeToolExecution creates a new isolated execution for a node tool.

type ProviderExecution

type ProviderExecution struct {
	*ChildExecution
	Iteration int
}

ProviderExecution represents an execution of the LLM provider.

func NewProviderExecution

func NewProviderExecution(parentID, providerNodeID idwrap.IDWrap, orchestratorName string, iteration int) *ProviderExecution

NewProviderExecution creates a new isolated execution for a provider call.

type ToolExecuteResult

type ToolExecuteResult struct {
	Output      string
	OutputData  any
	AuxiliaryID *idwrap.IDWrap
	Err         error
}

ToolExecuteResult contains the result of a tool execution

type ToolInfo

type ToolInfo struct {
	Name         string   `json:"name"`
	Description  string   `json:"description"`
	RequiredVars []string `json:"required_variables,omitempty"`
	OutputVars   []string `json:"output_variables,omitempty"`
}

ToolInfo represents information about a tool for discovery

type ToolOverview

type ToolOverview struct {
	Name    string
	Inputs  []AIParam
	Outputs []string
}

ToolOverview represents a simplified view of a tool for AI understanding

Jump to

Keyboard shortcuts

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