taskengine

package
v1.0.0-rc.9 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: Apache-2.0 Imports: 31 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	ContextKeyOutputByteLimit contextKey = "output_byte_limit"
	ContextKeyToolCallID      contextKey = "tool_call_id"
	ContextKeyToolArgsMissing contextKey = "tool_args_missing"
)
View Source
const (
	TransitionExecuted      = "executed"
	TransitionToolCall      = "tool_call"
	TransitionNoop          = "noop"
	TransitionNoCallsFound  = "no_calls_found"
	TransitionToolsExecuted = "tools_executed"
	TransitionFailed        = "failed"
)
View Source
const CheckpointSchemaVersion = 1
View Source
const FallbackContextTokens = 131072
View Source
const (
	MaxToolResultImageBytes = 5 << 20
)
View Source
const TaskEventSubjectAll = "taskengine.events"
View Source
const TemplateVarModelPinned = "model_pinned"
View Source
const (
	TermEnd = "end"
)

Variables

View Source
var ErrChainLint = errors.New("chain failed load-time validation")
View Source
var ErrCheckpointVersion = errors.New("taskengine: unsupported checkpoint schema version")
View Source
var ErrContextLengthExceeded = errors.New("exceeds context length")
View Source
var ErrGateRecordFailed = errors.New("taskengine: gated call executed but recording its result failed")
View Source
var ErrToolsNotFound = errors.New("tools not found")
View Source
var ErrToolsToolsUnavailable = errors.New("tools tools unavailable")
View Source
var ErrUnsupportedTaskType = errors.New("executor does not support the task type")

Functions

func ApprovalVerdictFromContext

func ApprovalVerdictFromContext(ctx context.Context, approvalID string) (approved bool, ok bool)

func AsksDetached

func AsksDetached(ctx context.Context) bool

func ConvertToType

func ConvertToType(value interface{}, dataType DataType) (interface{}, error)

func EdgeCountsFromContext

func EdgeCountsFromContext(ctx context.Context) map[string]int

func ExportedApplyAllowlist

func ExportedApplyAllowlist(allowlist []string, all []string) []string

func ExportedApplyTaskAllowlist

func ExportedApplyTaskAllowlist(allowlist []string, all []string) []string

func ExportedResolveToolsNames

func ExportedResolveToolsNames(ctx context.Context, allowlist []string, provider ToolsProvider) ([]string, error)

func ExtractJSONArray

func ExtractJSONArray(s string) string

func ExtractJSONObject

func ExtractJSONObject(s string) string

func GetPrimaryModel

func GetPrimaryModel(llmCall *LLMExecutionConfig) string

func HasCheckpointSaver

func HasCheckpointSaver(ctx context.Context) bool

func IsAssistantProseHandler

func IsAssistantProseHandler(handler string) bool

func IsToolBearingHandler

func IsToolBearingHandler(handler string) bool

func LintChain

func LintChain(chain *TaskChainDefinition, entryTypes ...DataType) error

func MarshalCheckpoint

func MarshalCheckpoint(cp *Checkpoint) ([]byte, error)

func MarshalGateResult

func MarshalGateResult(r GateResult) ([]byte, error)

func MergeTemplateVars

func MergeTemplateVars(ctx context.Context, overlay map[string]string) context.Context

func RequestedContextLengthFromContext added in v0.33.0

func RequestedContextLengthFromContext(ctx context.Context) int

func RuntimeHiddenTools

func RuntimeHiddenTools(ctx context.Context) []string

func RuntimeToolsAllowlistFromContext

func RuntimeToolsAllowlistFromContext(ctx context.Context) ([]string, bool)

func StateSubject

func StateSubject(reqID string) string

func StripCodeFences

func StripCodeFences(s string) string

func SupportedOperators

func SupportedOperators() []string

func TaskEventRequestSubject

func TaskEventRequestSubject(requestID string) string

func TemplateVarsFromContext

func TemplateVarsFromContext(ctx context.Context) (map[string]string, error)

func ToolArgsMissingFromContext

func ToolArgsMissingFromContext(ctx context.Context) bool

func ToolCallSuspendable

func ToolCallSuspendable(ctx context.Context) bool

func ToolsArgsFromContext

func ToolsArgsFromContext(ctx context.Context, toolsName string) map[string]string

func ToolsToolsUnavailable

func ToolsToolsUnavailable(toolsName string, cause error) error

