-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtoolchain.go
More file actions
723 lines (572 loc) · 17.6 KB
/
Copy pathtoolchain.go
File metadata and controls
723 lines (572 loc) · 17.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
package sdk
import (
"context"
"fmt"
"strconv"
"sync"
"time"
logger "github.com/xraph/go-utils/log"
"github.com/xraph/go-utils/metrics"
)
// ToolChain provides a fluent API for sequential tool execution with transformations
// and conditional branching. It simplifies common patterns that would otherwise require
// a full workflow definition.
//
// Example:
//
// result, err := sdk.NewToolChain(registry).
// Step("fetch_user", sdk.WithInput(map[string]any{"id": 123})).
// Transform(func(ctx *ChainContext, result any) any {
// user := result.(map[string]any)
// ctx.Set("user_name", user["name"])
// return user["id"]
// }).
// Step("get_orders").
// ConditionalStep("send_notification",
// sdk.When(func(ctx *ChainContext) bool {
// orders := ctx.GetLastResult().([]any)
// return len(orders) > 0
// }),
// ).
// OnStepComplete(func(step string, result any) {
// log.Printf("Completed: %s", step)
// }).
// Execute(ctx)
type ToolChain struct {
registry *ToolRegistry
logger logger.Logger
metrics metrics.Metrics
steps []ChainStep
context *ChainContext
errorHandler func(step string, err error) error
// Callbacks
onStepStart func(step string, input map[string]any)
onStepComplete func(step string, result any)
onChainStart func()
onChainComplete func(result *ChainResult)
// Configuration
timeout time.Duration
continueOnError bool
}
// ChainStep represents a single step in the tool chain.
type ChainStep struct {
// Step identification
Name string
ToolName string
Version string
// Input configuration
Input map[string]any
InputMapper func(ctx *ChainContext) map[string]any
// Output transformation
Transformer func(ctx *ChainContext, result any) any
// Conditional execution
Condition func(ctx *ChainContext) bool
// Branching
OnSuccess string // Name of next step on success (for non-linear flows)
OnFailure string // Name of step to jump to on failure
SkipOnFail bool // Skip this step if a previous step failed
// Parallel execution
Parallel []ChainStep // Steps to run in parallel
}
// ChainContext provides shared state across chain steps.
type ChainContext struct {
mu sync.RWMutex
// Shared data accessible by all steps
data map[string]any
// Results from each step
results map[string]any
// Execution tracking
currentStep string
lastResult any
errors map[string]error
// Parent context
ctx context.Context
}
// ChainResult contains the complete result of chain execution.
type ChainResult struct {
// Final result from the last step
FinalResult any
// Results from each step
StepResults map[string]any
// Execution metadata
StepsExecuted int
StepsSkipped int
TotalDuration time.Duration
StepDurations map[string]time.Duration
// Errors encountered
Errors map[string]error
Success bool
}
// ChainOption configures a chain step.
type ChainOption func(*ChainStep)
// NewToolChain creates a new tool chain.
func NewToolChain(registry *ToolRegistry) *ToolChain {
return &ToolChain{
registry: registry,
steps: make([]ChainStep, 0),
context: &ChainContext{
data: make(map[string]any),
results: make(map[string]any),
errors: make(map[string]error),
},
timeout: 5 * time.Minute,
}
}
// WithLogger sets the logger for the chain.
func (c *ToolChain) WithLogger(logger logger.Logger) *ToolChain {
c.logger = logger
return c
}
// WithMetrics sets the metrics for the chain.
func (c *ToolChain) WithMetrics(metrics metrics.Metrics) *ToolChain {
c.metrics = metrics
return c
}
// WithTimeout sets the overall chain timeout.
func (c *ToolChain) WithTimeout(timeout time.Duration) *ToolChain {
c.timeout = timeout
return c
}
// ContinueOnError configures the chain to continue even if a step fails.
func (c *ToolChain) ContinueOnError(continue_ bool) *ToolChain {
c.continueOnError = continue_
return c
}
// OnError sets a custom error handler.
func (c *ToolChain) OnError(handler func(step string, err error) error) *ToolChain {
c.errorHandler = handler
return c
}
// Step adds a tool execution step to the chain.
func (c *ToolChain) Step(toolName string, opts ...ChainOption) *ToolChain {
step := ChainStep{
Name: fmt.Sprintf("step_%d_%s", len(c.steps)+1, toolName),
ToolName: toolName,
Version: "1.0.0",
}
for _, opt := range opts {
opt(&step)
}
c.steps = append(c.steps, step)
return c
}
// NamedStep adds a named step to the chain (useful for conditional jumps).
func (c *ToolChain) NamedStep(name, toolName string, opts ...ChainOption) *ToolChain {
step := ChainStep{
Name: name,
ToolName: toolName,
Version: "1.0.0",
}
for _, opt := range opts {
opt(&step)
}
c.steps = append(c.steps, step)
return c
}
// ConditionalStep adds a step that only executes if the condition is true.
func (c *ToolChain) ConditionalStep(toolName string, condition func(ctx *ChainContext) bool, opts ...ChainOption) *ToolChain {
opts = append(opts, func(s *ChainStep) {
s.Condition = condition
})
return c.Step(toolName, opts...)
}
// Transform adds a transformer after the last step.
func (c *ToolChain) Transform(transformer func(ctx *ChainContext, result any) any) *ToolChain {
if len(c.steps) > 0 {
c.steps[len(c.steps)-1].Transformer = transformer
}
return c
}
// ParallelSteps adds multiple steps to run in parallel.
func (c *ToolChain) ParallelSteps(steps ...ChainStep) *ToolChain {
if len(steps) > 0 {
parentStep := ChainStep{
Name: fmt.Sprintf("parallel_%d", len(c.steps)+1),
Parallel: steps,
}
c.steps = append(c.steps, parentStep)
}
return c
}
// OnStepStart registers a callback for step start.
func (c *ToolChain) OnStepStart(fn func(step string, input map[string]any)) *ToolChain {
c.onStepStart = fn
return c
}
// OnStepComplete registers a callback for step completion.
func (c *ToolChain) OnStepComplete(fn func(step string, result any)) *ToolChain {
c.onStepComplete = fn
return c
}
// OnChainStart registers a callback for chain start.
func (c *ToolChain) OnChainStart(fn func()) *ToolChain {
c.onChainStart = fn
return c
}
// OnChainComplete registers a callback for chain completion.
func (c *ToolChain) OnChainComplete(fn func(result *ChainResult)) *ToolChain {
c.onChainComplete = fn
return c
}
// Execute runs the tool chain.
func (c *ToolChain) Execute(ctx context.Context) (*ChainResult, error) {
startTime := time.Now()
// Apply timeout
execCtx, cancel := context.WithTimeout(ctx, c.timeout)
defer cancel()
c.context.ctx = execCtx
if c.onChainStart != nil {
c.onChainStart()
}
if c.logger != nil {
c.logger.Debug("Starting tool chain execution",
logger.Int("steps", len(c.steps)),
logger.Duration("timeout", c.timeout),
)
}
result := &ChainResult{
StepResults: make(map[string]any),
StepDurations: make(map[string]time.Duration),
Errors: make(map[string]error),
Success: true,
}
// Execute steps
for i, step := range c.steps {
select {
case <-execCtx.Done():
result.Errors["chain"] = execCtx.Err()
result.Success = false
return result, fmt.Errorf("chain execution timed out: %w", execCtx.Err())
default:
}
stepStart := time.Now()
c.context.currentStep = step.Name
// Check condition
if step.Condition != nil && !step.Condition(c.context) {
if c.logger != nil {
c.logger.Debug("Skipping step (condition not met)",
logger.String("step", step.Name),
logger.Int("index", i),
)
}
result.StepsSkipped++
continue
}
// Check if this is a parallel step group
if len(step.Parallel) > 0 {
if err := c.executeParallelSteps(execCtx, step.Parallel, result); err != nil {
if !c.continueOnError {
result.Success = false
return result, err
}
}
result.StepsExecuted++
continue
}
// Build input
input := c.buildStepInput(step)
if c.onStepStart != nil {
c.onStepStart(step.Name, input)
}
// Execute tool
toolResult, err := c.registry.ExecuteTool(execCtx, step.ToolName, step.Version, input)
stepDuration := time.Since(stepStart)
result.StepDurations[step.Name] = stepDuration
if err != nil {
result.Errors[step.Name] = err
if c.errorHandler != nil {
err = c.errorHandler(step.Name, err)
}
if err != nil && !c.continueOnError {
result.Success = false
if c.logger != nil {
c.logger.Error("Tool chain step failed",
logger.String("step", step.Name),
logger.String("tool", step.ToolName),
logger.String("error", err.Error()),
)
}
return result, fmt.Errorf("step %s failed: %w", step.Name, err)
}
if c.logger != nil {
c.logger.Warn("Tool chain step failed (continuing)",
logger.String("step", step.Name),
logger.String("tool", step.ToolName),
logger.String("error", err.Error()),
)
}
result.StepsExecuted++
continue
}
// Apply transformer if present
stepResult := toolResult.Result
if step.Transformer != nil {
stepResult = step.Transformer(c.context, stepResult)
}
// Store result
c.context.results[step.Name] = stepResult
c.context.lastResult = stepResult
result.StepResults[step.Name] = stepResult
if c.onStepComplete != nil {
c.onStepComplete(step.Name, stepResult)
}
if c.logger != nil {
c.logger.Debug("Tool chain step completed",
logger.String("step", step.Name),
logger.String("tool", step.ToolName),
logger.Duration("duration", stepDuration),
)
}
result.StepsExecuted++
}
result.FinalResult = c.context.lastResult
result.TotalDuration = time.Since(startTime)
if c.onChainComplete != nil {
c.onChainComplete(result)
}
if c.metrics != nil {
toolchainSuccess := 0
if result.Success {
toolchainSuccess = 1
}
c.metrics.Counter("forge.ai.sdk.toolchain.executions", metrics.WithLabel("executions", strconv.Itoa(result.StepsExecuted))).Inc()
c.metrics.Histogram("forge.ai.sdk.toolchain.duration", metrics.WithLabel("duration", strconv.FormatFloat(result.TotalDuration.Seconds(), 'f', -1, 64))).Observe(result.TotalDuration.Seconds())
c.metrics.Histogram("forge.ai.sdk.toolchain.steps", metrics.WithLabel("steps", strconv.Itoa(result.StepsExecuted))).Observe(float64(result.StepsExecuted))
c.metrics.Histogram("forge.ai.sdk.toolchain.steps_skipped", metrics.WithLabel("steps_skipped", strconv.Itoa(result.StepsSkipped))).Observe(float64(result.StepsSkipped))
c.metrics.Histogram("forge.ai.sdk.toolchain.success", metrics.WithLabel("success", strconv.Itoa(toolchainSuccess))).Observe(float64(toolchainSuccess))
c.metrics.Histogram("forge.ai.sdk.toolchain.errors", metrics.WithLabel("errors", strconv.Itoa(len(result.Errors)))).Observe(float64(len(result.Errors)))
for stepName, duration := range result.StepDurations {
c.metrics.Histogram("forge.ai.sdk.toolchain.step_durations", metrics.WithLabel("step_name", stepName)).Observe(duration.Seconds())
}
c.metrics.Histogram("forge.ai.sdk.toolchain.step_durations_total", metrics.WithLabel("step_durations_total", strconv.FormatFloat(result.TotalDuration.Seconds(), 'f', -1, 64))).Observe(result.TotalDuration.Seconds())
c.metrics.Histogram("forge.ai.sdk.toolchain.step_durations_average", metrics.WithLabel("step_durations_average", strconv.FormatFloat(result.TotalDuration.Seconds()/float64(result.StepsExecuted), 'f', -1, 64))).Observe(result.TotalDuration.Seconds() / float64(result.StepsExecuted))
c.metrics.Histogram("forge.ai.sdk.toolchain.step_durations_max", metrics.WithLabel("step_durations_max", strconv.FormatFloat(result.TotalDuration.Seconds(), 'f', -1, 64))).Observe(result.TotalDuration.Seconds())
}
if c.logger != nil {
c.logger.Info("Tool chain completed",
logger.Int("steps_executed", result.StepsExecuted),
logger.Int("steps_skipped", result.StepsSkipped),
logger.Duration("duration", result.TotalDuration),
logger.Bool("success", result.Success),
)
}
return result, nil
}
// executeParallelSteps executes steps in parallel.
func (c *ToolChain) executeParallelSteps(ctx context.Context, steps []ChainStep, result *ChainResult) error {
var (
wg sync.WaitGroup
mu sync.Mutex
firstErr error
)
for _, step := range steps {
wg.Add(1)
go func(s ChainStep) {
defer wg.Done()
input := c.buildStepInput(s)
toolResult, err := c.registry.ExecuteTool(ctx, s.ToolName, s.Version, input)
mu.Lock()
defer mu.Unlock()
if err != nil {
result.Errors[s.Name] = err
if firstErr == nil {
firstErr = err
}
return
}
stepResult := toolResult.Result
if s.Transformer != nil {
stepResult = s.Transformer(c.context, stepResult)
}
c.context.mu.Lock()
c.context.results[s.Name] = stepResult
c.context.mu.Unlock()
result.StepResults[s.Name] = stepResult
}(step)
}
wg.Wait()
return firstErr
}
// buildStepInput builds the input for a step.
func (c *ToolChain) buildStepInput(step ChainStep) map[string]any {
// Use input mapper if provided
if step.InputMapper != nil {
return step.InputMapper(c.context)
}
// Use static input if provided
if step.Input != nil {
return step.Input
}
// Default: use last result as input
if c.context.lastResult != nil {
if m, ok := c.context.lastResult.(map[string]any); ok {
return m
}
return map[string]any{"input": c.context.lastResult}
}
return make(map[string]any)
}
// --- ChainContext methods ---
// Set stores a value in the context.
func (cc *ChainContext) Set(key string, value any) {
cc.mu.Lock()
defer cc.mu.Unlock()
cc.data[key] = value
}
// Get retrieves a value from the context.
func (cc *ChainContext) Get(key string) any {
cc.mu.RLock()
defer cc.mu.RUnlock()
return cc.data[key]
}
// GetString retrieves a string value from the context.
func (cc *ChainContext) GetString(key string) string {
if v := cc.Get(key); v != nil {
if s, ok := v.(string); ok {
return s
}
}
return ""
}
// GetInt retrieves an int value from the context.
func (cc *ChainContext) GetInt(key string) int {
if v := cc.Get(key); v != nil {
switch n := v.(type) {
case int:
return n
case int64:
return int(n)
case float64:
return int(n)
}
}
return 0
}
// GetBool retrieves a bool value from the context.
func (cc *ChainContext) GetBool(key string) bool {
if v := cc.Get(key); v != nil {
if b, ok := v.(bool); ok {
return b
}
}
return false
}
// GetLastResult returns the result of the previous step.
func (cc *ChainContext) GetLastResult() any {
cc.mu.RLock()
defer cc.mu.RUnlock()
return cc.lastResult
}
// GetStepResult returns the result of a specific step.
func (cc *ChainContext) GetStepResult(stepName string) any {
cc.mu.RLock()
defer cc.mu.RUnlock()
return cc.results[stepName]
}
// GetError returns the error from a specific step.
func (cc *ChainContext) GetError(stepName string) error {
cc.mu.RLock()
defer cc.mu.RUnlock()
return cc.errors[stepName]
}
// HasError checks if any step has errored.
func (cc *ChainContext) HasError() bool {
cc.mu.RLock()
defer cc.mu.RUnlock()
return len(cc.errors) > 0
}
// Context returns the underlying context.Context.
func (cc *ChainContext) Context() context.Context {
return cc.ctx
}
// --- Chain options ---
// WithInput sets static input for a step.
func WithInput(input map[string]any) ChainOption {
return func(s *ChainStep) {
s.Input = input
}
}
// WithInputMapper sets a dynamic input mapper for a step.
func WithInputMapper(mapper func(ctx *ChainContext) map[string]any) ChainOption {
return func(s *ChainStep) {
s.InputMapper = mapper
}
}
// WithVersion sets the tool version for a step.
func WithVersion(version string) ChainOption {
return func(s *ChainStep) {
s.Version = version
}
}
// WithStepName sets a custom name for the step.
func WithStepName(name string) ChainOption {
return func(s *ChainStep) {
s.Name = name
}
}
// When creates a condition function for conditional steps.
func When(condition func(ctx *ChainContext) bool) func(ctx *ChainContext) bool {
return condition
}
// IfPreviousSucceeded creates a condition that checks if the previous step succeeded.
func IfPreviousSucceeded() func(ctx *ChainContext) bool {
return func(ctx *ChainContext) bool {
return !ctx.HasError()
}
}
// IfResultContains creates a condition that checks if the last result contains a key.
func IfResultContains(key string) func(ctx *ChainContext) bool {
return func(ctx *ChainContext) bool {
if result, ok := ctx.GetLastResult().(map[string]any); ok {
_, exists := result[key]
return exists
}
return false
}
}
// IfContextValue creates a condition based on a context value.
func IfContextValue(key string, expected any) func(ctx *ChainContext) bool {
return func(ctx *ChainContext) bool {
return ctx.Get(key) == expected
}
}
// --- Pipeline helper ---
// Pipeline creates a simple sequential chain with automatic input passing.
// Each tool's output becomes the next tool's input.
func Pipeline(registry *ToolRegistry, tools ...string) *ToolChain {
chain := NewToolChain(registry)
for _, tool := range tools {
chain.Step(tool)
}
return chain
}
// --- MapReduce helper ---
// MapReduce executes a tool over multiple inputs and reduces the results.
func MapReduce(
registry *ToolRegistry,
toolName string,
inputs []map[string]any,
reducer func(results []any) any,
) *ToolChain {
chain := NewToolChain(registry)
// Create parallel steps for each input
parallelSteps := make([]ChainStep, len(inputs))
for i, input := range inputs {
parallelSteps[i] = ChainStep{
Name: fmt.Sprintf("map_%d", i),
ToolName: toolName,
Version: "1.0.0",
Input: input,
}
}
chain.ParallelSteps(parallelSteps...)
// Add reducer as final transformer
chain.Transform(func(ctx *ChainContext, _ any) any {
results := make([]any, len(inputs))
for i := range inputs {
results[i] = ctx.GetStepResult(fmt.Sprintf("map_%d", i))
}
return reducer(results)
})
return chain
}