reasoning

package
v0.0.0-...-140e820 Latest Latest
Warning

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

Go to latest
Published: Feb 4, 2026 License: Apache-2.0 Imports: 7 Imported by: 0

Documentation

Overview

Package reasoning provides reasoning techniques like Chain-of-Thought, Self-Consistency, etc.

Package reasoning provides reasoning techniques for AI agents.

Package reasoning provides reasoning techniques like Chain-of-Thought, Self-Consistency, etc.

Package reasoning provides reasoning data structures for Graph-of-Thought.

Package reasoning provides reasoning techniques and supporting data structures.

Package reasoning provides reasoning techniques like Self-Consistency, Chain-of-Thought, etc.

Package reasoning provides reasoning techniques for AI agents.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AggregatorType

type AggregatorType string

AggregatorType defines the aggregation strategy for combining reasoning paths.

const (
	// AggregatorPathBased aggregates entire reasoning paths.
	AggregatorPathBased AggregatorType = "path_based"
	// AggregatorNodeBased aggregates individual nodes.
	AggregatorNodeBased AggregatorType = "node_based"
)

type AnswerExtractor

type AnswerExtractor func(text string) string

AnswerExtractor is a function that extracts the final answer from a response.

type ChainOfThought

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

ChainOfThought implements the Chain-of-Thought reasoning technique.

It applies structured prompting to encourage step-by-step reasoning, optionally parsing and tracking individual reasoning steps.

Reference: "Chain-of-Thought Prompting Elicits Reasoning in Large Language Models" Wei et al., 2022 - https://arxiv.org/abs/2201.11903

Example:

cot := reasoning.NewChainOfThought(
    baseAgent,
    reasoning.WithPromptTemplate("Solve step by step:\n{query}"),
    reasoning.WithMaxSteps(5),
)
response, err := cot.Process(ctx, message)

func NewChainOfThought

func NewChainOfThought(agent agenkit.Agent, options ...ChainOfThoughtOption) *ChainOfThought

NewChainOfThought creates a new ChainOfThought agent.

The agent wraps a base agent and applies CoT prompting to encourage step-by-step reasoning, leading to more accurate and explainable results.

Example:

cot := reasoning.NewChainOfThought(
    baseAgent,
    reasoning.WithPromptTemplate("Think carefully:\n{query}"),
    reasoning.WithMaxSteps(5),
)

func (*ChainOfThought) Capabilities

func (cot *ChainOfThought) Capabilities() []string

Capabilities returns the agent capabilities.

func (*ChainOfThought) Name

func (cot *ChainOfThought) Name() string

Name returns the agent name.

func (*ChainOfThought) Process

func (cot *ChainOfThought) Process(ctx context.Context, message *agenkit.Message) (*agenkit.Message, error)

Process processes a message with Chain-of-Thought reasoning.

It applies the CoT prompt template to the input message, generates a response using the wrapped agent, and optionally parses reasoning steps.

The response metadata includes:

  • technique: "chain_of_thought"
  • reasoning_steps: []string (if parseSteps is true)
  • num_steps: int (if parseSteps is true)

type ChainOfThoughtOption

type ChainOfThoughtOption func(*ChainOfThought)

ChainOfThoughtOption is a functional option for configuring ChainOfThought.

func WithMaxSteps

func WithMaxSteps(max int) ChainOfThoughtOption

WithMaxSteps sets the maximum number of reasoning steps to extract.

func WithParseSteps

func WithParseSteps(parse bool) ChainOfThoughtOption

WithParseSteps sets whether to extract and track individual reasoning steps.

func WithPromptTemplate

func WithPromptTemplate(template string) ChainOfThoughtOption

WithPromptTemplate sets the prompt template with {query} placeholder.

func WithStepDelimiter

func WithStepDelimiter(delimiter string) ChainOfThoughtOption

WithStepDelimiter sets the delimiter for splitting steps.

type DecomposerFunc

type DecomposerFunc func(problem string) ([]string, error)

DecomposerFunc is a function that decomposes a problem into subproblems.

type EdgeType

type EdgeType string

EdgeType represents the type of logical connection between nodes.

