Help us shape the future of Go! Take the 2026 Go Developer Survey

reasoning

package
v1.11.3 Latest Latest
Warning

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

Go to latest
Published: Apr 18, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type DynamicPlanner

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

Dynamic Planner执行动态规划并进行回溯跟踪.

func NewDynamicPlanner

func NewDynamicPlanner(gateway llmcore.Gateway, executor tools.ToolExecutor, schemas []types.ToolSchema, config DynamicPlannerConfig, logger *zap.Logger) *DynamicPlanner

NewDynamic Planner创建了新的动态计划.

func (*DynamicPlanner) Execute

func (d *DynamicPlanner) Execute(ctx context.Context, task string) (*ReasoningResult, error)

执行运行动态规划并进行回溯跟踪.

func (*DynamicPlanner) Name

func (d *DynamicPlanner) Name() string

type DynamicPlannerConfig

type DynamicPlannerConfig struct {
	MaxBacktracks       int           // Maximum backtrack attempts
	MaxPlanDepth        int           // Maximum plan depth
	ConfidenceThreshold float64       // Minimum confidence to proceed
	Timeout             time.Duration // Overall timeout
	EnableParallel      bool          // Enable parallel path exploration
	MaxParallelPaths    int           // Maximum parallel paths to explore
	Model               string        // LLM model to use for reasoning steps
}

DynamicPlannerConfig配置了动态规划器.

func DefaultDynamicPlannerConfig

func DefaultDynamicPlannerConfig() DynamicPlannerConfig

默认 DynamicPlannerConfig 返回合理的默认值 。

type ExecutionPlan

type ExecutionPlan struct {
	Goal           string          `json:"goal"`
	Steps          []ExecutionStep `json:"steps"`
	CurrentStep    int             `json:"current_step"`
	CompletedSteps []string        `json:"completed_steps"`
	Status         string          `json:"status"` // planning, executing, replanning, completed, failed
}

执行计划代表目前的计划状态.

type ExecutionStep

type ExecutionStep struct {
	ID          string `json:"id"`
	Description string `json:"description"`
	Tool        string `json:"tool,omitempty"`
	Arguments   string `json:"arguments,omitempty"`
	Status      string `json:"status"` // pending, running, completed, failed, skipped
	Result      string `json:"result,omitempty"`
	Error       string `json:"error,omitempty"`
}

"执行步骤"代表了计划的一个步骤.

type IterativeDeepening

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

迭代深化实施迭代深化研究推理模式. 它通过生成搜索查询,分析结果,来循环地探索一个话题, 确定新的研究方向,深化探索直至充分 实现理解或达到深度限制。

这种模式对以下方面特别有效: - 需要多方面探索的不限成员名额的研究问题 - 初步询问显示意外分专题的专题 - 综合文献/信息调查 - 通过逐步完善,加深理解

func NewIterativeDeepening

func NewIterativeDeepening(gateway llmcore.Gateway, executor tools.ToolExecutor, config IterativeDeepeningConfig, logger *zap.Logger) *IterativeDeepening

NewIterative Deepenning 创造了一个新的"活泼"Deepenning Research causeer. 互联网档案馆的存檔,存档日期2013-12-21.

func (*IterativeDeepening) Execute

func (id *IterativeDeepening) Execute(ctx context.Context, task string) (*ReasoningResult, error)

Execute运行"惯性深化研究"推理模式.

func (*IterativeDeepening) Name

func (id *IterativeDeepening) Name() string

名称返回模式标识符 。

type IterativeDeepeningConfig

type IterativeDeepeningConfig struct {
	Breadth         int           // Number of parallel search queries per level
	MaxDepth        int           // Maximum recursion depth for exploration
	ResultsPerQuery int           // Maximum results to analyze per query
	MinConfidence   float64       // Minimum confidence to continue deepening (0-1)
	Timeout         time.Duration // Overall timeout for the entire research process
	ParallelSearch  bool          // Whether to execute searches in parallel
	SynthesisModel  string        // Model to use for final synthesis (empty = default)
}

迭代深化Config配置了迭代深化研究推理模式. 在深层研究的循环探索方法的启发下,这种模式 进行宽度第一查询生成,然后进行深度第一回溯探索。

func DefaultIterativeDeepeningConfig

func DefaultIterativeDeepeningConfig() IterativeDeepeningConfig

默认的深度 Config 返回用于迭代深化研究的合理默认值 。

type MemoryEntry

type MemoryEntry struct {
	Task       string      `json:"task"`
	Reflection *Reflection `json:"reflection"`
}

内存 Entry 代表存储的经验 。

type NodeStatus

