Execute 执行工具链
(ctx context.Context, tc *tools.ToolContext)
| 221 | |
| 222 | // Execute 执行工具链 |
| 223 | func (c *ToolChain) Execute(ctx context.Context, tc *tools.ToolContext) *ChainResult { |
| 224 | if len(c.steps) == 0 { |
| 225 | return &ChainResult{ |
| 226 | Success: false, |
| 227 | Error: "no steps in chain", |
| 228 | } |
| 229 | } |
| 230 | |
| 231 | results := make([]*CallToolResult, len(c.steps)) |
| 232 | var prevResult any |
| 233 | |
| 234 | for i, step := range c.steps { |
| 235 | input := step.Input |
| 236 | |
| 237 | // 如果有 mapper 且有前一步结果,使用 mapper 生成输入 |
| 238 | if step.InputMapper != nil && prevResult != nil { |
| 239 | input = step.InputMapper(prevResult) |
| 240 | } |
| 241 | |
| 242 | result, _ := c.bridge.CallTool(ctx, step.Name, input, tc) |
| 243 | results[i] = result |
| 244 | |
| 245 | if !result.Success { |
| 246 | return &ChainResult{ |
| 247 | Steps: results[:i+1], |
| 248 | Success: false, |
| 249 | Error: fmt.Sprintf("step %d (%s) failed: %s", i, step.Name, result.Error), |
| 250 | } |
| 251 | } |
| 252 | |
| 253 | prevResult = result.Result |
| 254 | } |
| 255 | |
| 256 | return &ChainResult{ |
| 257 | Steps: results, |
| 258 | FinalResult: prevResult, |
| 259 | Success: true, |
| 260 | } |
| 261 | } |