const (
	// EdgeTypeSupports indicates the node supports another.
	EdgeTypeSupports EdgeType = "supports"
	// EdgeTypeDependsOn indicates the node depends on another.
	EdgeTypeDependsOn EdgeType = "depends_on"
	// EdgeTypeContradicts indicates the node contradicts another.
	EdgeTypeContradicts EdgeType = "contradicts"
	// EdgeTypeRefines indicates the node refines/improves another.
	EdgeTypeRefines EdgeType = "refines"
)

type EvaluatorFunc

type EvaluatorFunc func(text string) float64

EvaluatorFunc is a function that scores a reasoning path (0.0-1.0).

type GraphOfThought

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

GraphOfThought implements the Graph-of-Thought reasoning technique.

It builds a directed graph of reasoning steps, explores connections, and aggregates multiple reasoning paths to reach conclusions.

This technique is particularly effective for: - Multi-hop reasoning with complex dependencies - Problems requiring synthesis of multiple chains of thought - Situations where thoughts may support, contradict, or refine each other - Complex knowledge integration tasks

Reference: "Graph of Thoughts: Solving Elaborate Problems with Large Language Models" https://arxiv.org/abs/2308.09687

Example:

got := reasoning.NewGraphOfThought(
    baseAgent,
    reasoning.WithMaxNodes(20),
    reasoning.WithMaxEdges(40),
    reasoning.WithAggregator(reasoning.AggregatorPathBased),
)
response, err := got.Process(ctx, message)

func NewGraphOfThought

func NewGraphOfThought(agent agenkit.Agent, options ...GraphOfThoughtOption) *GraphOfThought

NewGraphOfThought creates a new GraphOfThought agent.

The agent builds a directed graph of reasoning, explores multiple paths, and aggregates them to reach conclusions.

Example:

got := reasoning.NewGraphOfThought(
    baseAgent,
    reasoning.WithMaxNodes(20),
    reasoning.WithAggregator(reasoning.AggregatorPathBased),
)

func (*GraphOfThought) AggregatePaths

func (got *GraphOfThought) AggregatePaths(graph *ReasoningGraph, paths [][]int) string

AggregatePaths aggregates multiple reasoning paths into a final answer.

func (*GraphOfThought) BuildGraph

func (got *GraphOfThought) BuildGraph(ctx context.Context, problem string) (*ReasoningGraph, error)

BuildGraph builds the reasoning graph for the problem.

func (*GraphOfThought) Capabilities

func (got *GraphOfThought) Capabilities() []string

Capabilities returns the agent capabilities.

func (*GraphOfThought) FindReasoningPaths

func (got *GraphOfThought) FindReasoningPaths(graph *ReasoningGraph) [][]int

FindReasoningPaths finds reasoning paths from premises to conclusions.

func (*GraphOfThought) GeneratePremises

func (got *GraphOfThought) GeneratePremises(ctx context.Context, problem string) ([]string, error)

GeneratePremises generates initial premises/facts for the problem.

func (*GraphOfThought) GenerateThoughts

func (got *GraphOfThought) GenerateThoughts(ctx context.Context, problem string, existingThoughts []string, maxNew int) ([]string, error)

GenerateThoughts generates new intermediate thoughts based on existing ones.

func (*GraphOfThought) IdentifyConnections

func (got *GraphOfThought) IdentifyConnections(ctx context.Context, thought1, thought2 string) (EdgeType, error)

IdentifyConnections identifies the logical connection between two thoughts.

func (*GraphOfThought) Name

func (got *GraphOfThought) Name() string

Name returns the agent name.

func (*GraphOfThought) Process

func (got *GraphOfThought) Process(ctx context.Context, message *agenkit.Message) (*agenkit.Message, error)

Process processes a message with Graph-of-Thought reasoning.

Builds a reasoning graph, finds paths, and aggregates them into a final answer.

The response metadata includes:

  • technique: "graph_of_thought"
  • graph: The reasoning graph (pointer)
  • reasoning_paths: List of reasoning paths
  • num_nodes: Number of nodes in graph
  • num_edges: Number of edges in graph
  • has_cycles: Whether graph contains cycles
  • aggregator: Aggregation strategy used

Example:

response, err := got.Process(ctx, message)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Nodes: %v\n", response.Metadata["num_nodes"])

type GraphOfThoughtOption

type GraphOfThoughtOption func(*GraphOfThought)

GraphOfThoughtOption is a functional option for configuring GraphOfThought.

func WithAggregator

