{"modulePath":"github.com/contenox/runtime","version":"v0.0.76","isLatest":false,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package taskengine\n\nPackage taskengine provides a configurable workflow system for building AI-powered task chains. It supports LLM interactions, external integrations via hooks, complex branching logic, and robust error handling with retries and timeouts.\n\nKey Features: - Multiple task handlers (condition keys, parsing, hooks, no-op) - Type-safe data passing between tasks - Conditional branching with various operators - External system integration via hooks - Comprehensive debugging and monitoring - Template-based prompt generation\n\ntaskengine enables building AI workflows where tasks are linked in sequence, supporting conditional branching, numeric or scored evaluation, range resolution, and optional integration with external systems (hooks). Each task can invoke an LLM prompt or a custom hook function depending on its type.\n\nHooks are pluggable interfaces that allow tasks to perform side effects — calling APIs, saving data, or triggering custom business logic — outside of prompt-based processing.\n\nTypical use cases:\n\n  - Chatbot systems\n  - Data processing pipelines\n  - Automated decision-making systems\n  - Dynamic content generation (e.g. marketing copy, reports)\n  - AI agent orchestration with branching logic\n  - Decision trees based on LLM outputs\n  - Automation pipelines involving prompts and external system calls\n\n## Constants\n\n```go\nconst (\n\tTermEnd = \"end\"\n)\n```\n\n## Variables\n\n```go\nvar ErrUnsupportedTaskType = errors.New(\"executor does not support the task type\")\n```\nErrUnsupportedTaskType indicates unrecognized task type\n\n## Functions\n\n```go\nfunc ConvertOpenAIToChatHistory(request OpenAIChatRequest) (ChatHistory, int, []Tool, LLMExecutionConfig)\n```\nConvertOpenAIToChatHistory converts an OpenAI-compatible chat request into the internal ChatHistory and LLMExecutionConfig formats used by the task engine.\n\n```go\nfunc ConvertToType(value interface{}, dataType DataType) (interface{}, error)\n```\nConvertToType converts a value to the specified DataType\n\n```go\nfunc SupportedOperators() []string\n```\n\n## Types\n\n```go\ntype CapturedStateUnit struct {\n\tTaskID      string        `json:\"taskID\" example:\"validate_input\"`\n\tTaskHandler string        `json:\"taskHandler\" example:\"condition_key\"`\n\tInputType   DataType      `json:\"inputType\" example:\"string\" openapi_include_type:\"string\"`\n\tOutputType  DataType      `json:\"outputType\" example:\"string\" openapi_include_type:\"string\"`\n\tTransition  string        `json:\"transition\" example:\"valid_input\"`\n\tDuration    time.Duration `json:\"duration\" example:\"452000000\"` // in nanoseconds\n\tError       ErrorResponse `json:\"error\" openapi_include_type:\"taskengine.ErrorResponse\"`\n\tInput       string        `json:\"input\" example:\"This is a test input that needs validation\"`\n\tOutput      string        `json:\"output\" example:\"valid\"`\n\tInputVar    string        `json:\"inputVar\" example:\"input\"` // Which variable was used as input\n}\n```\n\n```go\nfunc (c *CapturedStateUnit) MarshalJSON() ([]byte, error)\n```\n\n```go\nfunc (c *CapturedStateUnit) UnmarshalJSON(data []byte) error\n```\n\n```go\ntype ChainContext struct {\n\tTools       map[string]ToolWithResolution\n\tClientTools []Tool\n}\n```\n\n```go\ntype ChainTerms string\n```\n\n```go\ntype ChatHistory struct {\n\t// Messages is the list of messages in the conversation.\n\tMessages []Message `json:\"messages\"`\n\t// Model is the name of the model to use for the conversation.\n\tModel string `json:\"model\" example:\"mistral:instruct\"`\n\t// InputTokens will be filled by the engine and will hold the number of tokens used for the input.\n\tInputTokens int `json:\"inputTokens\" example:\"15\"`\n\t// OutputTokens will be filled by the engine and will hold the number of tokens used for the output.\n\tOutputTokens int `json:\"outputTokens\" example:\"10\"`\n}\n```\nChatHistory represents a conversation history with an LLM.\n\n```go\ntype ComposeTask struct {\n\t// Selects the variable to compose the current input with.\n\tWithVar string `yaml:\"with_var,omitempty\" json:\"with_var,omitempty\"`\n\t// Strategy defines how values should be merged (\"override\", \"merge_chat_histories\", \"append_string_to_chat_history\").\n\t// Optional; defaults to \"override\" or \"merge_chat_histories\" if both output and WithVar values are ChatHistory.\n\t// \"merge_chat_histories\": If both output and WithVar values are ChatHistory,\n\t// appends the WithVar's Messages to the output's Messages.\n\tStrategy string `yaml:\"strategy,omitempty\" json:\"strategy,omitempty\"`\n}\n```\nComposeTask is a task that composes multiple variables into a single output. the composed output is stored in a variable named after the task ID with \"\\_composed\" suffix. and is also directly mutating the task's output. example:\n\ncompose:\n\n\twith_var: \"chat2\"\n\tstrategy: \"override\"\n\n```go\ntype DataType int\n```\nDataType represents the type of data passed between tasks. All types support JSON/YAML marshaling and unmarshaling.\n\n```go\nconst (\n\tDataTypeAny                DataType = iota // Any type (use sparingly, loses type safety)\n\tDataTypeString                             // String data\n\tDataTypeBool                               // Boolean value\n\tDataTypeInt                                // Integer number\n\tDataTypeFloat                              // Floating-point number\n\tDataTypeVector                             // Embedding vector ([]float64)\n\tDataTypeSearchResults                      // Search results array\n\tDataTypeJSON                               // Generic JSON data\n\tDataTypeChatHistory                        // Chat conversation history\n\tDataTypeOpenAIChat                         // OpenAI chat request format\n\tDataTypeOpenAIChatResponse                 // OpenAI chat response format\n\tDataTypeNil                                // Nil value\n)\n```\n\n```go\nfunc DataTypeFromString(s string) (DataType, error)\n```\nDataTypeFromString converts a string to DataType, returns error for unknown types.\n\n```go\nfunc (d DataType) MarshalJSON() ([]byte, error)\n```\n\n```go\nfunc (d DataType) MarshalYAML() ([]byte, error)\n```\n\n```go\nfunc (d *DataType) String() string\n```\nString returns the string representation of the data type.\n\n```go\nfunc (dt *DataType) UnmarshalJSON(data []byte) error\n```\n\n```go\nfunc (dt *DataType) UnmarshalYAML(data []byte) error\n```\n\n```go\ntype EnvExecutor interface {\n\t// ExecEnv executes a task chain with the given input and data type.\n\t// Returns final output, output type, execution history, and error.\n\tExecEnv(ctx context.Context, chain *TaskChainDefinition, input any, dataType DataType) (any, DataType, []CapturedStateUnit, error)\n}\n```\nEnvExecutor executes complete task chains with input and environment management.\n\n```go\nfunc NewEnv(\n\t_ context.Context,\n\ttracker libtracker.ActivityTracker,\n\texec TaskExecutor,\n\tinspector Inspector,\n\thookProvider HookRepo,\n) (EnvExecutor, error)\n```\nNewEnv creates a new SimpleEnv with the given tracker and task executor.\n\n```go\ntype ErrorResponse struct {\n\tErrorInternal error  `json:\"-\"`\n\tError         string `json:\"error\" example:\"validation failed: input contains prohibited content\"`\n}\n```\n\n```go\ntype ExecutionState struct {\n\tVariables   map[string]any\n\tDataTypes   map[string]DataType\n\tCurrentTask *TaskDefinition\n}\n```\n\n```go\ntype FunctionCall struct {\n\tName      string `json:\"name\" example:\"get_current_weather\"`\n\tArguments string `json:\"arguments\" example:\"{\\n  \\\"location\\\": \\\"San Francisco, CA\\\",\\n  \\\"unit\\\": \\\"celsius\\\"\\n}\"`\n}\n```\nFunctionCall specifies the function name and arguments for a tool call.\n\n```go\ntype FunctionCallObject struct {\n\tName      string `json:\"name\" example:\"get_current_weather\"`\n\tArguments any    `json:\"arguments\"`\n}\n```\n\n```go\ntype FunctionTool struct {\n\tName        string      `json:\"name\"`\n\tDescription string      `json:\"description,omitempty\"`\n\tParameters  interface{} `json:\"parameters,omitempty\"` // JSON Schema object\n}\n```\nFunctionTool defines the schema for a function-type tool.\n\n```go\ntype HookCall struct {\n\t// Name is the registered hook-service (e.g., \"send_email\").\n\tName string `yaml:\"name\" json:\"name\" example:\"slack\"`\n\n\t// ToolName is the name of the tool to invoke (e.g., \"send_slack_notification\").\n\tToolName string `yaml:\"tool_name\" json:\"tool_name\" example:\"send_slack_notification\"`\n\t// Args are key-value pairs to parameterize the hook call.\n\t// Example: {\"to\": \"user@example.com\", \"subject\": \"Notification\"}\n\tArgs map[string]string `yaml:\"args\" json:\"args\" example:\"{\\\"channel\\\": \\\"#alerts\\\", \\\"message\\\": \\\"Task completed successfully\\\"}\"`\n}\n```\nHookCall represents an external integration or side-effect triggered during a task. Hooks allow tasks to interact with external systems (e.g., \"send\\_email\", \"update\\_db\").\n\n```go\ntype HookProvider interface {\n\tHookRegistry\n\tHooksWithSchema\n}\n```\n\n```go\ntype HookRegistry interface {\n\tSupports(ctx context.Context) ([]string, error)\n}\n```\n\n```go\ntype HookRepo interface {\n\t// Exec executes a hook with the given input and arguments.\n\t// Returns the hook's output or an error.\n\tExec(ctx context.Context, startingTime time.Time, input any, args *HookCall) (any, DataType, error)\n\t// HookRegistry provides hook discovery functionality.\n\tHookRegistry\n\tHooksWithSchema\n}\n```\nHookRepo defines interface for external system integrations and side effects.\n\n```go\ntype HooksWithSchema interface {\n\tGetSchemasForSupportedHooks(ctx context.Context) (map[string]*openapi3.T, error)\n\tGetToolsForHookByName(ctx context.Context, name string) ([]Tool, error)\n}\n```\n\n```go\ntype Inspector interface {\n\tStart(ctx context.Context) StackTrace\n}\n```\n\n```go\nfunc NewSimpleInspector() Inspector\n```\n\n```go\ntype KVActivitySink struct {\n\t// contains filtered or unexported fields\n}\n```\n\n```go\nfunc NewKVActivityTracker(kvManager libkv.KVManager) *KVActivitySink\n```\n\n```go\nfunc (t *KVActivitySink) GetActivityLogs(ctx context.Context, limit int) ([]TrackedEvent, error)\n```\n\n```go\nfunc (t *KVActivitySink) GetActivityLogsByRequestID(ctx context.Context, requestID string) ([]TrackedEvent, error)\n```\n\n```go\nfunc (t *KVActivitySink) GetExecutionStateByRequestID(ctx context.Context, requestID string) ([]CapturedStateUnit, error)\n```\n\n```go\nfunc (t *KVActivitySink) GetKnownOperations(ctx context.Context) ([]Operation, error)\n```\n\n```go\nfunc (t *KVActivitySink) GetRecentRequestIDs(ctx context.Context, limit int) ([]TrackedRequest, error)\n```\n\n```go\nfunc (t *KVActivitySink) GetRequestIDByOperation(ctx context.Context, operation Operation) ([]TrackedRequest, error)\n```\n\n```go\nfunc (t *KVActivitySink) GetStatefulRequests(ctx context.Context) ([]string, error)\n```\n\n```go\nfunc (t *KVActivitySink) Start(\n\tctx context.Context,\n\toperation string,\n\tsubject string,\n\tkvArgs ...any,\n) (func(error), func(string, any), func())\n```\n\n```go\ntype LLMExecutionConfig struct {\n\tModel            string   `yaml:\"model\" json:\"model\" example:\"mistral:instruct\"`\n\tModels           []string `yaml:\"models,omitempty\" json:\"models,omitempty\" example:\"[\\\"gpt-4\\\", \\\"gpt-3.5-turbo\\\"]\"`\n\tProvider         string   `yaml:\"provider,omitempty\" json:\"provider,omitempty\" example:\"ollama\"`\n\tProviders        []string `yaml:\"providers,omitempty\" json:\"providers,omitempty\" example:\"[\\\"ollama\\\", \\\"openai\\\"]\"`\n\tTemperature      float32  `yaml:\"temperature,omitempty\" json:\"temperature,omitempty\" example:\"0.7\"`\n\tHooks            []string `yaml:\"hooks,omitempty\" json:\"hooks,omitempty\" example:\"[\\\"slack_notification\\\", \\\"email_notification\\\"]\"`\n\tHideTools        []string `yaml:\"hide_tools,omitempty\" json:\"hide_tools,omitempty\" example:\"[\\\"tool1\\\", \\\"hook_name1.tool1\\\"]\"`\n\tPassClientsTools bool     `yaml:\"pass_clients_tools\" json:\"pass_clients_tools\"`\n}\n```\nLLMExecutionConfig represents configuration for executing tasks using Large Language Models (LLMs).\n\n```go\ntype Message struct {\n\t// ID is the unique identifier for the message.\n\t// This field is not used by the engine. It can be filled as part of the Request, or left empty.\n\t// The ID is useful for tracking messages and computing differences of histories before storage.\n\tID string `json:\"id\" example:\"msg_123456\"`\n\t// Role is the role of the message sender.\n\tRole string `json:\"role\" example:\"user\"`\n\t// Content is the content of the message.\n\tContent string `json:\"content,omitempty\" example:\"What is the capital of France?\"`\n\t// ToolCallID is the ID of the tool call associated with the message.\n\tToolCallID string `json:\"tool_call_id,omitempty\"`\n\t// CallTools is the tool call of the message sender.\n\tCallTools []ToolCall `json:\"callTools,omitempty\"`\n\t// Timestamp is the time the message was sent.\n\tTimestamp time.Time `json:\"timestamp\" example:\"2023-11-15T14:30:45Z\"`\n}\n```\nMessage represents a single message in a chat conversation.\n\n```go\ntype MockTaskExecutor struct {\n\t// Single value responses\n\tMockOutput          any\n\tMockTransitionValue string\n\tMockError           error\n\n\t// Sequence responses\n\tMockOutputSequence          []any\n\tMockTaskTypeSequence        []DataType\n\tMockTransitionValueSequence []string\n\tErrorSequence               []error\n\n\t// Tracking\n\tCalledWithTask   *TaskDefinition\n\tCalledWithInput  any\n\tCalledWithPrompt string\n\t// contains filtered or unexported fields\n}\n```\nMockTaskExecutor is a mock implementation of taskengine.TaskExecutor.\n\n```go\nfunc (m *MockTaskExecutor) CallCount() int\n```\nCallCount returns how many times TaskExec was called\n\n```go\nfunc (m *MockTaskExecutor) Reset()\n```\nReset clears all mock state between tests\n\n```go\nfunc (m *MockTaskExecutor) TaskExec(ctx context.Context, startingTime time.Time, tokenLimit int, chainContext *ChainContext, currentTask *TaskDefinition, input any, dataType DataType) (any, DataType, string, error)\n```\nTaskExec is the mock implementation of the TaskExec method.\n\n```go\ntype OpenAIChatRequest struct {\n\tModel            string                     `json:\"model\" example:\"mistral:instruct\"`\n\tMessages         []OpenAIChatRequestMessage `json:\"messages\" openapi_include_type:\"taskengine.OpenAIChatRequestMessage\"`\n\tTools            []Tool                     `json:\"tools,omitempty\"`\n\tToolChoice       interface{}                `json:\"tool_choice,omitempty\"` // Can be \"none\", \"auto\", or {\"type\": \"function\", \"function\": {\"name\": \"my_function\"}}\n\tMaxTokens        int                        `json:\"max_tokens,omitempty\" example:\"512\"`\n\tTemperature      float64                    `json:\"temperature,omitempty\" example:\"0.7\"`\n\tTopP             float64                    `json:\"top_p,omitempty\" example:\"1.0\"`\n\tStop             []string                   `json:\"stop,omitempty\" example:\"[\\\"\\\\n\\\", \\\"###\\\"]\"`\n\tN                int                        `json:\"n,omitempty\" example:\"1\"`\n\tStream           bool                       `json:\"stream,omitempty\" example:\"false\"`\n\tPresencePenalty  float64                    `json:\"presence_penalty,omitempty\" example:\"0.0\"`\n\tFrequencyPenalty float64                    `json:\"frequency_penalty,omitempty\" example:\"0.0\"`\n\tUser             string                     `json:\"user,omitempty\" example:\"user_123\"`\n}\n```\nOpenAIChatRequest represents a request compatible with OpenAI's chat API.\n\n```go\nfunc ConvertChatHistoryToOpenAIRequest(\n\tchatHistory ChatHistory,\n) (OpenAIChatRequest, int, int)\n```\n\n```go\ntype OpenAIChatRequestMessage struct {\n\tRole    string `json:\"role\" example:\"user\"`\n\tContent string `json:\"content\" example:\"Hello, how are you?\"`\n}\n```\n\n```go\ntype OpenAIChatResponse struct {\n\tID                string                     `json:\"id\" example:\"chat_123\"`\n\tObject            string                     `json:\"object\" example:\"chat.completion\"`\n\tCreated           int64                      `json:\"created\" example:\"1690000000\"`\n\tModel             string                     `json:\"model\" example:\"mistral:instruct\"`\n\tChoices           []OpenAIChatResponseChoice `json:\"choices\" openapi_include_type:\"taskengine.OpenAIChatResponseChoice\"`\n\tUsage             OpenAITokenUsage           `json:\"usage\" openapi_include_type:\"taskengine.OpenAITokenUsage\"`\n\tSystemFingerprint string                     `json:\"system_fingerprint,omitempty\" example:\"system_456\"`\n}\n```\n\n```go\nfunc ConvertChatHistoryToOpenAI(id string, chatHistory ChatHistory) OpenAIChatResponse\n```\nConvertChatHistoryToOpenAI converts the internal ChatHistory format to an OpenAI-compatible response. This is useful for adapting the task engine's output to systems expecting an OpenAI API format.\n\n```go\ntype OpenAIChatResponseChoice struct {\n\tIndex        int                       `json:\"index\" example:\"0\"`\n\tMessage      OpenAIChatResponseMessage `json:\"message\" openapi_include_type:\"taskengine.OpenAIChatResponseMessage\"`\n\tFinishReason string                    `json:\"finish_reason\" example:\"stop\"`\n}\n```\nOpenAIChatResponseChoice represents a single choice in an OpenAI chat response.\n\n```go\ntype OpenAIChatResponseMessage struct {\n\tRole      string     `json:\"role\" example:\"assistant\"`\n\tContent   *string    `json:\"content,omitempty\" example:\"I can help with that.\"` // Pointer to handle null content for tool calls\n\tToolCalls []ToolCall `json:\"tool_calls,omitempty\" openapi_include_type:\"taskengine.ToolCall\"`\n}\n```\n\n```go\ntype OpenAITokenUsage struct {\n\tPromptTokens     int `json:\"prompt_tokens\" example:\"100\"`\n\tCompletionTokens int `json:\"completion_tokens\" example:\"50\"`\n\tTotalTokens      int `json:\"total_tokens\" example:\"150\"`\n}\n```\n\n```go\ntype Operation struct {\n\tOperation string `json:\"operation\"`\n\tSubject   string `json:\"subject\"`\n}\n```\n\n```go\ntype OperatorTerm string\n```\nOperatorTerm represents logical operators used for task transition evaluation\n\n```go\nconst (\n\tOpEquals      OperatorTerm = \"equals\"\n\tOpContains    OperatorTerm = \"contains\"\n\tOpStartsWith  OperatorTerm = \"starts_with\"\n\tOpEndsWith    OperatorTerm = \"ends_with\"\n\tOpGreaterThan OperatorTerm = \"\u003e\"\n\tOpGt          OperatorTerm = \"gt\"\n\tOpLessThan    OperatorTerm = \"\u003c\"\n\tOpLt          OperatorTerm = \"lt\"\n\tOpInRange     OperatorTerm = \"in_range\"\n\tOpDefault     OperatorTerm = \"default\"\n)\n```\n\n```go\nfunc ToOperatorTerm(s string) (OperatorTerm, error)\n```\n\n```go\nfunc (t OperatorTerm) String() string\n```\n\n```go\ntype SearchResult struct {\n\tID           string  `json:\"id\" example:\"search_123456\"`\n\tResourceType string  `json:\"type\" example:\"document\"`\n\tDistance     float32 `json:\"distance\" example:\"0.85\"`\n}\n```\n\n```go\ntype SimpleEnv struct {\n\t// contains filtered or unexported fields\n}\n```\nSimpleEnv is the default implementation of EnvExecutor. this is the default EnvExecutor implementation It executes tasks in order, using retry and timeout policies, and tracks execution progress using an ActivityTracker.\n\n```go\nfunc (env SimpleEnv) ExecEnv(ctx context.Context, chain *TaskChainDefinition, input any, dataType DataType) (any, DataType, []CapturedStateUnit, error)\n```\nExecEnv executes the given chain with the provided input.\n\nIt manages the full lifecycle of task execution: rendering prompts, calling the TaskExecutor, handling timeouts, retries, transitions, and collecting final output.\n\n```go\ntype SimpleExec struct {\n\t// contains filtered or unexported fields\n}\n```\nSimpleExec is a basic implementation of TaskExecutor. It supports prompt-to-string, number, score, range, boolean condition evaluation, and delegation to registered hooks.\n\n```go\nfunc (exe *SimpleExec) Embed(ctx context.Context, llmCall LLMExecutionConfig, prompt string) ([]float64, error)\n```\nPrompt resolves a model client and sends the prompt to be executed. Returns the trimmed response string or an error.\n\n```go\nfunc (exe *SimpleExec) Prompt(ctx context.Context, systemInstruction string, llmCall LLMExecutionConfig, prompt string) (string, error)\n```\nPrompt resolves a model client using the resolver policy and sends the prompt to be executed. Returns the trimmed response string or an error.\n\n```go\nfunc (exe *SimpleExec) TaskExec(taskCtx context.Context, startingTime time.Time, ctxLength int, chainContext *ChainContext, currentTask *TaskDefinition, input any, dataType DataType) (any, DataType, string, error)\n```\nTaskExec dispatches task execution based on the task type.\n\n```go\ntype SimpleStackTrace struct {\n\t// contains filtered or unexported fields\n}\n```\n\n```go\nfunc (s *SimpleStackTrace) ClearBreakpoints()\n```\n\n```go\nfunc (s *SimpleStackTrace) GetCurrentState() ExecutionState\n```\n\n```go\nfunc (s *SimpleStackTrace) GetExecutionHistory() []CapturedStateUnit\n```\n\n```go\nfunc (s *SimpleStackTrace) HasBreakpoint(taskID string) bool\n```\n\n```go\nfunc (s *SimpleStackTrace) RecordStep(step CapturedStateUnit)\n```\n\n```go\nfunc (s *SimpleStackTrace) SetBreakpoint(taskID string)\n```\n\n```go\ntype StackTrace interface {\n\t// Observation\n\tRecordStep(step CapturedStateUnit)\n\tGetExecutionHistory() []CapturedStateUnit\n\n\t// Control\n\tSetBreakpoint(taskID string)\n\tClearBreakpoints()\n\n\tHasBreakpoint(taskID string) bool\n}\n```\n\n```go\ntype TaskChainDefinition struct {\n\t// ID uniquely identifies the chain.\n\tID string `yaml:\"id\" json:\"id\"`\n\n\t// Enables capturing user input and output.\n\tDebug bool `yaml:\"debug\" json:\"debug\"`\n\n\t// Description provides a human-readable summary of the chain's purpose.\n\tDescription string `yaml:\"description\" json:\"description\"`\n\n\t// Tasks is the list of tasks to execute in sequence.\n\tTasks []TaskDefinition `yaml:\"tasks\" json:\"tasks\" openapi_include_type:\"taskengine.TaskDefinition\"`\n\n\t// TokenLimit is the token limit for the context window (used during execution).\n\tTokenLimit int64 `yaml:\"token_limit\" json:\"token_limit\"`\n}\n```\nTaskChainDefinition describes a sequence of tasks to execute in order, along with branching logic, retry policies, and model preferences.\n\nTaskChainDefinition support dynamic routing based on LLM outputs or conditions, and can include hooks to perform external actions (e.g., sending emails).\n\n```go\ntype TaskDefinition struct {\n\t// ID uniquely identifies the task within the chain.\n\tID string `yaml:\"id\" json:\"id\" example:\"validate_input\"`\n\n\t// Description is a human-readable summary of what the task does.\n\tDescription string `yaml:\"description\" json:\"description\" example:\"Validates user input meets quality requirements\"`\n\n\t// Handler determines how the LLM output (or hook) will be interpreted.\n\tHandler TaskHandler `yaml:\"handler\" json:\"handler\" example:\"condition_key\" openapi_include_type:\"string\"`\n\n\t// SystemInstruction provides additional instructions to the LLM, if applicable system level will be used.\n\tSystemInstruction string `yaml:\"system_instruction,omitempty\" json:\"system_instruction,omitempty\" example:\"You are a quality control assistant. Respond only with 'valid' or 'invalid'.\"`\n\n\t// ValidConditions defines allowed values for ConditionKey tasks.\n\t// Required for ConditionKey tasks, ignored for all other types.\n\t// Example: {\"yes\": true, \"no\": true} for a yes/no condition.\n\tValidConditions map[string]bool `yaml:\"valid_conditions,omitempty\" json:\"valid_conditions,omitempty\" example:\"{\\\"valid\\\": true, \\\"invalid\\\": true}\"`\n\n\t// ExecuteConfig defines the configuration for executing prompt or chat model tasks.\n\tExecuteConfig *LLMExecutionConfig `yaml:\"execute_config,omitempty\" json:\"execute_config,omitempty\" openapi_include_type:\"taskengine.LLMExecutionConfig\"`\n\n\t// Hook defines an external action to run.\n\t// Required for Hook tasks, must be nil/omitted for all other types.\n\t// Example: {type: \"send_email\", args: {\"to\": \"user@example.com\"}}\n\tHook *HookCall `yaml:\"hook,omitempty\" json:\"hook,omitempty\" openapi_include_type:\"taskengine.HookCall\"`\n\n\t// Print optionally formats the output for display/logging.\n\t// Supports template variables from previous task outputs.\n\t// Optional for all task types except Hook where it's rarely used.\n\t// Example: \"The score is: {{.previous_output}}\"\n\tPrint string `yaml:\"print,omitempty\" json:\"print,omitempty\" example:\"Validation result: {{.validate_input}}\"`\n\n\t// PromptTemplate is the text prompt sent to the LLM.\n\t// It's Required and only applicable for the raw_string type.\n\t// Supports template variables from previous task outputs.\n\t// Example: \"Rate the quality from 1-10: {{.input}}\"\n\tPromptTemplate string `yaml:\"prompt_template\" json:\"prompt_template\" example:\"Is this input valid? {{.input}}\"`\n\n\t// OutputTemplate is an optional go template to format the output of a hook.\n\t// If specified, the hook's JSON output will be used as data for the template.\n\t// The final output of the task will be the rendered string.\n\t// Example: \"The weather is {{.weather}} with a temperature of {{.temperature}}.\"\n\tOutputTemplate string `yaml:\"output_template,omitempty\" json:\"output_template,omitempty\" example:\"Hook result: {{.status}}\"`\n\n\t// InputVar is the name of the variable to use as input for the task.\n\t// Example: \"input\" for the original input.\n\t// Each task stores its output in a variable named with it's task id.\n\tInputVar string `yaml:\"input_var,omitempty\" json:\"input_var,omitempty\" example:\"input\"`\n\n\t// Compose merges the specified the output with the withVar side.\n\t// Optional. compose is applied before the input reaches the task execution,\n\tCompose *ComposeTask `yaml:\"compose,omitempty\" json:\"compose,omitempty\" openapi_include_type:\"taskengine.ComposeTask\"`\n\n\t// Transition defines what to do after this task completes.\n\tTransition TaskTransition `yaml:\"transition\" json:\"transition\" openapi_include_type:\"taskengine.TaskTransition\"`\n\n\t// Timeout optionally sets a timeout for task execution.\n\t// Format: \"10s\", \"2m\", \"1h\" etc.\n\t// Optional for all task types.\n\tTimeout string `yaml:\"timeout,omitempty\" json:\"timeout,omitempty\" example:\"30s\"`\n\n\t// RetryOnFailure sets how many times to retry this task on failure.\n\t// Applies to all task types including Hooks.\n\t// Default: 0 (no retries)\n\tRetryOnFailure int `yaml:\"retry_on_failure,omitempty\" json:\"retry_on_failure,omitempty\" example:\"2\"`\n}\n```\nTaskDefinition represents a single step in a workflow. Each task has a handler that dictates how its prompt will be processed.\n\nField validity by task type: | Field               | ConditionKey | ParseNumber | ParseScore | ParseRange | RawString | Hook  | Noop  | |---------------------|--------------|-------------|------------|------------|-----------|-------|-------| | ValidConditions     | Required     | -           | -          | -          | -         | -     | -     | | Hook                | -            | -           | -          | -          | -         | Req   | -     | | PromptTemplate      | Required     | Required    | Required   | Required   | Required  | -     | Opt   | | OutputTemplate      | -            | -           | -          | -          | -         | Opt   | -     | | Print               | Optional     | Optional    | Optional   | Optional   | Optional  | Opt   | Opt   | | ExecuteConfig       | Optional     | Optional    | Optional   | Optional   | Optional  | -     | -     | | InputVar            | Optional     | Optional    | Optional   | Optional   | Optional  | Opt   | Opt   | | SystemInstruction   | Optional     | Optional    | Optional   | Optional   | Optional  | Opt   | Opt   | | Compose             | Optional     | Optional    | Optional   | Optional   | Optional  | Opt   | Opt   | | Transition          | Required     | Required    | Required   | Required   | Required  | Req   | Req   |\n\n```go\ntype TaskExecutor interface {\n\t// TaskExec executes a single task with the given input and data type.\n\t// Returns:\n\t// - output: The processed task result\n\t// - outputType: The data type of the output\n\t// - transitionEval: String used for transition evaluation\n\t// - error: Any execution error encountered\n\t//\n\t// Parameters:\n\t// - ctx: Context for cancellation and timeouts\n\t// - startingTime: Chain start time for consistent timing\n\t// - ctxLength: Token context length limit for LLM operations\n\t// - chainContext: Immutable context of the chain\n\t// - currentTask: The task definition to execute\n\t// - input: Task input data\n\t// - dataType: Type of the input data\n\tTaskExec(ctx context.Context, startingTime time.Time, ctxLength int, chainContext *ChainContext, currentTask *TaskDefinition, input any, dataType DataType) (any, DataType, string, error)\n}\n```\nTaskExecutor executes individual tasks within a workflow. Implementations should handle all task types and return appropriate outputs.\n\n```go\nfunc NewExec(\n\t_ context.Context,\n\trepo llmrepo.ModelRepo,\n\thookProvider HookRepo,\n\ttracker libtracker.ActivityTracker,\n) (TaskExecutor, error)\n```\nNewExec creates a new SimpleExec instance\n\n```go\ntype TaskHandler string\n```\nTaskHandler defines how task outputs are processed and interpreted.\n\n```go\nconst (\n\t// HandleConditionKey interprets response as a condition key for transition branching.\n\t// Requires ValidConditions to be set with allowed values.\n\tHandleConditionKey TaskHandler = \"condition_key\"\n\n\t// HandleParseNumber expects a numeric response and parses it into an integer.\n\t// Returns error if response cannot be parsed as integer.\n\tHandleParseNumber TaskHandler = \"parse_number\"\n\n\t// HandleParseScore expects a floating-point score (e.g., quality rating).\n\t// Returns error if response cannot be parsed as float.\n\tHandleParseScore TaskHandler = \"parse_score\"\n\n\t// HandleParseRange expects a numeric range like \"5-7\" or single number \"5\" (converted to \"5-5\").\n\t// Returns error if response cannot be parsed as valid range.\n\tHandleParseRange TaskHandler = \"parse_range\"\n\n\t// HandleRawString returns the raw string result from the LLM without parsing.\n\tHandleRawString TaskHandler = \"raw_string\"\n\n\t// HandleEmbedding expects string input and returns an embedding vector ([]float64).\n\t// This is useful as last step in a text enrichment pipeline to enrich the data before embedding.\n\tHandleEmbedding TaskHandler = \"embedding\"\n\n\t// HandleRaiseError raises an error with the provided message from task input.\n\t// Useful for explicit error conditions in workflows.\n\tHandleRaiseError TaskHandler = \"raise_error\"\n\n\t// HandleModelExecution executes specified model on chat history input.\n\t// Requires DataTypeChatHistory input and ExecuteConfig configuration.\n\tHandleModelExecution TaskHandler = \"model_execution\"\n\n\t// HandleExecuteToolCalls executes specified tool calls on chat history input.\n\tHandleExecuteToolCalls TaskHandler = \"execute_tool_calls\"\n\n\t// HandleParseTransition attempts to parse transition commands (e.g., \"/command\").\n\t// Strips transition prefix if present in input.\n\tHandleParseTransition TaskHandler = \"parse_transition\"\n\n\t// HandleParseKeyValue expects a string of key=value pairs and parses it into a JSON object.\n\t// Example input: \"name=John, age=30, city=New York\"\n\t// Returns a map[string]string that can be serialized as JSON.\n\tHandleParseKeyValue TaskHandler = \"parse_key_value\"\n\n\t// HandleConvertToOpenAIChatResponse converts a chat history input to OpenAI Chat format.\n\t// Requires DataTypeChatHistory input and ExecuteConfig configuration.\n\tHandleConvertToOpenAIChatResponse TaskHandler = \"convert_to_openai_chat_response\"\n\n\t// HandleNoop performs no operation, passing input through unchanged.\n\t// Useful for data mutation, variable composition, and transition steps.\n\tHandleNoop TaskHandler = \"noop\"\n\n\t// HandleHook executes an external action via registered hook rather than calling LLM.\n\t// Requires Hook configuration with name and arguments.\n\tHandleHook TaskHandler = \"hook\"\n)\n```\n\n```go\nfunc (t TaskHandler) String() string\n```\n\n```go\ntype TaskTransition struct {\n\t// OnFailure is the task ID to jump to in case of failure.\n\tOnFailure string `yaml:\"on_failure\" json:\"on_failure\" example:\"error_handler\"`\n\n\t// Branches defines conditional branches for successful task completion.\n\tBranches []TransitionBranch `yaml:\"branches\" json:\"branches\" openapi_include_type:\"taskengine.TransitionBranch\"`\n}\n```\nTaskTransition defines what happens after a task completes, including which task to go to next and how to handle errors.\n\n```go\ntype Tool struct {\n\tType     string       `json:\"type\"`\n\tFunction FunctionTool `json:\"function\"`\n}\n```\nOpenAIChatRequest represents a request compatible with OpenAI's chat API. Tool represents a tool that can be called by the model.\n\n```go\ntype ToolCall struct {\n\tID       string       `json:\"id\" example:\"call_abc123\"`\n\tType     string       `json:\"type\" example:\"function\"`\n\tFunction FunctionCall `json:\"function\" openapi_include_type:\"taskengine.FunctionCall\"`\n}\n```\nToolCall represents a tool call requested by the model.\n\n```go\ntype ToolWithResolution struct {\n\tTool\n\tHookName string\n}\n```\n\n```go\ntype TrackedEvent struct {\n\tID         string            `json:\"id\"`\n\tOperation  string            `json:\"operation\"`\n\tSubject    string            `json:\"subject\"`\n\tStart      time.Time         `json:\"start\"`\n\tEnd        *time.Time        `json:\"end,omitempty\"`\n\tError      *string           `json:\"error,omitempty\"`\n\tEntityID   *string           `json:\"entityID,omitempty\"`\n\tEntityData any               `json:\"entityData,omitempty\"`\n\tDuration   float64           `json:\"duration\"` // Duration in milliseconds\n\tMetadata   map[string]string `json:\"metadata,omitempty\"`\n\tRequestID  string            `json:\"requestID,omitempty\"`\n}\n```\n\n```go\ntype TrackedRequest struct {\n\tID string `json:\"id\"`\n}\n```\n\n```go\ntype TransitionBranch struct {\n\t// Operator defines how to compare the task's output to When.\n\tOperator OperatorTerm `yaml:\"operator,omitempty\" json:\"operator,omitempty\" example:\"equals\" openapi_include_type:\"string\"`\n\n\t// When specifies the condition that must be met to follow this branch.\n\t// Format depends on the task type:\n\t// - For condition_key: exact string match\n\t// - For parse_number: numeric comparison (using Operator)\n\tWhen string `yaml:\"when\" json:\"when\" example:\"yes\"`\n\n\t// Goto specifies the target task ID if this branch is taken.\n\t// Leave empty or use taskengine.TermEnd to end the chain.\n\tGoto string `yaml:\"goto\" json:\"goto\" example:\"positive_response\"`\n}\n```\nTransitionBranch defines a single possible path in the workflow, selected when the task's output matches the specified condition.\n\n","path":"github.com/contenox/runtime/taskengine","name":"taskengine","synopsis":"Package taskengine provides a configurable workflow system for building AI-powered task chains.","isRedistributable":true}