func WithApprovalVerdicts

func WithApprovalVerdicts(ctx context.Context, verdicts map[string]bool) context.Context

func WithAttentionAnswers

func WithAttentionAnswers(ctx context.Context, answers map[string]AttentionAnswer) context.Context

func WithCheckpointSaver

func WithCheckpointSaver(ctx context.Context, saver CheckpointSaver) context.Context

func WithDetachedAsks

func WithDetachedAsks(ctx context.Context) context.Context

func WithEdgeCounts

func WithEdgeCounts(ctx context.Context, counts map[string]int) context.Context

func WithGateResultRecorder

func WithGateResultRecorder(ctx context.Context, rec GateResultRecorder) context.Context

func WithGateResultStore

func WithGateResultStore(ctx context.Context, store *GateResultStore) context.Context

func WithRequestedContextLength added in v0.33.0

func WithRequestedContextLength(ctx context.Context, contextLength int) context.Context

func WithResumeCheckpoint

func WithResumeCheckpoint(ctx context.Context, cp *Checkpoint) context.Context

func WithRetryOutcomeSink

func WithRetryOutcomeSink(ctx context.Context, sink *RetryOutcomeSink) context.Context

func WithRuntimeToolsAllowlist

func WithRuntimeToolsAllowlist(ctx context.Context, allowlist []string) context.Context

func WithSuspendableToolCall

func WithSuspendableToolCall(ctx context.Context) context.Context

func WithTaskEventScope

func WithTaskEventScope(ctx context.Context, scope TaskEventScope) context.Context

func WithTaskEventSink

func WithTaskEventSink(ctx context.Context, sink TaskEventSink) context.Context

func WithTemplateVars

func WithTemplateVars(ctx context.Context, vars map[string]string) context.Context

func WithToolArgsMissing

func WithToolArgsMissing(ctx context.Context, missing bool) context.Context

func WithToolsArgs

func WithToolsArgs(ctx context.Context, toolsName string, args map[string]string) context.Context

Types

type ApprovalPendingError

type ApprovalPendingError struct {
	ApprovalID string
	ToolName   string
}

func (*ApprovalPendingError) Error

func (e *ApprovalPendingError) Error() string

type AttentionAnswer

type AttentionAnswer struct {
	Answered bool
	Text     string
}

func AttentionAnswerFromContext

func AttentionAnswerFromContext(ctx context.Context, askID string) (ans AttentionAnswer, ok bool)

type AudioPart

type AudioPart struct {
	Data     []byte `json:"data"`
	MimeType string `json:"mime_type" example:"audio/wav"`
}

type BusInspector

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

func NewBusInspector

func NewBusInspector(inner Inspector, bus libbus.Messenger, tracker libtracker.ActivityTracker) *BusInspector

func (*BusInspector) Start

func (i *BusInspector) Start(ctx context.Context) StackTrace

type BusTaskEventSink

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

func NewBusTaskEventSink

func NewBusTaskEventSink(bus libbus.Messenger) *BusTaskEventSink

func (*BusTaskEventSink) PublishTaskEvent

func (s *BusTaskEventSink) PublishTaskEvent(ctx context.Context, event TaskEvent) error

func (*BusTaskEventSink) Wants

type CapturedPayloadSummary added in v0.29.0

type CapturedPayloadSummary struct {
	Truncated         bool   `json:"truncated"`
	Reason            string `json:"reason"`
	OriginalType      string `json:"originalType,omitempty"`
	OriginalJSONBytes int    `json:"originalJsonBytes,omitempty"`
	SHA256            string `json:"sha256,omitempty"`
	Preview           string `json:"preview,omitempty"`
	PreviewBytes      int    `json:"previewBytes,omitempty"`
}

type CapturedStateUnit

type CapturedStateUnit struct {
	Scope       EventScope    `json:"scope,omitzero"`
	TaskID      string        `json:"taskID" example:"validate_input"`
	TaskHandler string        `json:"taskHandler" example:"chat_completion"`
	InputType   DataType      `json:"inputType" example:"string"`
	OutputType  DataType      `json:"outputType" example:"string"`
	Transition  string        `json:"transition" example:"valid_input"`
	Duration    time.Duration `json:"duration" example:"452000000"`
	Error       ErrorResponse `json:"error"`
	Input       any           `json:"input,omitempty"`
	Output      any           `json:"output,omitempty"`
	InputVar    string        `json:"inputVar" example:"input"`

	RetryIndex   int         `json:"retryIndex"`
	Cancelled    bool        `json:"cancelled,omitempty"`
	TimedOut     bool        `json:"timedOut,omitempty"`
	ProviderType string      `json:"providerType,omitempty"`
	ModelName    string      `json:"modelName,omitempty"`
	ToolNames    []string    `json:"toolNames,omitempty"`
	TokenUsage   *TokenUsage `json:"tokenUsage,omitempty"`
	FinishReason string      `json:"finishReason,omitempty"`
}