func WithAggregator(agg AggregatorType) GraphOfThoughtOption

WithAggregator sets the aggregation strategy for combining paths.

func WithAllowCycles

func WithAllowCycles(allow bool) GraphOfThoughtOption

WithAllowCycles sets whether to allow cycles in the reasoning graph.

func WithMaxEdges

func WithMaxEdges(n int) GraphOfThoughtOption

WithMaxEdges sets the maximum number of edges in the reasoning graph.

func WithMaxNodes

func WithMaxNodes(n int) GraphOfThoughtOption

WithMaxNodes sets the maximum number of nodes in the reasoning graph.

type GraphStatistics

type GraphStatistics struct {
	NumNodes      int
	NumEdges      int
	NodeTypes     map[string]int
	EdgeTypes     map[string]int
	HasCycles     bool
	AvgConfidence float64
}

GraphStatistics contains statistics about the reasoning graph.

type LeastToMost

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

LeastToMost implements the Least-to-Most reasoning technique.

It breaks complex problems into simpler subproblems, solves them sequentially from simplest to most complex, using solutions to build up to the final answer.

This technique is particularly effective for compositional reasoning where complex problems can be decomposed into manageable pieces.

Reference: "Least-to-Most Prompting Enables Complex Reasoning in Large Language Models" Zhou et al., 2022 - https://arxiv.org/abs/2205.10625

Example:

ltm := reasoning.NewLeastToMost(
    baseAgent,
    reasoning.WithLTMMaxSubproblems(5),
    reasoning.WithComposeSolutions(true),
)
response, err := ltm.Process(ctx, message)

func NewLeastToMost

func NewLeastToMost(agent agenkit.Agent, options ...LeastToMostOption) *LeastToMost

NewLeastToMost creates a new LeastToMost agent.

The agent wraps a base agent and applies least-to-most prompting to break down complex problems into simpler subproblems, solve them sequentially, and compose the final solution.

Example:

ltm := reasoning.NewLeastToMost(
    baseAgent,
    reasoning.WithLTMMaxSubproblems(5),
    reasoning.WithComposeSolutions(true),
)

func (*LeastToMost) Capabilities

func (ltm *LeastToMost) Capabilities() []string

Capabilities returns the agent capabilities.

func (*LeastToMost) Introspect

func (ltm *LeastToMost) Introspect() *agenkit.IntrospectionResult

Introspect returns introspection information about the agent.

func (*LeastToMost) Name

func (ltm *LeastToMost) Name() string

Name returns the agent name.

func (*LeastToMost) Process

func (ltm *LeastToMost) Process(ctx context.Context, message *agenkit.Message) (*agenkit.Message, error)

Process processes a message with Least-to-Most reasoning.

It decomposes the problem, solves subproblems sequentially from easiest to hardest, and composes the final solution.

The response metadata includes:

  • technique: "least_to_most"
  • num_subproblems: int
  • subproblems: []string
  • subproblem_solutions: []string
  • compose_solutions: bool

type LeastToMostOption

type LeastToMostOption func(*LeastToMost)

LeastToMostOption is a functional option for configuring LeastToMost.

func WithComposeSolutions

func WithComposeSolutions(compose bool) LeastToMostOption

WithComposeSolutions sets whether to use previous solutions as context.

func WithLTMDecomposer

func WithLTMDecomposer(decomposer DecomposerFunc) LeastToMostOption

WithLTMDecomposer sets a custom decomposer function.

func WithLTMMaxSubproblems

func WithLTMMaxSubproblems(max int) LeastToMostOption

WithLTMMaxSubproblems sets the maximum number of subproblems.

type LogicalEdge

type LogicalEdge struct {
	// FromNode is the source node ID.
	FromNode int
	// ToNode is the target node ID.
	ToNode int
	// EdgeType is the type of logical connection.
	EdgeType EdgeType
	// Strength is the connection strength (0.0-1.0).
	Strength float64
	// Metadata contains additional edge-specific data.
	Metadata map[string]interface{}
}

LogicalEdge represents a logical connection between two thoughts.

type NodeState

type NodeState string

NodeState represents the state of a reasoning node during search.

