The Branch Agent is a core component in the Blades framework used to implement conditional branch logic. It allows for the dynamic selection of execution paths based on runtime conditions, choosing one executable task from multiple options according to the return value of a condition function. This pattern is particularly suitable for scenarios requiring different actions based on varying inputs or states.
The Branch Agent structure is as follows:
type Branch struct { condition BranchCondition runners map[string]blades.Runnable}Branch contains two parameters: the branch condition function (BranchCondition) and the executable task mapping (runners).
func(ctx context.Context, input *blades.Prompt) (string, error)map[string]blades.RunnableThe following describes how to use the Branch Agent.
condition := func(ctx context.Context, input *blades.Prompt) (string, error) { if input.Latest().Text() == "positive" { return "positive_branch", nil } return "default_branch", nil}runners := map[string]blades.Runnable{ "positive_branch": flow.NewSequential( // positive handling ), "default_branch": flow.NewSequential( // default handling ),}branch := flow.NewBranch(condition, runners)result, err := branch.Run(context.Background(), prompt)func main() { condition := func(ctx context.Context, input *blades.Prompt) (string, error) { latest := input.Latest() if latest == nil { return "default", nil }
text := latest.Text() switch { case strings.Contains(text, "help"): return "help", nil case strings.Contains(text, "order"): return "order", nil default: return "general", nil } }
runners := map[string]blades.Runnable{ "help": flow.NewSequential( // handle help ), "order": flow.NewSequential( // handle order ), "general": flow.NewSequential( // handle general ), }
branch := flow.NewBranch(condition, runners) result, err := branch.Run(ctx, prompt)}