type ChainContext

type ChainContext struct {
	Tools       map[string]ToolWithResolution
	ClientTools []Tool
	Debug       bool
	ModelCall   llmrepo.Meta
}

type ChainSuspendedError

type ChainSuspendedError struct {
	ApprovalID string
	Scope      EventScope
}

func (*ChainSuspendedError) Error

func (e *ChainSuspendedError) Error() string

type ChainTerms

type ChainTerms string

type ChatHistory

type ChatHistory struct {
	Messages     []Message `json:"messages"`
	Model        string    `json:"model" example:"llama2:7b"`
	InputTokens  int       `json:"inputTokens" example:"15"`
	OutputTokens int       `json:"outputTokens" example:"10"`
	FinishReason string    `json:"finishReason,omitempty" example:"stop"`
}

type Checkpoint

type Checkpoint struct {
	ApprovalID        string
	PendingCalls      []PendingToolCall
	Chain             *TaskChainDefinition
	TaskID            string
	RetryIndex        int
	Scope             EventScope
	Vars              map[string]any
	VarTypes          map[string]DataType
	EdgeCounts        map[string]int
	History           ChatHistory
	TemplateVars      map[string]string
	ToolsAllowlist    []string
	HasToolsAllowlist bool
	ContextLength     int
	SessionID         string
	MissionID         string
	RequestID         string
	ChainRef          string
	CreatedAt         time.Time
}

func UnmarshalCheckpoint

func UnmarshalCheckpoint(raw []byte) (*Checkpoint, error)

type CheckpointSaver

type CheckpointSaver interface {
	SaveCheckpoint(ctx context.Context, cp *Checkpoint) error
}

type ContextShift

type ContextShift struct {
	Window        int `json:"window"`
	Requested     int `json:"requested,omitempty"`
	HistoryBudget int `json:"historyBudget"`
	Reserve       int `json:"reserve"`
	Before        int `json:"before"`
	After         int `json:"after"`
	Removed       int `json:"removed"`
	Kept          int `json:"kept"`
}

type DataType

type DataType int
const (
	DataTypeAny DataType = iota
	DataTypeString
	DataTypeInt
	DataTypeJSON
	DataTypeChatHistory
	DataTypeNil
)

func DataTypeFromString

func DataTypeFromString(s string) (DataType, error)

func InferDataType

func InferDataType(v any) DataType

func NormalizeDataType

func NormalizeDataType(v any, dt DataType) (any, DataType, error)

func NormalizeFinalChainOutput

func NormalizeFinalChainOutput(value any, dt DataType) (any, DataType, error)

func (DataType) MarshalJSON

func (d DataType) MarshalJSON() ([]byte, error)

func (DataType) MarshalYAML

func (d DataType) MarshalYAML() (any, error)

func (*DataType) String

func (d *DataType) String() string

func (*DataType) UnmarshalJSON

func (dt *DataType) UnmarshalJSON(data []byte) error

func (*DataType) UnmarshalYAML

func (dt *DataType) UnmarshalYAML(value *yaml.Node) error

type EnvExecutor

type EnvExecutor interface {
	ExecEnv(ctx context.Context, chain *TaskChainDefinition, input any, dataType DataType) (any, DataType, []CapturedStateUnit, error)
}

func NewEnv

func NewEnv(
	ctx context.Context,
	tracker libtracker.ActivityTracker,
	exec TaskExecutor,
	inspector Inspector,
	toolsProvider ToolsRepo,
) (EnvExecutor, error)

func NewMacroEnv

func NewMacroEnv(inner EnvExecutor, toolsProvider ToolsRepo, opts ...MacroOption) (EnvExecutor, error)

type ErrorResponse

type ErrorResponse struct {
	ErrorInternal error  `json:"-"`
	Error         string `json:"error" example:"validation failed: input contains prohibited content"`
}