type NodeStatus string

节点状态代表计划节点状态.

const (
	NodeStatusPending   NodeStatus = "pending"
	NodeStatusRunning   NodeStatus = "running"
	NodeStatusCompleted NodeStatus = "completed"
	NodeStatusFailed    NodeStatus = "failed"
	NodeStatusSkipped   NodeStatus = "skipped"
	NodeStatusBacktrack NodeStatus = "backtrack"
)

type PatternRegistry

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

PatternRegistry 推理模式注册表 - 管理和发现可用的推理模式

func NewPatternRegistry

func NewPatternRegistry() *PatternRegistry

NewPatternRegistry 创建推理模式注册表

func (*PatternRegistry) Get

func (r *PatternRegistry) Get(name string) (ReasoningPattern, bool)

Get 获取推理模式

func (*PatternRegistry) List

func (r *PatternRegistry) List() []string

List 列出所有已注册的推理模式名称

func (*PatternRegistry) Register

func (r *PatternRegistry) Register(pattern ReasoningPattern) error

Register 注册推理模式

func (*PatternRegistry) Unregister

func (r *PatternRegistry) Unregister(name string) bool

Unregister 注销推理模式

type PlanAndExecute

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

PlanAndExecute执行"计划与执行"推理模式. 与ReWOO不同,它可以根据中间结果来调整计划.

func NewPlanAndExecute

func NewPlanAndExecute(gateway llmcore.Gateway, executor tools.ToolExecutor, schemas []types.ToolSchema, config PlanExecuteConfig, logger *zap.Logger) *PlanAndExecute

NewPlanAndExecute创建了一个新的"计划"和"执行"推理器.

func (*PlanAndExecute) Execute

func (p *PlanAndExecute) Execute(ctx context.Context, task string) (*ReasoningResult, error)

Execute运行"计划与执行"推理模式.

func (*PlanAndExecute) Name

func (p *PlanAndExecute) Name() string

type PlanExecuteConfig

type PlanExecuteConfig struct {
	MaxPlanSteps      int           // Maximum steps in initial plan
	MaxReplanAttempts int           // Maximum replanning attempts on failure
	Timeout           time.Duration // Overall timeout
	AdaptivePlanning  bool          // Allow plan modification during execution
	Model             string        // LLM model to use for reasoning steps
}

PlanExecuteConfig 配置了 Plan- and-Execute 推理模式.

func DefaultPlanExecuteConfig

func DefaultPlanExecuteConfig() PlanExecuteConfig

默认 PlanExecuteConfig 返回合理的默认值 。

type PlanNode

type PlanNode struct {
	ID           string      `json:"id"`
	ParentID     string      `json:"parent_id,omitempty"`
	Action       string      `json:"action"`
	Description  string      `json:"description"`
	Status       NodeStatus  `json:"status"`
	Result       string      `json:"result,omitempty"`
	Error        string      `json:"error,omitempty"`
	Confidence   float64     `json:"confidence"`
	Children     []*PlanNode `json:"children,omitempty"`
	Alternatives []*PlanNode `json:"alternatives,omitempty"` // Alternative paths if this fails
	CreatedAt    time.Time   `json:"created_at"`
	CompletedAt  *time.Time  `json:"completed_at,omitempty"`
}

PlanNode代表了执行计划中树上的一个节点.

type PlanStep

type PlanStep struct {
	ID           string   `json:"id"`           // e.g., #E1, #E2
	Tool         string   `json:"tool"`         // Tool name to call
	Arguments    string   `json:"arguments"`    // Arguments (may reference previous steps like #E1)
	Dependencies []string `json:"dependencies"` // IDs of steps this depends on
	Reasoning    string   `json:"reasoning"`    // Why this step is needed
}

PlanStep代表了ReWOO计划中的一步.

type ReWOO

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

ReWOO执行无观测理性模式. 它产生一个完整的计划前, 然后执行所有步骤, 最后从所有观测中合成答案。

func NewReWOO

func NewReWOO(gateway llmcore.Gateway, executor tools.ToolExecutor, schemas []types.ToolSchema, config ReWOOConfig, logger *zap.Logger) *ReWOO

NewReWOO创建了新的ReWOO理性.

func (*ReWOO) Execute

func (r *ReWOO) Execute(ctx context.Context, task string) (*ReasoningResult, error)

执行运行了ReWOO推理模式.

func (*ReWOO) Name

func (r *ReWOO) Name() string

type ReWOOConfig

type ReWOOConfig struct {
	MaxPlanSteps    int           // Maximum steps in the plan
	Timeout         time.Duration // Overall timeout
	ParallelWorkers int           // Number of parallel workers for independent steps
	Model           string        // LLM model to use for reasoning steps
}