const (
	// NodeStateOpen indicates the node is not yet explored.
	NodeStateOpen NodeState = "open"
	// NodeStateActive indicates the node is currently being explored.
	NodeStateActive NodeState = "active"
	// NodeStateEvaluated indicates the node has been evaluated and may have children.
	NodeStateEvaluated NodeState = "evaluated"
	// NodeStatePruned indicates the node has been pruned from search.
	NodeStatePruned NodeState = "pruned"
	// NodeStateTerminal indicates the node is a leaf node (complete reasoning path).
	NodeStateTerminal NodeState = "terminal"
)

type NodeType

type NodeType string

NodeType represents the type of a thought node in the reasoning graph.

const (
	// NodeTypePremise is a starting assumption or fact.
	NodeTypePremise NodeType = "premise"
	// NodeTypeIntermediate is an intermediate conclusion.
	NodeTypeIntermediate NodeType = "intermediate"
	// NodeTypeConclusion is a final conclusion.
	NodeTypeConclusion NodeType = "conclusion"
)

type Plan

type Plan struct {
	Steps           []*PlanStep
	Problem         string
	Strategy        string
	Validated       bool
	ValidationNotes string
}

Plan represents a complete solution plan

type PlanAndSolveAgent

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

PlanAndSolveAgent implements the Plan-and-Solve technique

func NewPlanAndSolveAgent

func NewPlanAndSolveAgent(agent agenkit.Agent, config PlanAndSolveConfig) *PlanAndSolveAgent

NewPlanAndSolveAgent creates a new Plan-and-Solve agent

func (*PlanAndSolveAgent) Capabilities

func (a *PlanAndSolveAgent) Capabilities() []string

Capabilities returns agent capabilities

func (*PlanAndSolveAgent) CreatePlan

func (a *PlanAndSolveAgent) CreatePlan(ctx context.Context, problem string) (*Plan, error)

CreatePlan creates a solution plan for the problem

func (*PlanAndSolveAgent) ExecutePlan

func (a *PlanAndSolveAgent) ExecutePlan(ctx context.Context, plan *Plan) ([]string, error)

ExecutePlan executes all steps in the plan sequentially

func (*PlanAndSolveAgent) ExecuteStep

func (a *PlanAndSolveAgent) ExecuteStep(ctx context.Context, step *PlanStep, previousResults []string) (string, error)

ExecuteStep executes a single plan step

func (*PlanAndSolveAgent) Name

func (a *PlanAndSolveAgent) Name() string

Name returns the agent name

func (*PlanAndSolveAgent) Process

func (a *PlanAndSolveAgent) Process(ctx context.Context, message *agenkit.Message) (*agenkit.Message, error)

Process processes a message with Plan-and-Solve prompting

func (*PlanAndSolveAgent) Validate

func (a *PlanAndSolveAgent) Validate(ctx context.Context, plan *Plan) (*Plan, error)

Validate validates that a plan is complete and feasible

type PlanAndSolveConfig

type PlanAndSolveConfig struct {
	Planner         PlannerFunc
	Solver          SolverFunc
	ValidatePlan    bool
	AllowReplanning bool
}

PlanAndSolveConfig configures the Plan-and-Solve agent

type PlanStep

type PlanStep struct {
	Description         string
	Order               int
	Dependencies        []int
	EstimatedComplexity int // 1-5 scale
	Result              string
	Executed            bool
}

PlanStep represents a single step in a plan

type PlannerFunc

type PlannerFunc func(ctx context.Context, problem string) (*Plan, error)

PlannerFunc is a custom function to create plans

type ReasoningGraph

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

ReasoningGraph is a directed graph for representing reasoning structures.

Nodes represent thoughts, conclusions, or premises. Edges represent logical connections and dependencies.

Supports: - Adding nodes and edges - Path finding between nodes - Cycle detection - Topological sorting - Graph statistics

func NewReasoningGraph

func NewReasoningGraph() *ReasoningGraph

NewReasoningGraph creates a new empty reasoning graph.

func (*ReasoningGraph) AddEdge

func (g *ReasoningGraph) AddEdge(fromNode, toNode int, edgeType EdgeType, strength float64, metadata map[string]interface{}) error

AddEdge adds a logical edge between two nodes.

func (*ReasoningGraph) AddNode

func (g *ReasoningGraph) AddNode(content string, nodeType NodeType, confidence float64, metadata map[string]interface{}) int

AddNode adds a thought node to the graph and returns its ID.

