-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreact_agent.go
More file actions
326 lines (277 loc) · 8.16 KB
/
react_agent.go
File metadata and controls
326 lines (277 loc) · 8.16 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
package sdk
import (
"context"
"fmt"
"time"
logger "github.com/xraph/go-utils/log"
"github.com/xraph/go-utils/metrics"
)
// ReactAgent is an agent that uses the ReAct (Reasoning + Acting) strategy.
// It alternates between reasoning and acting until reaching a final answer.
type ReactAgent struct {
*Agent
strategy *ReactStrategy
reasoningPrompt string
}
// ReactAgentBuilder helps construct a ReactAgent.
type ReactAgentBuilder struct {
// Base agent configuration
id string
name string
description string
model string
provider string
// Execution configuration
systemPrompt string
tools []Tool
maxIterations int
temperature float64
// ReAct-specific configuration
reflectionInterval int
confidenceThreshold float64
reasoningPrompt string
// Dependencies
llmManager LLMManager
stateStore StateStore
memoryManager *MemoryManager
logger logger.Logger
metrics metrics.Metrics
// Optional components
guardrails *GuardrailManager
}
// NewReactAgentBuilder creates a new builder for ReactAgent.
func NewReactAgentBuilder(name string) *ReactAgentBuilder {
return &ReactAgentBuilder{
name: name,
maxIterations: 10,
temperature: 0.7,
reflectionInterval: 3,
confidenceThreshold: 0.7,
}
}
// WithID sets the agent ID.
func (b *ReactAgentBuilder) WithID(id string) *ReactAgentBuilder {
b.id = id
return b
}
// WithDescription sets the agent description.
func (b *ReactAgentBuilder) WithDescription(desc string) *ReactAgentBuilder {
b.description = desc
return b
}
// WithModel sets the LLM model.
func (b *ReactAgentBuilder) WithModel(model string) *ReactAgentBuilder {
b.model = model
return b
}
// WithProvider sets the LLM provider.
func (b *ReactAgentBuilder) WithProvider(provider string) *ReactAgentBuilder {
b.provider = provider
return b
}
// WithSystemPrompt sets the system prompt.
func (b *ReactAgentBuilder) WithSystemPrompt(prompt string) *ReactAgentBuilder {
b.systemPrompt = prompt
return b
}
// WithTools sets the available tools.
func (b *ReactAgentBuilder) WithTools(tools ...Tool) *ReactAgentBuilder {
b.tools = append(b.tools, tools...)
return b
}
// WithMaxIterations sets the maximum reasoning steps.
func (b *ReactAgentBuilder) WithMaxIterations(max int) *ReactAgentBuilder {
b.maxIterations = max
return b
}
// WithTemperature sets the LLM temperature.
func (b *ReactAgentBuilder) WithTemperature(temp float64) *ReactAgentBuilder {
b.temperature = temp
return b
}
// WithReflectionInterval sets how often to self-reflect.
func (b *ReactAgentBuilder) WithReflectionInterval(interval int) *ReactAgentBuilder {
b.reflectionInterval = interval
return b
}
// WithConfidenceThreshold sets the minimum confidence level.
func (b *ReactAgentBuilder) WithConfidenceThreshold(threshold float64) *ReactAgentBuilder {
b.confidenceThreshold = threshold
return b
}
// WithReasoningPrompt sets a custom reasoning prompt template.
func (b *ReactAgentBuilder) WithReasoningPrompt(prompt string) *ReactAgentBuilder {
b.reasoningPrompt = prompt
return b
}
// WithLLMManager sets the LLM manager.
func (b *ReactAgentBuilder) WithLLMManager(manager LLMManager) *ReactAgentBuilder {
b.llmManager = manager
return b
}
// WithStateStore sets the state store.
func (b *ReactAgentBuilder) WithStateStore(store StateStore) *ReactAgentBuilder {
b.stateStore = store
return b
}
// WithMemoryManager sets the memory manager.
func (b *ReactAgentBuilder) WithMemoryManager(manager *MemoryManager) *ReactAgentBuilder {
b.memoryManager = manager
return b
}
// WithLogger sets the logger.
func (b *ReactAgentBuilder) WithLogger(logger logger.Logger) *ReactAgentBuilder {
b.logger = logger
return b
}
// WithMetrics sets the metrics collector.
func (b *ReactAgentBuilder) WithMetrics(metrics metrics.Metrics) *ReactAgentBuilder {
b.metrics = metrics
return b
}
// WithGuardrails sets the guardrail manager.
func (b *ReactAgentBuilder) WithGuardrails(guardrails *GuardrailManager) *ReactAgentBuilder {
b.guardrails = guardrails
return b
}
// Build creates the ReactAgent.
func (b *ReactAgentBuilder) Build() (*ReactAgent, error) {
// Validate required fields
if b.name == "" {
return nil, fmt.Errorf("agent name is required")
}
if b.llmManager == nil {
return nil, fmt.Errorf("LLM manager is required")
}
// Generate ID if not provided
if b.id == "" {
b.id = fmt.Sprintf("react_agent_%d", time.Now().UnixNano())
}
// Create base agent
baseBuilder := NewAgentBuilder().
WithID(b.id).
WithName(b.name).
WithDescription(b.description).
WithModel(b.model).
WithProvider(b.provider).
WithSystemPrompt(b.systemPrompt).
WithTools(b.tools...).
WithLLMManager(b.llmManager).
WithStateStore(b.stateStore).
WithLogger(b.logger).
WithMetrics(b.metrics).
WithMaxIterations(b.maxIterations).
WithTemperature(b.temperature)
if b.guardrails != nil {
baseBuilder.WithGuardrails(b.guardrails)
}
agent, err := baseBuilder.Build()
if err != nil {
return nil, fmt.Errorf("failed to build base agent: %w", err)
}
// Create ReAct strategy
strategyConfig := &ReactStrategyConfig{
MaxIterations: b.maxIterations,
ReflectionInterval: b.reflectionInterval,
ConfidenceThreshold: b.confidenceThreshold,
MemoryManager: b.memoryManager,
ReasoningPrompt: b.reasoningPrompt,
}
strategy := NewReactStrategy(b.logger, b.metrics, strategyConfig)
// Create ReactAgent
reactAgent := &ReactAgent{
Agent: agent,
strategy: strategy,
reasoningPrompt: b.reasoningPrompt,
}
return reactAgent, nil
}
// Execute runs the agent using the ReAct strategy.
func (a *ReactAgent) Execute(ctx context.Context, input string) (*AgentExecution, error) {
if a.logger != nil {
a.logger.Info("Executing ReactAgent",
logger.String("agent_id", a.ID),
logger.String("input", input),
)
}
execution, err := a.strategy.Execute(ctx, a.Agent, input)
if err != nil {
if a.logger != nil {
a.logger.Error("ReactAgent execution failed",
logger.String("agent_id", a.ID),
logger.String("error", err.Error()),
)
}
return execution, err
}
if a.metrics != nil {
a.metrics.Counter("forge.ai.sdk.react_agent.executions",
metrics.WithLabel("agent_id", a.ID),
metrics.WithLabel("status", string(execution.Status)),
).Inc()
}
return execution, nil
}
// GetTraces returns the reasoning traces from the last execution.
func (a *ReactAgent) GetTraces() []ReasoningTrace {
return a.strategy.GetTraces()
}
// GetReflections returns the reflection results from the last execution.
func (a *ReactAgent) GetReflections() []ReflectionResult {
return a.strategy.GetReflections()
}
// GetStrategy returns the underlying ReAct strategy.
func (a *ReactAgent) GetStrategy() *ReactStrategy {
return a.strategy
}
// SetReasoningPrompt updates the reasoning prompt template.
func (a *ReactAgent) SetReasoningPrompt(prompt string) {
a.reasoningPrompt = prompt
// Update strategy's prompt if needed
}
// AsTool converts the ReactAgent into a Tool that can be used by other agents.
func (a *ReactAgent) AsTool() Tool {
return Tool{
Name: "call_" + a.Name,
Description: a.getToolDescription(),
Parameters: map[string]any{
"type": "object",
"properties": map[string]any{
"input": map[string]any{
"type": "string",
"description": "The question or task for the " + a.Name + " agent",
},
},
"required": []string{"input"},
},
Handler: func(ctx context.Context, params map[string]any) (any, error) {
input, ok := params["input"].(string)
if !ok {
return nil, fmt.Errorf("input parameter is required and must be a string")
}
execution, err := a.Execute(ctx, input)
if err != nil {
return nil, err
}
return map[string]any{
"output": execution.FinalOutput,
"iterations": len(execution.Steps),
"traces": a.GetTraces(),
}, nil
},
}
}
func (a *ReactAgent) getToolDescription() string {
desc := a.Description
if desc == "" {
desc = fmt.Sprintf("Use ReAct reasoning to solve: %s", a.Name)
}
if len(a.tools) > 0 {
toolNames := make([]string, len(a.tools))
for i, tool := range a.tools {
toolNames[i] = tool.Name
}
desc += fmt.Sprintf(" Available tools: %v", toolNames)
}
return desc
}