Skip to main content

mofa_kernel/agent/components/
reasoner.rs

1//! 推理组件
2//!
3//! 定义 Agent 的推理/思考能力
4
5use crate::agent::capabilities::ReasoningStrategy;
6use crate::agent::context::AgentContext;
7use crate::agent::error::AgentResult;
8use crate::agent::types::AgentInput;
9use async_trait::async_trait;
10use serde::{Deserialize, Serialize};
11
12/// 推理器 Trait
13///
14/// 负责 Agent 的推理/思考过程
15///
16/// # 示例
17///
18/// ```rust,ignore
19/// use mofa_kernel::agent::components::reasoner::{Reasoner, ReasoningResult};
20/// use mofa_foundation::agent::components::reasoner::DirectReasoner;
21///
22/// // 使用 foundation 层提供的具体实现
23/// let reasoner = DirectReasoner;
24/// // 或者实现自定义 Reasoner
25/// struct MyReasoner;
26///
27/// #[async_trait]
28/// impl Reasoner for MyReasoner {
29///     async fn reason(&self, input: &AgentInput, ctx: &CoreAgentContext) -> AgentResult<ReasoningResult> {
30///         Ok(ReasoningResult {
31///             thoughts: vec![],
32///             decision: Decision::Respond { content: input.to_text() },
33///             confidence: 1.0,
34///         })
35///     }
36///
37///     fn strategy(&self) -> ReasoningStrategy {
38///         ReasoningStrategy::Direct
39///     }
40/// }
41/// ```
42#[async_trait]
43pub trait Reasoner: Send + Sync {
44    /// 执行推理过程
45    async fn reason(&self, input: &AgentInput, ctx: &AgentContext) -> AgentResult<ReasoningResult>;
46
47    /// 获取推理策略
48    fn strategy(&self) -> ReasoningStrategy;
49
50    /// 是否支持多步推理
51    fn supports_multi_step(&self) -> bool {
52        matches!(
53            self.strategy(),
54            ReasoningStrategy::ReAct { .. }
55                | ReasoningStrategy::ChainOfThought
56                | ReasoningStrategy::TreeOfThought { .. }
57        )
58    }
59
60    /// 推理器名称
61    fn name(&self) -> &str {
62        "reasoner"
63    }
64
65    /// 推理器描述
66    fn description(&self) -> Option<&str> {
67        None
68    }
69}
70
71/// 推理结果
72#[derive(Debug, Clone, Serialize, Deserialize)]
73pub struct ReasoningResult {
74    /// 思考步骤
75    pub thoughts: Vec<ThoughtStep>,
76    /// 最终决策
77    pub decision: Decision,
78    /// 置信度 (0.0 - 1.0)
79    pub confidence: f32,
80}
81
82impl ReasoningResult {
83    /// 创建简单的响应结果
84    pub fn respond(content: impl Into<String>) -> Self {
85        Self {
86            thoughts: vec![],
87            decision: Decision::Respond {
88                content: content.into(),
89            },
90            confidence: 1.0,
91        }
92    }
93
94    /// 创建工具调用结果
95    pub fn call_tool(tool_name: impl Into<String>, arguments: serde_json::Value) -> Self {
96        Self {
97            thoughts: vec![],
98            decision: Decision::CallTool {
99                tool_name: tool_name.into(),
100                arguments,
101            },
102            confidence: 1.0,
103        }
104    }
105
106    /// 添加思考步骤
107    pub fn with_thought(mut self, step: ThoughtStep) -> Self {
108        self.thoughts.push(step);
109        self
110    }
111
112    /// 设置置信度
113    pub fn with_confidence(mut self, confidence: f32) -> Self {
114        self.confidence = confidence.clamp(0.0, 1.0);
115        self
116    }
117}
118
119/// 思考步骤
120#[derive(Debug, Clone, Serialize, Deserialize)]
121pub struct ThoughtStep {
122    /// 步骤类型
123    pub step_type: ThoughtStepType,
124    /// 步骤内容
125    pub content: String,
126    /// 步骤序号
127    pub step_number: usize,
128    /// 时间戳 (毫秒)
129    pub timestamp_ms: u64,
130}
131
132impl ThoughtStep {
133    /// 创建新的思考步骤
134    pub fn new(step_type: ThoughtStepType, content: impl Into<String>, step_number: usize) -> Self {
135        let now = std::time::SystemTime::now()
136            .duration_since(std::time::UNIX_EPOCH)
137            .unwrap_or_default()
138            .as_millis() as u64;
139
140        Self {
141            step_type,
142            content: content.into(),
143            step_number,
144            timestamp_ms: now,
145        }
146    }
147
148    /// 创建思考步骤
149    pub fn thought(content: impl Into<String>, step_number: usize) -> Self {
150        Self::new(ThoughtStepType::Thought, content, step_number)
151    }
152
153    /// 创建分析步骤
154    pub fn analysis(content: impl Into<String>, step_number: usize) -> Self {
155        Self::new(ThoughtStepType::Analysis, content, step_number)
156    }
157
158    /// 创建规划步骤
159    pub fn planning(content: impl Into<String>, step_number: usize) -> Self {
160        Self::new(ThoughtStepType::Planning, content, step_number)
161    }
162
163    /// 创建反思步骤
164    pub fn reflection(content: impl Into<String>, step_number: usize) -> Self {
165        Self::new(ThoughtStepType::Reflection, content, step_number)
166    }
167}
168
169/// 思考步骤类型
170#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
171pub enum ThoughtStepType {
172    /// 思考
173    Thought,
174    /// 分析
175    Analysis,
176    /// 规划
177    Planning,
178    /// 反思
179    Reflection,
180    /// 评估
181    Evaluation,
182    /// 自定义
183    Custom(String),
184}
185
186/// 决策类型
187#[derive(Debug, Clone, Serialize, Deserialize)]
188pub enum Decision {
189    /// 直接响应
190    Respond {
191        /// 响应内容
192        content: String,
193    },
194    /// 调用工具
195    CallTool {
196        /// 工具名称
197        tool_name: String,
198        /// 工具参数
199        arguments: serde_json::Value,
200    },
201    /// 调用多个工具 (并行)
202    CallMultipleTools {
203        /// 工具调用列表
204        tool_calls: Vec<ToolCall>,
205    },
206    /// 委托给其他 Agent
207    Delegate {
208        /// 目标 Agent ID
209        agent_id: String,
210        /// 委托任务
211        task: String,
212    },
213    /// 需要更多信息
214    NeedMoreInfo {
215        /// 需要的信息
216        questions: Vec<String>,
217    },
218    /// 无法处理
219    CannotHandle {
220        /// 原因
221        reason: String,
222    },
223}
224
225/// 工具调用
226#[derive(Debug, Clone, Serialize, Deserialize)]
227pub struct ToolCall {
228    /// 工具名称
229    pub tool_name: String,
230    /// 工具参数
231    pub arguments: serde_json::Value,
232}
233
234impl ToolCall {
235    /// 创建新的工具调用
236    pub fn new(tool_name: impl Into<String>, arguments: serde_json::Value) -> Self {
237        Self {
238            tool_name: tool_name.into(),
239            arguments,
240        }
241    }
242}
243
244// Note: Concrete Reasoner implementations (like DirectReasoner) are provided
245// in the foundation layer (mofa-foundation::agent::components::reasoner)