func (*ReasoningGraph) FindCycles

func (g *ReasoningGraph) FindCycles() [][]int

FindCycles finds all cycles in the graph.

func (*ReasoningGraph) FindPaths

func (g *ReasoningGraph) FindPaths(start, end int, maxLength int) [][]int

FindPaths finds all paths from start node to end node.

Returns a list of paths, where each path is a list of node IDs.

func (*ReasoningGraph) GetConclusions

func (g *ReasoningGraph) GetConclusions() []*ThoughtNode

GetConclusions returns all conclusion nodes.

func (*ReasoningGraph) GetIncomingEdges

func (g *ReasoningGraph) GetIncomingEdges(nodeID int) []*LogicalEdge

GetIncomingEdges returns all edges pointing to the node.

func (*ReasoningGraph) GetNode

func (g *ReasoningGraph) GetNode(nodeID int) *ThoughtNode

GetNode returns the node with the given ID, or nil if not found.

func (*ReasoningGraph) GetOutgoingEdges

func (g *ReasoningGraph) GetOutgoingEdges(nodeID int) []*LogicalEdge

GetOutgoingEdges returns all edges originating from the node.

func (*ReasoningGraph) GetPathScore

func (g *ReasoningGraph) GetPathScore(path []int) float64

GetPathScore calculates the score for a reasoning path.

Combines node confidence and edge strength.

func (*ReasoningGraph) GetPremises

func (g *ReasoningGraph) GetPremises() []*ThoughtNode

GetPremises returns all premise nodes.

func (*ReasoningGraph) HasCycle

func (g *ReasoningGraph) HasCycle() bool

HasCycle checks if the graph contains any cycles.

func (*ReasoningGraph) Statistics

func (g *ReasoningGraph) Statistics() GraphStatistics

Statistics returns statistics about the graph.

func (*ReasoningGraph) TopologicalSort

func (g *ReasoningGraph) TopologicalSort() []int

TopologicalSort returns nodes in topological order if the graph is acyclic.

Returns nil if the graph has cycles.

type ReasoningNode

type ReasoningNode struct {
	// ID is the unique node identifier.
	ID int
	// Content is the reasoning text for this step.
	Content string
	// ParentID is the ID of the parent node (nil for root).
	ParentID *int
	// ChildrenIDs contains the IDs of all child nodes.
	ChildrenIDs []int
	// Depth is the depth in the tree (0 for root).
	Depth int
	// Score is the evaluation score (0.0-1.0, higher is better).
	Score float64
	// State is the current state in the search process.
	State NodeState
	// Metadata contains additional node-specific data.
	Metadata map[string]interface{}
}

ReasoningNode represents a single node in a reasoning tree.

Each node contains a reasoning step and can branch into multiple child nodes.

func (*ReasoningNode) AddChild

func (n *ReasoningNode) AddChild(childID int)

AddChild adds a child node ID to this node.

func (*ReasoningNode) IsLeaf

func (n *ReasoningNode) IsLeaf() bool

IsLeaf returns true if this node has no children.

func (*ReasoningNode) IsRoot

func (n *ReasoningNode) IsRoot() bool

IsRoot returns true if this node has no parent.

type ReasoningTree

type ReasoningTree struct {

	// MaxDepth is the maximum depth reached in the tree.
	MaxDepth int
	// contains filtered or unexported fields
}

ReasoningTree represents a tree structure for branching reasoning paths.

The tree manages nodes and provides methods for building, searching, and analyzing reasoning paths.

func NewReasoningTree

func NewReasoningTree() *ReasoningTree

NewReasoningTree creates a new empty reasoning tree.

func (*ReasoningTree) AddChild

func (t *ReasoningTree) AddChild(parentID int, content string, score float64, metadata map[string]interface{}) (int, error)

AddChild adds a child node to a parent and returns the child ID.

func (*ReasoningTree) CreateRoot

func (t *ReasoningTree) CreateRoot(content string, metadata map[string]interface{}) int

CreateRoot creates a root node and returns its ID.

func (*ReasoningTree) GetBestLeaf

func (t *ReasoningTree) GetBestLeaf() *ReasoningNode

GetBestLeaf returns the leaf node with the highest score.

func (*ReasoningTree) GetChildren

func (t *ReasoningTree) GetChildren(nodeID int) []*ReasoningNode