ReWOOConfig配置了ReWOO推理模式.

func DefaultReWOOConfig

func DefaultReWOOConfig() ReWOOConfig

默认 ReWOOConfig 返回合理的默认值 。

type ReasoningPattern

type ReasoningPattern interface {
	// 执行运行推理模式并返回最终结果.
	Execute(ctx context.Context, task string) (*ReasoningResult, error)
	// 名称返回图案名称 。
	Name() string
}

理由 图案定义了不同推理策略的界面.

type ReasoningResult

type ReasoningResult struct {
	Pattern      string          `json:"pattern"`
	Task         string          `json:"task"`
	FinalAnswer  string          `json:"final_answer"`
	Confidence   float64         `json:"confidence,omitempty"`
	Steps        []ReasoningStep `json:"steps"`
	TotalTokens  int             `json:"total_tokens"`
	TotalLatency time.Duration   `json:"total_latency"`
	Metadata     map[string]any  `json:"metadata,omitempty"`
}

理由 结果包含一个推理模式的输出.

type ReasoningStep

type ReasoningStep struct {
	StepID     string          `json:"step_id"`
	Type       string          `json:"type"` // thought, action, observation, evaluation, backtrack
	Content    string          `json:"content"`
	Score      float64         `json:"score,omitempty"`
	Children   []ReasoningStep `json:"children,omitempty"`
	Duration   time.Duration   `json:"duration"`
	TokensUsed int             `json:"tokens_used,omitempty"`
}

ReasoningStep代表了推理过程中的一阶.

type Reflection

type Reflection struct {
	Analysis     string   `json:"analysis"`
	Mistakes     []string `json:"mistakes"`
	NextStrategy string   `json:"next_strategy"`
}

反思是对审判的反馈。

type ReflexionConfig

type ReflexionConfig struct {
	MaxTrials        int           `json:"max_trials"`
	SuccessThreshold float64       `json:"success_threshold"`
	Timeout          time.Duration `json:"timeout"`
	EnableMemory     bool          `json:"enable_memory"`
	Model            string        `json:"model,omitempty"`
}

ReflexionConfig 配置了 Reflexion 执行器.

func DefaultReflexionConfig

func DefaultReflexionConfig() ReflexionConfig

默认 Reflexion Config 返回合理的默认值 。

type ReflexionExecutor

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

ReflexionExecutor执行Reflexion模式.

func NewReflexionExecutor

func NewReflexionExecutor(gateway llmcore.Gateway, executor tools.ToolExecutor, schemas []types.ToolSchema, config ReflexionConfig, logger *zap.Logger) *ReflexionExecutor

新ReflexionExecutor创建了新的Reflexion执行器.

func (*ReflexionExecutor) Execute

func (r *ReflexionExecutor) Execute(ctx context.Context, task string) (*ReasoningResult, error)

执行运行折射回路.

func (*ReflexionExecutor) Name

func (r *ReflexionExecutor) Name() string

type ReflexionMemory

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

折射记忆存储过去的经验。

type TrajectoryCollector added in v1.6.0

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

TrajectoryCollector builds trajectory records incrementally during execution. Safe for concurrent use.

func NewTrajectoryCollector added in v1.6.0

func NewTrajectoryCollector(id, agentID, pattern, task string) *TrajectoryCollector

NewTrajectoryCollector creates a new collector for the given agent and task.

func (*TrajectoryCollector) AddStep added in v1.6.0

func (c *TrajectoryCollector) AddStep(stepType, content string, opts ...TrajectoryStepOption)

AddStep records a step in the trajectory.

func (*TrajectoryCollector) Finalize added in v1.6.0

func (c *TrajectoryCollector) Finalize(answer string, totalTokens int, duration time.Duration) *TrajectoryRecord

Finalize completes the trajectory record with the final answer and total stats.

func (*TrajectoryCollector) Record added in v1.6.0

Record returns a snapshot of the current trajectory record (may be incomplete). The returned copy is safe to read without holding any lock.

type TrajectoryEvaluator added in v1.6.0

type TrajectoryEvaluator interface {
	Evaluate(ctx context.Context, record *TrajectoryRecord) (float64, error)
}

TrajectoryEvaluator scores the quality of an execution trajectory.

type TrajectoryRecord added in v1.6.0