type EventScope

type EventScope struct {
	Chain    string `json:"chain,omitempty"`
	Task     string `json:"task,omitempty"`
	ToolCall string `json:"tool_call,omitempty"`
}

type ExecOption

type ExecOption func(*SimpleExec)

func WithToolImagesKept

func WithToolImagesKept(kept ToolImagesKept) ExecOption

type FunctionCall

type FunctionCall struct {
	Name      string `json:"name" example:"get_current_weather"`
	Arguments string `json:"arguments" example:"{\n  \"location\": \"San Francisco, CA\",\n  \"unit\": \"celsius\"\n}"`
}

type FunctionCallObject

type FunctionCallObject struct {
	Name      string `json:"name" example:"get_current_weather"`
	Arguments any    `json:"arguments"`
}

type FunctionTool

type FunctionTool struct {
	Name        string      `json:"name"`
	Description string      `json:"description,omitempty"`
	Parameters  interface{} `json:"parameters,omitempty"`
}

type GateResult

type GateResult struct {
	Value any
	Type  DataType
}

func RecordedGateResultFromContext

func RecordedGateResultFromContext(ctx context.Context, approvalID string) (GateResult, bool)

func UnmarshalGateResult

func UnmarshalGateResult(raw []byte) (GateResult, error)

type GateResultRecorder

type GateResultRecorder func(ctx context.Context, approvalID string, result GateResult) error

func GateResultRecorderFromContext

func GateResultRecorderFromContext(ctx context.Context) GateResultRecorder

type GateResultStore

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

func NewGateResultStore

func NewGateResultStore() *GateResultStore

func (*GateResultStore) Get

func (s *GateResultStore) Get(approvalID string) (GateResult, bool)

func (*GateResultStore) Set

func (s *GateResultStore) Set(approvalID string, r GateResult)

type HandlerOutputMode

type HandlerOutputMode int
const (
	HandlerOutputFixed HandlerOutputMode = iota
	HandlerOutputPassthrough
	HandlerOutputDynamic
	HandlerOutputNone
)

type HandlerSignature

type HandlerSignature struct {
	Inputs       []DataType
	Mode         HandlerOutputMode
	Output       DataType
	SuccessEvals []string
}

func HandlerSignatureFor

func HandlerSignatureFor(h TaskHandler) (HandlerSignature, bool)

func (HandlerSignature) AcceptsInput

func (s HandlerSignature) AcceptsInput(dt DataType) bool

type ImagePart

type ImagePart struct {
	Data     []byte `json:"data"`
	MimeType string `json:"mime_type" example:"image/png"`
}

type Inspector

type Inspector interface {
	Start(ctx context.Context) StackTrace
}

func NewSimpleInspector

func NewSimpleInspector() Inspector

type KVInspector

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

func NewKVInspector

func NewKVInspector(inner Inspector, kv libkv.KVManager, tracker libtracker.ActivityTracker) *KVInspector

func (*KVInspector) ClearExecutionState

func (i *KVInspector) ClearExecutionState(ctx context.Context) (int, error)

func (*KVInspector) GetExecutionStateByRequestID

func (i *KVInspector) GetExecutionStateByRequestID(ctx context.Context, reqID string) ([]CapturedStateUnit, error)

func (*KVInspector) GetStatefulRequests

func (i *KVInspector) GetStatefulRequests(ctx context.Context) ([]string, error)

func (*KVInspector) Start

func (i *KVInspector) Start(ctx context.Context) StackTrace

type KVJournalTaskEventSink added in v0.36.0

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

func NewKVJournalTaskEventSink added in v0.36.0

func NewKVJournalTaskEventSink(inner TaskEventSink, kv libkv.KVManager, tracker libtracker.ActivityTracker) *KVJournalTaskEventSink

func (*KVJournalTaskEventSink) PublishTaskEvent added in v0.36.0

func (s *KVJournalTaskEventSink) PublishTaskEvent(ctx context.Context, event TaskEvent) error

func (*KVJournalTaskEventSink) Wants

func (s *KVJournalTaskEventSink) Wants(kind TaskEventKind) bool

type LLMExecutionConfig

