handlers

package
v0.0.5 Latest Latest
Warning

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

Go to latest
Published: Jan 18, 2025 License: Apache-2.0 Imports: 5 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DefaultAggregator added in v0.0.5

func DefaultAggregator(results []HandlerResult) (minds.ThreadContext, error)

DefaultAggregator combines results by merging contexts in order. Merging is done by starting with the first successful context and merging all subsequent successful contexts into it. If no successful contexts are found, an error is returned.

Metadata merging is done with the minds.KeepNew strategy, which overwrites existing values with new values. Messages are appended in order.

Parameters:

  • results: List of handler results to aggregate.

Returns:

  • A single thread context that combines all successful results.

func First added in v0.0.3

func First(name string, handlers ...minds.ThreadHandler) *firstHandler

First creates a handler that runs multiple handlers in parallel and returns on first success.

Handlers are executed concurrently and the first successful result is returned. If all handlers fail, an error containing all handler errors is returned. Processing is canceled for remaining handlers once a successful result is obtained. If no handlers are provided, the thread context is passed to the next handler.

Parameters:

  • name: Identifier for this parallel handler group.
  • handlers: Variadic list of handlers to execute in parallel.

Returns:

  • A handler that implements parallel execution with first-success semantics.

Example:

first := handlers.First("validation",
    validateA,
    validateB,
    validateC,
)

func For added in v0.0.3

func For(name string, iterations int, handler minds.ThreadHandler, fn ForConditionFn) *looper

For creates a handler that repeats processing based on iterations and conditions.

A continuation function can optionally control the loop based on the ThreadContext and iteration count. The handler runs either until the iteration count is reached, the continuation function returns false, or infinitely if iterations is 0.

Parameters:

  • name: Identifier for this loop handler.
  • iterations: Number of iterations (0 for infinite).
  • handler: The handler to repeat.
  • fn: Optional function controlling loop continuation.

Returns:

  • A handler that implements controlled repetition of processing.

Example:

loop := handlers.For("validation", 3, validateHandler, func(tc ThreadContext, i int) bool {
    return tc.ShouldContinue()
})

func Must

func Must(name string, agg ResultAggregator, handlers ...minds.ThreadHandler) *mustHandler

Must returns a handler that runs multiple handlers in parallel with all-success semantics.

All handlers execute concurrently and must complete successfully. If any handler fails, remaining handlers are canceled and the first error encountered is returned. The timing of which error is returned is nondeterministic due to parallel execution.

Parameters:

  • name: Identifier for this parallel handler group.
  • handlers: Variadic list of handlers that must all succeed.

Returns:

  • A handler that implements parallel execution with all-success semantics.

Example:

must := handlers.Must("validation",
    validateA,
    validateB,
    validateC,
)

func Policy added in v0.0.3

func Policy(llm minds.ContentGenerator, name, systemPrompt string, resultFn PolicyResultFunc) *policyValidator

Policy creates a new policy validator handler.

The handler uses an LLM to validate thread content against a given policy. A system prompt is used to guide the validation process, and the result is processed by the optional result function. If the result function is nil, the handler defaults to checking the `Valid` field of the validation result.

Parameters:

  • llm: A content generator for generating validation responses.
  • name: The name of the policy validator.
  • systemPrompt: A prompt describing the policy validation rules.
  • resultFn: (Optional) Function to process validation results.

Returns:

  • A thread handler that validates thread content against a policy.

func Range added in v0.0.2

func Range(name string, handler minds.ThreadHandler, values ...interface{}) *ranger

Range creates a handler that processes a thread with a series of values.

For each value in the provided list, the handler executes with the value stored in the thread context's metadata under the key "range_value". An optional middleware handler can be used to wrap each iteration.

Parameters:

  • name: Identifier for this range handler.
  • handler: The handler to execute for each value.
  • values: Variadic list of values to iterate over.

Returns:

  • A handler that processes the thread once for each value.

Example:

range := handlers.Range("process",
    processHandler,
    "value1", "value2", "value3",
)

func Sequential

func Sequential(name string, handlers ...minds.ThreadHandler) *sequential

Sequential creates a ThreadHandler that executes a series of handlers in sequence. If any handler returns an error, the sequence stops, and the error is returned. You can add handlers to the sequence after construction using AddHandler or AddHandlers. Optionally, you can specify a handler as middleware with the `Use` method.

Example:

this := DoThisHandler()
that := DoThatHandler()
llm := LLMHandler()

// Sequentially run `this` -> `llm` -> `that` handlers
seq := Sequential("example", this, llm, that)
finalThread, err := seq.HandleThread(initialThread, nil)
if err != nil {
    log.Fatalf("Error handling thread: %v", err)
}
fmt.Println("Final thread:", finalThread.Messaages.Last().Content)

func Summarize added in v0.0.4

func Summarize(provider minds.ContentGenerator, systemMsg string) *summarize

Summarize creates a handler that maintains a running summary of thread messages.

The handler prompts an LLM to generate a concise summary of all messages in the thread, focusing on key information. The summary is appended to the system message in XML tags and persists across handler invocations.

