Documentation
¶
Overview ¶
包 reasoning 提供面向智能体的多种高级推理模式。
概述 ¶
本包用于解决智能体"如何系统性地思考、规划和解决复杂问题"的需求。 它将学术界和工程实践中的主流推理范式封装为统一接口,使智能体可以 根据任务特征选择最合适的推理策略,并通过注册表机制实现动态发现与切换。
核心接口 ¶
- ReasoningPattern: 推理模式统一接口,定义 Execute(ctx, task) 和 Name() 方法。
- PatternRegistry: 推理模式注册表,支持注册、查询、列举与注销。
核心模型 ¶
- ReasoningResult: 推理结果,包含最终答案、置信度、步骤链、Token 消耗与延迟。
- ReasoningStep: 推理步骤,类型涵盖 thought、action、observation、 evaluation、backtrack,支持嵌套子步骤与评分。
推理模式 ¶
- Tree-of-Thought (ToT): 思维树模式,并行探索多条推理路径, 通过 Beam Search 剪枝保留最优分支,适合需要创造性探索的开放问题。
- Plan-and-Execute: 先规划后执行模式,支持执行中自适应重规划, 适合目标明确但路径不确定的结构化任务。
- ReWOO: 无观测推理模式,先生成完整计划再批量执行所有步骤, 最后综合观测结果,适合步骤间依赖明确的高效批处理场景。
- Reflexion: 反思模式,通过"尝试 → 评估 → 反思 → 改进"的迭代循环 逐步提升输出质量,适合需要自我纠错的任务。
- Dynamic Planner: 动态规划模式,构建计划树并支持回溯与备选路径切换, 适合不确定性高、需要灵活应变的复杂任务。
- Iterative Deepening: 迭代加深研究模式,以宽度优先生成查询、 深度优先递归探索,逐层加深理解,适合开放式研究与信息综合。
与 agent 包协同 ¶
reasoning 可与 agent 执行流程集成:
- 通过 PatternRegistry 注册可用推理模式,运行时按任务类型动态选择
- 推理过程中调用 agent 的工具执行器(ToolExecutor)与 LLM Provider
- ReasoningResult 的步骤链可输出至 observability 包进行追踪与审计
Index ¶
- type DynamicPlanner
- type DynamicPlannerConfig
- type ExecutionPlan
- type ExecutionStep
- type IterativeDeepening
- type IterativeDeepeningConfig
- type MemoryEntry
- type NodeStatus
- type PatternRegistry
- type PlanAndExecute
- type PlanExecuteConfig
- type PlanNode
- type PlanStep
- type ReWOO
- type ReWOOConfig
- type ReasoningPattern
- type ReasoningResult
- type ReasoningStep
- type Reflection
- type ReflexionConfig
- type ReflexionExecutor
- type ReflexionMemory
- type TreeOfThought
- type TreeOfThoughtConfig
- type Trial
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(provider llm.Provider, executor tools.ToolExecutor, schemas []llm.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
}
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(provider llm.Provider, 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运行"惯性深化研究"推理模式.
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 (*PatternRegistry) Get ¶
func (r *PatternRegistry) Get(name string) (ReasoningPattern, bool)
Get 获取推理模式
func (*PatternRegistry) MustGet ¶
func (r *PatternRegistry) MustGet(name string) ReasoningPattern
MustGet 获取推理模式,不存在则 panic
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(provider llm.Provider, executor tools.ToolExecutor, schemas []llm.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
}
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(provider llm.Provider, executor tools.ToolExecutor, schemas []llm.ToolSchema, config ReWOOConfig, logger *zap.Logger) *ReWOO
NewReWOO创建了新的ReWOO理性.
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
}
ReWOOConfig配置了ReWOO推理模式.
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"`
}
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(provider llm.Provider, executor tools.ToolExecutor, schemas []llm.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 TreeOfThought ¶
type TreeOfThought struct {
// contains filtered or unexported fields
}
Tree Of Thought 执行思想之树推理模式. 它平行地探索多条推理路径,并选择了最好的一条.
func NewTreeOfThought ¶
func NewTreeOfThought(provider llm.Provider, 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
}
TreatyOfThoughtConfig 配置"思想之树"推理模式.
func DefaultTreeOfThoughtConfig ¶
func DefaultTreeOfThoughtConfig() TreeOfThoughtConfig
默认TreeOfThoughtConfig 返回合理的默认值 。