type LLMExecutionConfig struct {
	ModelRole         string                       `yaml:"-" json:"-"`
	Model             string                       `yaml:"model" json:"model" example:"llama2:7b"`
	Models            []string                     `yaml:"models,omitempty" json:"models,omitempty" example:"[\"gpt-4\", \"gpt-3.5-turbo\"]"`
	Provider          string                       `yaml:"provider,omitempty" json:"provider,omitempty" example:"ollama"`
	Providers         []string                     `yaml:"providers,omitempty" json:"providers,omitempty" example:"[\"ollama\", \"openai\"]"`
	Temperature       *float32                     `yaml:"temperature,omitempty" json:"temperature,omitempty" example:"0.7"`
	Tools             []string                     `yaml:"tools,omitempty" json:"tools,omitempty" example:"[\"local_shell\", \"nws\"]"`
	HideTools         []string                     `yaml:"hide_tools,omitempty" json:"hide_tools,omitempty" example:"[\"tool1\", \"tools_name1.tool1\"]"`
	ToolsPolicies     map[string]map[string]string `yaml:"tools_policies,omitempty" json:"tools_policies,omitempty"`
	PassClientsTools  bool                         `yaml:"pass_clients_tools" json:"pass_clients_tools"`
	Think             string                       `yaml:"think,omitempty" json:"think,omitempty" example:"high"`
	MaxTokens         *int                         `yaml:"max_tokens,omitempty" json:"max_tokens,omitempty" example:"8192"`
	MaxTokensTemplate string                       `yaml:"-" json:"-"`
	Shift             bool                         `yaml:"shift,omitempty" json:"shift,omitempty"`
	RetryPolicy       *llmretry.RetryPolicy        `yaml:"retry_policy,omitempty" json:"retry_policy,omitempty"`
}

func (LLMExecutionConfig) MarshalJSON added in v0.29.0

func (c LLMExecutionConfig) MarshalJSON() ([]byte, error)

func (*LLMExecutionConfig) UnmarshalJSON added in v0.29.0

func (c *LLMExecutionConfig) UnmarshalJSON(data []byte) error

func (*LLMExecutionConfig) UnmarshalYAML added in v0.29.0

func (c *LLMExecutionConfig) UnmarshalYAML(value *yaml.Node) error

type MacroEnv

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

func (*MacroEnv) ExecEnv

func (m *MacroEnv) ExecEnv(
	ctx context.Context,
	chain *TaskChainDefinition,
	input any,
	dataType DataType,
) (any, DataType, []CapturedStateUnit, error)

type MacroOption

type MacroOption func(*MacroEnv)

func WithPlatformShell

func WithPlatformShell(describe func() string) MacroOption

type Message

type Message struct {
	Continuation    *modelrepo.Continuation `json:"continuation,omitempty"`
	ID              string                  `json:"id" example:"msg_123456"`
	Role            string                  `json:"role" example:"user"`
	Content         string                  `json:"content,omitempty" example:"What is the capital of France?"`
	Images          []ImagePart             `json:"images,omitempty"`
	Audio           []AudioPart             `json:"audio,omitempty"`
	Thinking        string                  `json:"thinking,omitempty"`
	ToolCallID      string                  `json:"tool_call_id,omitempty"`
	ToolResultError bool                    `json:"tool_result_error,omitempty"`
	CallTools       []ToolCall              `json:"callTools,omitempty"`
	Timestamp       time.Time               `json:"timestamp" example:"2023-11-15T14:30:45Z"`
	RequestID       string                  `json:"requestId,omitempty"`
	ChainRef        string                  `json:"chainRef,omitempty"`
	Author          *MessageAuthor          `json:"author,omitempty"`
}

func SynthesizeHistory

func SynthesizeHistory(prior []Message, units []CapturedStateUnit, chainErr error) []Message

type MessageAuthor

type MessageAuthor struct {
	ID   string `json:"id"`
	Name string `json:"name,omitempty"`
}

type MockTaskExecutor

type MockTaskExecutor struct {
	MockOutput          any
	MockTransitionValue string
	MockError           error

	MockOutputSequence          []any
	MockTaskTypeSequence        []DataType
	MockTransitionValueSequence []string
	ErrorSequence               []error

	CalledWithTask   *TaskDefinition
	CalledWithInput  any
	CalledWithPrompt string
	// contains filtered or unexported fields
}

func (*MockTaskExecutor) CallCount

func (m *MockTaskExecutor) CallCount() int

func (*MockTaskExecutor) Reset

func (m *MockTaskExecutor) Reset()

func (*MockTaskExecutor) TaskExec