Parameters:

  • provider: LLM content generator for creating summaries.
  • systemMsg: Initial system message to prepend to summaries.

Returns:

  • A handler that maintains thread summaries via LLM generation.

Note: The original thread context is not modified; a new context with the updated system message is created.

func Switch added in v0.0.4

func Switch(name string, defaultHandler minds.ThreadHandler, cases ...SwitchCase) *switcher

)

func WithDescription

func WithDescription(description string) func(*HandlerOption)

func WithName

func WithName(name string) func(*HandlerOption)

func WithPrompt

func WithPrompt(prompt minds.Prompt) func(*HandlerOption)

Types

type ForConditionFn added in v0.0.3

type ForConditionFn func(tc minds.ThreadContext, iteration int) bool

type HandlerOption

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

type HandlerResult added in v0.0.5

type HandlerResult struct {
	Handler minds.ThreadHandler
	Context minds.ThreadContext
	Error   error
}

type LLMCondition added in v0.0.4

type LLMCondition struct {
	Generator minds.ContentGenerator // The LLM content generator to use
	Prompt    string                 // The prompt to send to the LLM
}

LLMCondition implements SwitchCondition using an LLM to evaluate a condition based on a provided prompt. It uses the content generator to process the prompt and expects a boolean response.

func (LLMCondition) Evaluate added in v0.0.4

func (l LLMCondition) Evaluate(tc minds.ThreadContext) (bool, error)

Evaluate sends the prompt to the LLM along with context from the thread's last message and interprets the response as a boolean value. The LLM's response must conform to the boolean_response schema.

It returns an error if the LLM generation fails or if the response cannot be parsed as a boolean value.

type MetadataEquals added in v0.0.4

type MetadataEquals struct {
	Key   string      // The metadata key to check
	Value interface{} // The value to compare against
}

MetadataEquals implements SwitchCondition to check if a metadata key equals a specific value. The comparison uses Go's standard equality operator (==).

func (MetadataEquals) Evaluate added in v0.0.4

func (m MetadataEquals) Evaluate(tc minds.ThreadContext) (bool, error)

Evaluate checks if the metadata value for the specified key equals the target value. Returns false if the key doesn't exist in the metadata.

type Middleware added in v0.0.5

type Middleware interface {
	Wrap(minds.ThreadHandler) minds.ThreadHandler
}

Middleware interface defines how middleware can wrap handlers

type MiddlewareFunc added in v0.0.5

type MiddlewareFunc func(minds.ThreadHandler) minds.ThreadHandler

func (MiddlewareFunc) Wrap added in v0.0.5

type PolicyResult added in v0.0.3

type PolicyResult struct {
	Valid     bool   `json:"valid" description:"Whether the content passes policy validation"`
	Reason    string `json:"reason" description:"Explanation for the validation result"`
	Violation string `json:"violation" description:"Description of the specific violation if any"`
}

PolicyResult represents the outcome of a policy validation.

type PolicyResultFunc

type PolicyResultFunc func(ctx context.Context, tc minds.ThreadContext, res PolicyResult) error

PolicyResultFunc defines a function to handle the result of a policy validation. It takes a context, thread context, and validation result, and returns an error if the validation fails or cannot be processed.

type ResultAggregator added in v0.0.5

type ResultAggregator func([]HandlerResult) (minds.ThreadContext, error)

type SwitchCase added in v0.0.4

type SwitchCase struct {
	Condition SwitchCondition
	Handler   minds.ThreadHandler
}

SwitchCase pairs a condition with a handler. When the condition evaluates to true, the corresponding handler is executed.

type SwitchCondition added in v0.0.4

type SwitchCondition interface {
	// Evaluate examines the thread context and returns true if the condition is met.
	// It returns an error if the evaluation fails.
	Evaluate(tc minds.ThreadContext) (bool, error)
}

SwitchCondition represents a condition that can be evaluated against a thread context. Implementations of this interface are used by the Switch handler to determine which case should be executed.

type ThreadFlow added in v0.0.5

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

result, err := flow.HandleThread(initialContext, nil)

if err != nil {
    log.Fatalf("Error in flow: %v", err)
}

fmt.Println("Result:", result.Messages().Last().Content)

func NewThreadFlow added in v0.0.5

func NewThreadFlow(name string) *ThreadFlow

NewThreadFlow creates a new ThreadFlow with the given handler

func (*ThreadFlow) Group added in v0.0.5

func (f *ThreadFlow) Group(fn func(*ThreadFlow))

Group creates a new middleware scope. Middleware added within the group function will only apply to that group and won't affect parent scopes.

func (*ThreadFlow) Handle added in v0.0.5

func (f *ThreadFlow) Handle(handler minds.ThreadHandler)

func (*ThreadFlow) HandleThread added in v0.0.5

func (*ThreadFlow) String added in v0.0.5

func (f *ThreadFlow) String() string

String returns a string representation of the ThreadFlow

func (*ThreadFlow) Use added in v0.0.5

func (f *ThreadFlow) Use(middleware ...Middleware)

Use adds middleware to the ThreadFlow. Middleware is executed in the order it's added, with each new middleware wrapping the previous ones.

Jump to

Keyboard shortcuts

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