GetChildren returns all children of a node.

func (*ReasoningTree) GetLeaves

func (t *ReasoningTree) GetLeaves() []*ReasoningNode

GetLeaves returns all leaf nodes (nodes with no children).

func (*ReasoningTree) GetNode

func (t *ReasoningTree) GetNode(nodeID int) *ReasoningNode

GetNode returns the node with the given ID, or nil if not found.

func (*ReasoningTree) GetPath

func (t *ReasoningTree) GetPath(nodeID int) []*ReasoningNode

GetPath returns the path from root to the given node.

func (*ReasoningTree) GetPathText

func (t *ReasoningTree) GetPathText(nodeID int, delimiter string) string

GetPathText returns the concatenated text of the path from root to node.

func (*ReasoningTree) GetRootID

func (t *ReasoningTree) GetRootID() *int

GetRootID returns the root node ID, or nil if the tree is empty.

func (*ReasoningTree) GetStatistics

func (t *ReasoningTree) GetStatistics() TreeStatistics

GetStatistics returns statistics about the tree.

func (*ReasoningTree) PruneNode

func (t *ReasoningTree) PruneNode(nodeID int)

PruneNode marks a node as pruned.

func (*ReasoningTree) Size

func (t *ReasoningTree) Size() int

Size returns the total number of nodes in the tree.

type SearchStrategy

type SearchStrategy string

SearchStrategy defines the tree search strategy.

const (
	// SearchStrategyBFS performs breadth-first search.
	SearchStrategyBFS SearchStrategy = "bfs"
	// SearchStrategyDFS performs depth-first search.
	SearchStrategyDFS SearchStrategy = "dfs"
	// SearchStrategyBestFirst always expands the highest-scoring node.
	SearchStrategyBestFirst SearchStrategy = "best-first"
)

type SelfConsistency

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

SelfConsistency implements the Self-Consistency reasoning technique. It generates multiple independent reasoning paths and selects the most consistent answer through voting or aggregation strategies.

Reference: "Self-Consistency Improves Chain of Thought Reasoning in Language Models" Wang et al., 2022 - https://arxiv.org/abs/2203.11171

func NewSelfConsistency

func NewSelfConsistency(agent agenkit.Agent, options ...SelfConsistencyOption) *SelfConsistency

NewSelfConsistency creates a new SelfConsistency agent.

The agent wraps a base agent and samples it multiple times to generate diverse reasoning paths. It then uses voting to determine the most consistent answer, improving reliability.

Example:

sc := reasoning.NewSelfConsistency(
    baseAgent,
    reasoning.WithNumSamples(5),
    reasoning.WithVotingStrategy(reasoning.VotingStrategyMajority),
)

func (*SelfConsistency) Capabilities

func (sc *SelfConsistency) Capabilities() []string

Capabilities returns the agent capabilities.

func (*SelfConsistency) Name

func (sc *SelfConsistency) Name() string

Name returns the agent name.

func (*SelfConsistency) Process

func (sc *SelfConsistency) Process(ctx context.Context, message *agenkit.Message) (*agenkit.Message, error)

Process processes the message with Self-Consistency.

It generates multiple independent samples, extracts answers, and uses voting to determine the most consistent answer.

type SelfConsistencyOption

type SelfConsistencyOption func(*SelfConsistency)

SelfConsistencyOption is a functional option for configuring SelfConsistency.

func WithAnswerExtractor

func WithAnswerExtractor(extractor AnswerExtractor) SelfConsistencyOption

WithAnswerExtractor sets a custom answer extraction function.

func WithNumSamples

func WithNumSamples(n int) SelfConsistencyOption

WithNumSamples sets the number of independent samples to generate.

func WithTemperature

func WithTemperature(temp float64) SelfConsistencyOption

WithTemperature sets the sampling temperature for diversity.

func WithVotingStrategy

func WithVotingStrategy(strategy VotingStrategy) SelfConsistencyOption

WithVotingStrategy sets the voting strategy for answer aggregation.

type SolverFunc

type SolverFunc func(ctx context.Context, step *PlanStep, previousResults []string) (string, error)

SolverFunc is a custom function to execute plan steps

type Subproblem

type Subproblem struct {
	Content      string
	Difficulty   int
	Dependencies []int
}

Subproblem represents a subproblem in the decomposition.

