-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreact_strategy.go
More file actions
662 lines (567 loc) · 17.6 KB
/
Copy pathreact_strategy.go
File metadata and controls
662 lines (567 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
package sdk
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"github.com/xraph/ai-sdk/llm"
logger "github.com/xraph/go-utils/log"
"github.com/xraph/go-utils/metrics"
)
// ReactStrategy implements the ReAct (Reasoning + Acting) pattern.
// It alternates between reasoning (thinking) and acting (tool use) until reaching a final answer.
type ReactStrategy struct {
// Configuration
maxIterations int
reflectionInterval int // Reflect every N steps
confidenceThreshold float64
timeout time.Duration
// Dependencies
memoryManager *MemoryManager
logger logger.Logger
metrics metrics.Metrics
// State
traces []ReasoningTrace
reflections []ReflectionResult
// Prompt templates
reasoningPrompt string
reflectionPrompt string
}
// ReactStrategyConfig configures the ReAct strategy.
type ReactStrategyConfig struct {
MaxIterations int
ReflectionInterval int
ConfidenceThreshold float64
Timeout time.Duration
MemoryManager *MemoryManager
ReasoningPrompt string
ReflectionPrompt string
}
// NewReactStrategy creates a new ReAct strategy.
func NewReactStrategy(logger logger.Logger, metrics metrics.Metrics, config *ReactStrategyConfig) *ReactStrategy {
if config == nil {
config = &ReactStrategyConfig{}
}
// Set defaults
if config.MaxIterations == 0 {
config.MaxIterations = 10
}
if config.ReflectionInterval == 0 {
config.ReflectionInterval = 3
}
if config.ConfidenceThreshold == 0 {
config.ConfidenceThreshold = 0.7
}
if config.Timeout == 0 {
config.Timeout = 5 * time.Minute
}
if config.ReasoningPrompt == "" {
config.ReasoningPrompt = defaultReasoningPrompt
}
if config.ReflectionPrompt == "" {
config.ReflectionPrompt = defaultReflectionPrompt
}
return &ReactStrategy{
maxIterations: config.MaxIterations,
reflectionInterval: config.ReflectionInterval,
confidenceThreshold: config.ConfidenceThreshold,
timeout: config.Timeout,
memoryManager: config.MemoryManager,
logger: logger,
metrics: metrics,
traces: make([]ReasoningTrace, 0),
reflections: make([]ReflectionResult, 0),
reasoningPrompt: config.ReasoningPrompt,
reflectionPrompt: config.ReflectionPrompt,
}
}
// Execute runs the ReAct reasoning loop.
func (s *ReactStrategy) Execute(ctx context.Context, agent *Agent, input string) (*AgentExecution, error) {
startTime := time.Now()
// Create execution context with timeout
execCtx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
execution := &AgentExecution{
ID: generateExecutionID(),
AgentID: agent.ID,
StartTime: startTime,
Status: ExecutionStatusRunning,
Steps: make([]*AgentStep, 0),
Metadata: make(map[string]any),
}
// Clear previous traces
s.traces = make([]ReasoningTrace, 0)
s.reflections = make([]ReflectionResult, 0)
if s.logger != nil {
s.logger.Info("Starting ReAct strategy execution",
logger.String("agent_id", agent.ID),
logger.String("execution_id", execution.ID),
)
}
// Recall relevant memories if available
var memoryContext string
if s.memoryManager != nil {
memories, err := s.memoryManager.Recall(execCtx, input, MemoryTierLongTerm, 5)
if err == nil && len(memories) > 0 {
memoryContext = s.formatMemories(memories)
}
}
// Main ReAct loop
currentInput := input
for iteration := 0; iteration < s.maxIterations; iteration++ {
// Check for cancellation
select {
case <-execCtx.Done():
execution.Status = ExecutionStatusCancelled
execution.Error = "execution timeout"
return execution, execCtx.Err()
default:
}
// Step 1: Generate thought/reasoning
trace, err := s.think(execCtx, agent, currentInput, memoryContext, iteration)
if err != nil {
execution.Status = ExecutionStatusFailed
execution.Error = err.Error()
return execution, fmt.Errorf("thinking failed at iteration %d: %w", iteration, err)
}
s.traces = append(s.traces, trace)
// Create agent step for this iteration
step := &AgentStep{
Index: iteration,
ID: fmt.Sprintf("%s_step_%d", execution.ID, iteration),
AgentID: agent.ID,
ExecutionID: execution.ID,
Input: currentInput,
StartTime: time.Now(),
State: StepStateRunning,
Metadata: make(map[string]any),
}
step.Metadata["reasoning_trace"] = trace
// Check if this is a final answer
if s.isFinalAnswer(trace) {
step.Output = trace.Observation
step.State = StepStateCompleted
step.EndTime = time.Now()
step.Duration = step.EndTime.Sub(step.StartTime)
execution.Steps = append(execution.Steps, step)
execution.Status = ExecutionStatusCompleted
execution.FinalOutput = trace.Observation
execution.EndTime = time.Now()
if s.logger != nil {
s.logger.Info("ReAct strategy completed with final answer",
logger.String("execution_id", execution.ID),
logger.Int("iterations", iteration+1),
)
}
return execution, nil
}
// Step 2: Execute action if specified
if trace.Action != "" {
observation, err := s.act(execCtx, agent, trace)
if err != nil {
step.Error = err.Error()
step.State = StepStateFailed
trace.Observation = fmt.Sprintf("Error: %s", err.Error())
trace.Confidence = 0.3 // Low confidence on error
} else {
trace.Observation = observation
step.ToolResults = []StepToolResult{
{
Name: trace.Action,
Result: observation,
Duration: time.Since(step.StartTime),
},
}
}
// Update trace with observation
s.traces[len(s.traces)-1] = trace
}
step.Output = trace.Observation
step.State = StepStateCompleted
step.EndTime = time.Now()
step.Duration = step.EndTime.Sub(step.StartTime)
execution.Steps = append(execution.Steps, step)
// Step 3: Periodic self-reflection
if s.reflectionInterval > 0 && (iteration+1)%s.reflectionInterval == 0 {
reflection, err := s.reflect(execCtx, agent, s.traces)
if err == nil {
s.reflections = append(s.reflections, reflection)
// Check if we should stop based on reflection
if reflection.ShouldReplan || reflection.Score < 0.5 {
if s.logger != nil {
s.logger.Warn("Reflection suggests stopping",
logger.String("quality", reflection.Quality),
logger.Float64("score", reflection.Score),
)
}
}
}
}
// Step 4: Check confidence threshold
if trace.Confidence < s.confidenceThreshold {
if s.logger != nil {
s.logger.Warn("Confidence below threshold",
logger.Float64("confidence", trace.Confidence),
logger.Float64("threshold", s.confidenceThreshold),
)
}
}
// Prepare next iteration input
currentInput = s.buildNextInput(trace)
}
// Max iterations reached without final answer
execution.Status = ExecutionStatusCompleted
execution.FinalOutput = "Max iterations reached without definitive answer"
if len(s.traces) > 0 {
lastTrace := s.traces[len(s.traces)-1]
if lastTrace.Observation != "" {
execution.FinalOutput = lastTrace.Observation
}
}
execution.EndTime = time.Now()
if s.logger != nil {
s.logger.Warn("ReAct strategy completed at max iterations",
logger.String("execution_id", execution.ID),
logger.Int("iterations", s.maxIterations),
)
}
return execution, nil
}
// think generates reasoning about what to do next.
func (s *ReactStrategy) think(
ctx context.Context,
agent *Agent,
input string,
memoryContext string,
iteration int,
) (ReasoningTrace, error) {
trace := ReasoningTrace{
Step: iteration,
Timestamp: time.Now(),
Metadata: make(map[string]any),
}
// Build prompt with context
prompt := s.buildReasoningPrompt(input, memoryContext, s.traces)
// Call LLM for reasoning
request := llm.ChatRequest{
Provider: agent.Provider,
Model: agent.Model,
Messages: []llm.ChatMessage{
{
Role: "system",
Content: agent.systemPrompt,
},
{
Role: "user",
Content: prompt,
},
},
}
if agent.temperature != 0 {
request.Temperature = &agent.temperature
}
// Add tools if available
if len(agent.tools) > 0 {
llmTools := make([]llm.Tool, len(agent.tools))
for i, tool := range agent.tools {
llmTools[i] = llm.Tool{
Type: "function",
Function: &llm.FunctionDefinition{
Name: tool.Name,
Description: tool.Description,
Parameters: tool.Parameters,
},
}
}
request.Tools = llmTools
}
response, err := agent.llmManager.Chat(ctx, request)
if err != nil {
return trace, fmt.Errorf("LLM call failed: %w", err)
}
if len(response.Choices) == 0 {
return trace, errors.New("no response from LLM")
}
// Parse response
content := response.Choices[0].Message.Content
trace.Thought, trace.Action, trace.ActionInput, trace.Confidence = s.parseReasoningResponse(content)
// Handle tool calls from structured tool calling
if len(response.Choices[0].Message.ToolCalls) > 0 {
toolCall := response.Choices[0].Message.ToolCalls[0]
trace.Action = toolCall.Function.Name
// Parse arguments
var args map[string]any
if toolCall.Function.Arguments != "" {
_ = json.Unmarshal([]byte(toolCall.Function.Arguments), &args)
trace.ActionInput = args
}
}
return trace, nil
}
// act executes the specified action/tool.
func (s *ReactStrategy) act(ctx context.Context, agent *Agent, trace ReasoningTrace) (string, error) {
// Find the tool
var tool *Tool
for i := range agent.tools {
if agent.tools[i].Name == trace.Action {
tool = &agent.tools[i]
break
}
}
if tool == nil {
return "", fmt.Errorf("tool not found: %s", trace.Action)
}
// Execute tool
if tool.Handler == nil {
return "", fmt.Errorf("tool %s has no handler", trace.Action)
}
result, err := tool.Handler(ctx, trace.ActionInput)
if err != nil {
return "", fmt.Errorf("tool execution failed: %w", err)
}
// Convert result to string
observation := fmt.Sprintf("%v", result)
if resultStr, ok := result.(string); ok {
observation = resultStr
} else if resultBytes, err := json.Marshal(result); err == nil {
observation = string(resultBytes)
}
if s.metrics != nil {
s.metrics.Counter("forge.ai.sdk.react.tool_calls",
metrics.WithLabel("tool", trace.Action),
).Inc()
}
return observation, nil
}
// reflect performs self-assessment of reasoning quality.
func (s *ReactStrategy) reflect(
ctx context.Context,
agent *Agent,
traces []ReasoningTrace,
) (ReflectionResult, error) {
reflection := ReflectionResult{
Issues: make([]string, 0),
Suggestions: make([]string, 0),
}
// Build reflection prompt
prompt := s.buildReflectionPrompt(traces)
request := llm.ChatRequest{
Provider: agent.Provider,
Model: agent.Model,
Messages: []llm.ChatMessage{
{
Role: "user",
Content: prompt,
},
},
}
response, err := agent.llmManager.Chat(ctx, request)
if err != nil {
return reflection, err
}
if len(response.Choices) == 0 {
return reflection, errors.New("no reflection response")
}
// Parse reflection
content := response.Choices[0].Message.Content
reflection.Quality = s.extractQuality(content)
reflection.Score = s.extractScore(content)
reflection.Reasoning = content
reflection.Issues = s.extractIssues(content)
reflection.Suggestions = s.extractSuggestions(content)
reflection.ShouldReplan = strings.Contains(strings.ToLower(content), "replan") ||
strings.Contains(strings.ToLower(content), "start over")
return reflection, nil
}
// Helper methods
func (s *ReactStrategy) buildReasoningPrompt(input string, memoryContext string, previousTraces []ReasoningTrace) string {
var sb strings.Builder
// Add memory context if available
if memoryContext != "" {
sb.WriteString("Relevant past experiences:\n")
sb.WriteString(memoryContext)
sb.WriteString("\n\n")
}
// Add task
sb.WriteString(fmt.Sprintf(s.reasoningPrompt, input))
// Add previous traces
if len(previousTraces) > 0 {
sb.WriteString("\n\nPrevious steps:\n")
for _, trace := range previousTraces {
sb.WriteString(fmt.Sprintf("Step %d:\n", trace.Step))
sb.WriteString(fmt.Sprintf(" Thought: %s\n", trace.Thought))
if trace.Action != "" {
sb.WriteString(fmt.Sprintf(" Action: %s\n", trace.Action))
}
if trace.Observation != "" {
sb.WriteString(fmt.Sprintf(" Observation: %s\n", trace.Observation))
}
sb.WriteString("\n")
}
}
sb.WriteString("\nWhat is your next thought and action?")
return sb.String()
}
func (s *ReactStrategy) buildReflectionPrompt(traces []ReasoningTrace) string {
var sb strings.Builder
sb.WriteString(s.reflectionPrompt)
sb.WriteString("\n\nReasoning steps to evaluate:\n")
for _, trace := range traces {
sb.WriteString(fmt.Sprintf("Step %d: %s\n", trace.Step, trace.Thought))
if trace.Action != "" {
sb.WriteString(fmt.Sprintf(" Action: %s\n", trace.Action))
}
if trace.Observation != "" {
sb.WriteString(fmt.Sprintf(" Observation: %s\n", trace.Observation))
}
}
return sb.String()
}
func (s *ReactStrategy) parseReasoningResponse(content string) (thought, action string, actionInput map[string]any, confidence float64) {
confidence = 0.8 // Default confidence
lines := strings.Split(content, "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
if strings.HasPrefix(strings.ToLower(line), "thought:") {
thought = strings.TrimSpace(strings.TrimPrefix(strings.ToLower(line), "thought:"))
} else if strings.HasPrefix(strings.ToLower(line), "action:") {
action = strings.TrimSpace(strings.TrimPrefix(strings.ToLower(line), "action:"))
} else if strings.HasPrefix(strings.ToLower(line), "action input:") {
inputStr := strings.TrimSpace(strings.TrimPrefix(strings.ToLower(line), "action input:"))
_ = json.Unmarshal([]byte(inputStr), &actionInput)
} else if strings.HasPrefix(strings.ToLower(line), "confidence:") {
confStr := strings.TrimSpace(strings.TrimPrefix(strings.ToLower(line), "confidence:"))
_, _ = fmt.Sscanf(confStr, "%f", &confidence) // Best effort parsing
}
}
// If no structured format, treat entire content as thought
if thought == "" {
thought = content
}
return
}
func (s *ReactStrategy) isFinalAnswer(trace ReasoningTrace) bool {
lowerThought := strings.ToLower(trace.Thought)
lowerObs := strings.ToLower(trace.Observation)
finalMarkers := []string{
"final answer:",
"the answer is",
"in conclusion",
"therefore,",
"to summarize",
}
for _, marker := range finalMarkers {
if strings.Contains(lowerThought, marker) || strings.Contains(lowerObs, marker) {
return true
}
}
// No action means final answer
return trace.Action == ""
}
func (s *ReactStrategy) buildNextInput(trace ReasoningTrace) string {
if trace.Observation != "" {
return trace.Observation
}
return trace.Thought
}
func (s *ReactStrategy) formatMemories(memories []*MemoryEntry) string {
var sb strings.Builder
for i, mem := range memories {
sb.WriteString(fmt.Sprintf("%d. %s\n", i+1, mem.Content))
}
return sb.String()
}
func (s *ReactStrategy) extractQuality(content string) string {
lower := strings.ToLower(content)
if strings.Contains(lower, "good") || strings.Contains(lower, "excellent") {
return "good"
}
if strings.Contains(lower, "invalid") || strings.Contains(lower, "incorrect") {
return "invalid"
}
return "needs_improvement"
}
func (s *ReactStrategy) extractScore(content string) float64 {
// Try to find a numeric score
var score float64
if strings.Contains(content, "score:") {
_, _ = fmt.Sscanf(content, "score: %f", &score) // Best effort parsing
}
// Default based on quality
if score == 0 {
quality := s.extractQuality(content)
switch quality {
case "good":
score = 0.8
case "needs_improvement":
score = 0.6
case "invalid":
score = 0.3
}
}
return score
}
func (s *ReactStrategy) extractIssues(content string) []string {
// Simple extraction - look for lines starting with "Issue:" or "-"
var issues []string
lines := strings.Split(content, "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
if strings.HasPrefix(strings.ToLower(line), "issue:") {
issues = append(issues, strings.TrimSpace(strings.TrimPrefix(strings.ToLower(line), "issue:")))
}
}
return issues
}
func (s *ReactStrategy) extractSuggestions(content string) []string {
// Simple extraction
var suggestions []string
lines := strings.Split(content, "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
if strings.HasPrefix(strings.ToLower(line), "suggestion:") {
suggestions = append(suggestions, strings.TrimSpace(strings.TrimPrefix(strings.ToLower(line), "suggestion:")))
}
}
return suggestions
}
// Name returns the strategy name.
func (s *ReactStrategy) Name() string {
return "ReAct"
}
// SupportsReplanning indicates if this strategy can replan.
func (s *ReactStrategy) SupportsReplanning() bool {
return false // ReAct doesn't do explicit replanning
}
// GetTraces returns the reasoning traces.
func (s *ReactStrategy) GetTraces() []ReasoningTrace {
return s.traces
}
// GetReflections returns the reflection results.
func (s *ReactStrategy) GetReflections() []ReflectionResult {
return s.reflections
}
// Default prompts
const defaultReasoningPrompt = `You are solving: %s
Use this format:
Thought: [Your reasoning about what to do next]
Action: [Tool to use, or leave blank if you have the final answer]
Action Input: [JSON arguments for the tool]
Confidence: [Your confidence level 0-1]
OR if you have the final answer:
Thought: [Your reasoning about the solution]
Final Answer: [Your complete answer]
Be concise and logical in your reasoning.`
const defaultReflectionPrompt = `Evaluate the quality of the following reasoning steps.
Consider:
1. Logical consistency
2. Tool choice appropriateness
3. Progress toward the goal
4. Any circular reasoning or mistakes
Provide:
- Quality assessment (good/needs_improvement/invalid)
- Specific issues found
- Suggestions for improvement
- Whether to replan from scratch`