type TrajectoryRecord struct {
	ID          string           `json:"id"`
	AgentID     string           `json:"agent_id"`
	Pattern     string           `json:"pattern"`
	Task        string           `json:"task"`
	Steps       []TrajectoryStep `json:"steps"`
	FinalAnswer string           `json:"final_answer"`
	Quality     float64          `json:"quality,omitempty"`
	TotalTokens int              `json:"total_tokens"`
	Duration    time.Duration    `json:"duration"`
	CreatedAt   time.Time        `json:"created_at"`
	Metadata    map[string]any   `json:"metadata,omitempty"`
}

TrajectoryRecord captures a complete execution trajectory for evaluation and replay.

func FromReasoningResult added in v1.6.0

func FromReasoningResult(id, agentID string, result *ReasoningResult) *TrajectoryRecord

FromReasoningResult converts a ReasoningResult into a TrajectoryRecord. Returns nil if result is nil.

func TrajectoryRecordFromJSON added in v1.6.0

func TrajectoryRecordFromJSON(data []byte) (*TrajectoryRecord, error)

TrajectoryRecordFromJSON deserializes a trajectory record from JSON.

func (*TrajectoryRecord) ToJSON added in v1.6.0

func (r *TrajectoryRecord) ToJSON() ([]byte, error)

ToJSON serializes a trajectory record to JSON.

type TrajectoryStep added in v1.6.0

type TrajectoryStep struct {
	Index      int            `json:"index"`
	Type       string         `json:"type"` // thought, action, observation, reflection, tool_call
	Content    string         `json:"content"`
	ToolName   string         `json:"tool_name,omitempty"`
	ToolArgs   map[string]any `json:"tool_args,omitempty"`
	ToolResult string         `json:"tool_result,omitempty"`
	TokensUsed int            `json:"tokens_used,omitempty"`
	Duration   time.Duration  `json:"duration"`
	Timestamp  time.Time      `json:"timestamp"`
}

TrajectoryStep records a single Thought → Action → Observation cycle.

type TrajectoryStepOption added in v1.6.0

type TrajectoryStepOption func(*TrajectoryStep)

TrajectoryStepOption configures optional fields on a TrajectoryStep.

func WithStepDuration added in v1.6.0

func WithStepDuration(d time.Duration) TrajectoryStepOption

func WithStepTokens added in v1.6.0

func WithStepTokens(tokens int) TrajectoryStepOption

func WithToolCall added in v1.6.0

func WithToolCall(name string, args map[string]any, result string) TrajectoryStepOption

type TrajectoryStore added in v1.6.0

type TrajectoryStore interface {
	Save(ctx context.Context, record *TrajectoryRecord) error
	Load(ctx context.Context, id string) (*TrajectoryRecord, error)
	ListByAgent(ctx context.Context, agentID string, limit int) ([]*TrajectoryRecord, error)
}

TrajectoryStore persists and retrieves trajectory records.

type TreeOfThought

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

Tree Of Thought 执行思想之树推理模式. 它平行地探索多条推理路径,并选择了最好的一条.

func NewTreeOfThought

func NewTreeOfThought(gateway llmcore.Gateway, executor tools.ToolExecutor, config TreeOfThoughtConfig, logger *zap.Logger) *TreeOfThought

NewTreeOfThought创造出"思想理性之树".

func (*TreeOfThought) Execute

func (t *TreeOfThought) Execute(ctx context.Context, task string) (*ReasoningResult, error)

执行运行"思想之树"推理模式.

func (*TreeOfThought) Name

func (t *TreeOfThought) Name() string

type TreeOfThoughtConfig

type TreeOfThoughtConfig struct {
	BranchingFactor int           // Number of thoughts to generate at each step
	MaxDepth        int           // Maximum depth of the thought tree
	BeamWidth       int           // Number of best paths to keep (beam search)
	EvaluationMode  string        // "self" (LLM self-eval) or "vote" (majority voting)
	PruneThreshold  float64       // Minimum score to keep a branch (0-1)
	Timeout         time.Duration // Overall timeout
	ParallelEval    bool          // Evaluate branches in parallel
	Model           string        // LLM model for thought generation
	EvalModel       string        // LLM model for evaluation (can be cheaper)
}

TreatyOfThoughtConfig 配置"思想之树"推理模式.

func DefaultTreeOfThoughtConfig

func DefaultTreeOfThoughtConfig() TreeOfThoughtConfig

默认TreeOfThoughtConfig 返回合理的默认值 。

type Trial

type Trial struct {
	Number     int         `json:"number"`
	Action     string      `json:"action"`
	Result     string      `json:"result"`
	Score      float64     `json:"score"`
	Reflection *Reflection `json:"reflection,omitempty"`
}

审判是解决这项任务的一次尝试。

Jump to

Keyboard shortcuts

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