type ThoughtNode

type ThoughtNode struct {
	// ID is the unique node identifier.
	ID int
	// Content is the thought/conclusion text.
	Content string
	// NodeType is the type of node.
	NodeType NodeType
	// Confidence is the confidence score (0.0-1.0).
	Confidence float64
	// Metadata contains additional node-specific data.
	Metadata map[string]interface{}
}

ThoughtNode represents a single thought or conclusion in the reasoning graph.

type TreeOfThought

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

TreeOfThought implements the Tree-of-Thought reasoning technique.

It explores multiple reasoning paths in a tree structure, evaluates each path, and selects the best solution using configurable search strategies.

Reference: "Tree of Thoughts: Deliberate Problem Solving with Large Language Models" Yao et al., 2023 - https://arxiv.org/abs/2305.10601

Example:

tot := reasoning.NewTreeOfThought(
    baseAgent,
    reasoning.WithBranchingFactor(3),
    reasoning.WithMaxDepth(4),
    reasoning.WithStrategy(reasoning.SearchStrategyBestFirst),
)
response, err := tot.Process(ctx, message)

func NewTreeOfThought

func NewTreeOfThought(agent agenkit.Agent, options ...TreeOfThoughtOption) *TreeOfThought

NewTreeOfThought creates a new TreeOfThought agent.

The agent explores multiple reasoning paths using tree search with branching, evaluation, and backtracking.

Example:

tot := reasoning.NewTreeOfThought(
    baseAgent,
    reasoning.WithBranchingFactor(3),
    reasoning.WithMaxDepth(4),
    reasoning.WithStrategy(reasoning.SearchStrategyBestFirst),
)

func (*TreeOfThought) Capabilities

func (tot *TreeOfThought) Capabilities() []string

Capabilities returns the agent capabilities.

func (*TreeOfThought) Name

func (tot *TreeOfThought) Name() string

Name returns the agent name.

func (*TreeOfThought) Process

func (tot *TreeOfThought) Process(ctx context.Context, message *agenkit.Message) (*agenkit.Message, error)

Process processes a message with Tree-of-Thought reasoning.

It builds a reasoning tree, explores multiple paths using the configured search strategy, and returns the best complete reasoning path.

The response metadata includes:

  • technique: "tree_of_thought"
  • search_strategy: string
  • reasoning_tree_stats: TreeStatistics
  • reasoning_path: []string
  • num_steps: int
  • best_score: float64

type TreeOfThoughtOption

type TreeOfThoughtOption func(*TreeOfThought)

TreeOfThoughtOption is a functional option for configuring TreeOfThought.

func WithBranchingFactor

func WithBranchingFactor(n int) TreeOfThoughtOption

WithBranchingFactor sets the number of alternative reasoning paths to explore at each step.

func WithEvaluator

func WithEvaluator(eval EvaluatorFunc) TreeOfThoughtOption

WithEvaluator sets a custom evaluator function for scoring reasoning paths.

func WithMaxDepth

func WithMaxDepth(depth int) TreeOfThoughtOption

WithMaxDepth sets the maximum depth of the reasoning tree.

func WithPruneThreshold

func WithPruneThreshold(threshold float64) TreeOfThoughtOption

WithPruneThreshold sets the threshold for pruning low-scoring paths (0.0-1.0).

func WithStrategy

func WithStrategy(strategy SearchStrategy) TreeOfThoughtOption

WithStrategy sets the search strategy (bfs, dfs, best-first).

type TreeStatistics

type TreeStatistics struct {
	TotalNodes   int
	MaxDepth     int
	NumLeaves    int
	NumEvaluated int
	NumPruned    int
	AvgScore     float64
	BestScore    float64
}

TreeStatistics contains statistics about the reasoning tree.

type VotingStrategy

type VotingStrategy string

VotingStrategy defines how to aggregate multiple answers.

const (
	// VotingStrategyMajority selects the most common answer.
	VotingStrategyMajority VotingStrategy = "majority"
	// VotingStrategyWeighted weights answers by response length (proxy for detail/confidence).
	VotingStrategyWeighted VotingStrategy = "weighted"
	// VotingStrategyFirst uses the first answer (no voting, for debugging).
	VotingStrategyFirst VotingStrategy = "first"
)

Jump to

Keyboard shortcuts

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