func (m *MockTaskExecutor) TaskExec(ctx context.Context, startingTime time.Time, tokenLimit int, chainContext *ChainContext, currentTask *TaskDefinition, input any, dataType DataType) (any, DataType, string, error)

type NoopTaskEventSink

type NoopTaskEventSink struct{}

func (NoopTaskEventSink) PublishTaskEvent

func (NoopTaskEventSink) PublishTaskEvent(context.Context, TaskEvent) error

func (NoopTaskEventSink) Wants

type OperatorTerm

type OperatorTerm string
const (
	OpEquals               OperatorTerm = "equals"
	OpContains             OperatorTerm = "contains"
	OpStartsWith           OperatorTerm = "starts_with"
	OpEndsWith             OperatorTerm = "ends_with"
	OpDefault              OperatorTerm = "default"
	OpEdgeTraversedAtLeast OperatorTerm = "edge_traversed_at_least"
)

func ToOperatorTerm

func ToOperatorTerm(s string) (OperatorTerm, error)

func (OperatorTerm) String

func (t OperatorTerm) String() string

type PendingToolCall

type PendingToolCall struct {
	CallID    string `json:"call_id"`
	Name      string `json:"name"`
	Arguments string `json:"arguments"`
}

type Prechecker

type Prechecker interface {
	Precheck(ctx context.Context, input any, args *ToolsCall) error
}

type RetryOutcomeSink

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

func (*RetryOutcomeSink) Append

func (s *RetryOutcomeSink) Append(o llmretry.Outcome)

func (*RetryOutcomeSink) LastErrorClass

func (s *RetryOutcomeSink) LastErrorClass() llmretry.ErrorClass

func (*RetryOutcomeSink) Outcomes

func (s *RetryOutcomeSink) Outcomes() []llmretry.Outcome

type SimpleEnv

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

func (SimpleEnv) ExecEnv

func (env SimpleEnv) ExecEnv(ctx context.Context, chain *TaskChainDefinition, input any, dataType DataType) (result any, resultType DataType, history []CapturedStateUnit, retErr error)

type SimpleExec

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

func (*SimpleExec) Prompt

func (exe *SimpleExec) Prompt(ctx context.Context, systemInstruction string, llmCall LLMExecutionConfig, prompt string, ctxLength int) (result string, meta llmrepo.Meta, retErr error)

func (*SimpleExec) TaskExec

func (exe *SimpleExec) TaskExec(taskCtx context.Context, startingTime time.Time, ctxLength int, chainContext *ChainContext, currentTask *TaskDefinition, input any, dataType DataType) (any, DataType, string, error)

type SimpleStackTrace

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

func (*SimpleStackTrace) GetExecutionHistory

func (s *SimpleStackTrace) GetExecutionHistory() []CapturedStateUnit

func (*SimpleStackTrace) RecordStep

func (s *SimpleStackTrace) RecordStep(step CapturedStateUnit)

type StackTrace

type StackTrace interface {
	RecordStep(step CapturedStateUnit)
	GetExecutionHistory() []CapturedStateUnit
}

type TaskChainDefinition

type TaskChainDefinition struct {
	ID string `yaml:"id" json:"id" jsonschema:"required"`

	Debug bool `yaml:"debug" json:"debug"`

	Description string `yaml:"description" json:"description"`

	Tasks []TaskDefinition `yaml:"tasks" json:"tasks" jsonschema:"required,minItems=1"`

	TokenLimit int64 `yaml:"token_limit" json:"token_limit"`
}

type TaskDefinition

type TaskDefinition struct {
	ID string `yaml:"id" json:"id" example:"validate_input" jsonschema:"required"`

	Description string `yaml:"description" json:"description" example:"Validates user input meets quality requirements"`

	Handler TaskHandler `yaml:"handler" json:"handler" example:"chat_completion" jsonschema:"required"`

	SystemInstruction string `` /* 158-byte string literal not displayed */

	ExecuteConfig *LLMExecutionConfig `yaml:"execute_config,omitempty" json:"execute_config,omitempty"`

	Tools *ToolsCall `yaml:"tools,omitempty" json:"tools,omitempty"`

	Print string `yaml:"print,omitempty" json:"print,omitempty" example:"Validation result: {{.validate_input}}"`

	PromptTemplate string `yaml:"prompt_template,omitempty" json:"prompt_template,omitempty" example:"Is this input valid? {{.input}}"`

	OutputTemplate string `yaml:"output_template,omitempty" json:"output_template,omitempty" example:"Tools result: {{.status}}"`

	InputVar string `yaml:"input_var,omitempty" json:"input_var,omitempty" example:"input"`

	InputMaxBytes int `yaml:"input_max_bytes,omitempty" json:"input_max_bytes,omitempty" example:"8192"`

	Transition TaskTransition `yaml:"transition" json:"transition"`

	Timeout string `yaml:"timeout,omitempty" json:"timeout,omitempty" example:"30s"`

	RetryOnFailure int `yaml:"retry_on_failure,omitempty" json:"retry_on_failure,omitempty" example:"2"`
}

type TaskEvent

type TaskEvent struct {
	Kind         TaskEventKind `json:"kind"`
	Timestamp    time.Time     `json:"timestamp"`
	RequestID    string        `json:"request_id,omitempty"`
	Scope        EventScope    `json:"scope,omitzero"`
	ChainID      string        `json:"chain_id,omitempty"`
	TaskID       string        `json:"task_id,omitempty"`
	TaskHandler  string        `json:"task_handler,omitempty"`
	Retry        int           `json:"retry"`
	ModelName    string        `json:"model_name,omitempty"`
	ProviderType string        `json:"provider_type,omitempty"`
	BackendID    string        `json:"backend_id,omitempty"`
	OutputType   string        `json:"output_type,omitempty"`
	Transition   string        `json:"transition,omitempty"`
	Content      string        `json:"content,omitempty"`
	Thinking     string        `json:"thinking,omitempty"`
	Error        string        `json:"error,omitempty"`

	ApprovalID   string         `json:"approval_id,omitempty"`
	HookName     string         `json:"hook_name,omitempty"`
	ToolName     string         `json:"tool_name,omitempty"`
	ApprovalArgs map[string]any `json:"approval_args,omitempty"`
	ApprovalDiff string         `json:"approval_diff,omitempty"`

	HITLAction            string `json:"hitl_action,omitempty"`
	HITLReason            string `json:"hitl_reason,omitempty"`
	HITLPolicyName        string `json:"hitl_policy_name,omitempty"`
	HITLPolicyPath        string `json:"hitl_policy_path,omitempty"`
	HITLArgsSummary       string `json:"hitl_args_summary,omitempty"`
	HITLMatchedRule       *int   `json:"hitl_matched_rule,omitempty"`
	HITLTimeoutS          int    `json:"hitl_timeout_s,omitempty"`
	HITLApprovalRequested *bool  `json:"hitl_approval_requested,omitempty"`

	ToolDiffPath    string `json:"tool_diff_path,omitempty"`
	ToolDiffOldText string `json:"tool_diff_old_text,omitempty"`
	ToolDiffNewText string `json:"tool_diff_new_text,omitempty"`

	ContextShift *ContextShift `json:"context_shift,omitempty"`
	TokenUsed    int           `json:"token_used,omitempty"`
	TokenSize    int           `json:"token_size,omitempty"`

	ChunkCount   int         `json:"chunk_count,omitempty"`
	FinishReason string      `json:"finish_reason,omitempty"`
	Usage        *TokenUsage `json:"usage,omitempty"`
}

func GetJournaledEvents added in v0.36.0

func GetJournaledEvents(ctx context.Context, kv libkv.KVManager, reqID string) ([]TaskEvent, error)

func NewTaskEvent

func NewTaskEvent(ctx context.Context, kind TaskEventKind) TaskEvent

type TaskEventKind

type TaskEventKind string
const (
	TaskEventChainStarted  TaskEventKind = "chain_started"
	TaskEventStepStarted   TaskEventKind = "step_started"
	TaskEventStepChunk     TaskEventKind = "step_chunk"
	TaskEventStepStreamEnd TaskEventKind = "step_stream_end"
	TaskEventStepCompleted TaskEventKind = "step_completed"
	TaskEventStepFailed    TaskEventKind = "step_failed"

	TaskEventChainCompleted TaskEventKind = "chain_completed"
	TaskEventChainFailed    TaskEventKind = "chain_failed"
	TaskEventChainSuspended TaskEventKind = "chain_suspended"

	TaskEventApprovalRequested TaskEventKind = "approval_requested"
	TaskEventHITLDecision      TaskEventKind = "hitl_decision"
	TaskEventToolCallPending   TaskEventKind = "tool_call_pending"
	TaskEventToolCall          TaskEventKind = "tool_call"
	TaskEventPrint             TaskEventKind = "print"
	TaskEventContextShift      TaskEventKind = "context_shift"
	TaskEventTokenUsage        TaskEventKind = "token_usage"
)

func AllTaskEventKinds

func AllTaskEventKinds() []TaskEventKind

type TaskEventScope

type TaskEventScope struct {
	ChainID     string
	TaskID      string
	TaskHandler string
	Retry       int
}

type TaskEventSink

type TaskEventSink interface {
	PublishTaskEvent(ctx context.Context, event TaskEvent) error
	Wants(kind TaskEventKind) bool
}

type TaskExecutor

type TaskExecutor interface {
	TaskExec(ctx context.Context, startingTime time.Time, ctxLength int, chainContext *ChainContext, currentTask *TaskDefinition, input any, dataType DataType) (any, DataType, string, error)
}

func NewExec

func NewExec(
	ctx context.Context,
	repo llmrepo.ModelRepo,
	toolsProvider ToolsRepo,
	tracker libtracker.ActivityTracker,
	opts ...ExecOption,
) (TaskExecutor, error)

type TaskHandler

type TaskHandler string
const (
	HandleRaiseError       TaskHandler = "raise_error"
	HandleRoute            TaskHandler = "route"
	HandleChatCompletion   TaskHandler = "chat_completion"
	HandleExecuteToolCalls TaskHandler = "execute_tool_calls"
	HandleNoop             TaskHandler = "noop"
	HandleTools            TaskHandler = "tools"
)

func (TaskHandler) String

func (t TaskHandler) String() string

type TaskTransition

type TaskTransition struct {
	OnFailure string `yaml:"on_failure" json:"on_failure" example:"error_handler"`

	Branches []TransitionBranch `yaml:"branches" json:"branches"`
}

type TokenUsage

type TokenUsage struct {
	Prompt     int `json:"prompt"`
	Completion int `json:"completion"`
	Thinking   int `json:"thinking,omitempty"`
	Total      int `json:"total"`
	CacheRead  int `json:"cacheRead,omitempty"`
	CacheWrite int `json:"cacheWrite,omitempty"`
}

type Tool

type Tool struct {
	Type     string       `json:"type"`
	Function FunctionTool `json:"function"`
}

type ToolCall

type ToolCall struct {
	ID           string            `json:"id" example:"call_abc123"`
	Type         string            `json:"type" example:"function"`
	Function     FunctionCall      `json:"function"`
	ProviderMeta map[string]string `json:"provider_meta,omitempty" example:"{\"thought_signature\":\"123456\"}"`
	ArgsMissing  bool              `json:"-"`
}

type ToolImageResult

type ToolImageResult struct {
	Text   string
	Images []ImagePart
}

type ToolImagesKept

type ToolImagesKept func(ctx context.Context) int

type ToolWithResolution

type ToolWithResolution struct {
	Tool
	ToolsName string
}

type ToolsCall

type ToolsCall struct {
	Name string `yaml:"name" json:"name" example:"slack"`

	ToolName string            `yaml:"tool_name" json:"tool_name" example:"send_slack_notification"`
	Args     map[string]string `` /* 126-byte string literal not displayed */
}

type ToolsProvider

type ToolsProvider interface {
	ToolsRegistry
	ToolsWithSchema
}

type ToolsRegistry

type ToolsRegistry interface {
	Supports(ctx context.Context) ([]string, error)
}

type ToolsRepo

type ToolsRepo interface {
	Exec(ctx context.Context, startingTime time.Time, input any, debug bool, args *ToolsCall) (any, DataType, error)
	ToolsRegistry
	ToolsWithSchema
}

type ToolsWithSchema

type ToolsWithSchema interface {
	GetSchemasForSupportedTools(ctx context.Context) (map[string]*openapi3.T, error)
	GetToolsForToolsByName(ctx context.Context, name string) ([]Tool, error)
}

type TransitionBranch

type TransitionBranch struct {
	Operator OperatorTerm `yaml:"operator,omitempty" json:"operator,omitempty" example:"equals"`

	When string `yaml:"when" json:"when" example:"tool_call"`

	Goto string `yaml:"goto" json:"goto" example:"positive_response"`

	Edge string `yaml:"edge,omitempty" json:"edge,omitempty" example:"chat->run_tools"`
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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