-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbatch.go
More file actions
270 lines (214 loc) · 5.6 KB
/
Copy pathbatch.go
File metadata and controls
270 lines (214 loc) · 5.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
package sdk
import (
"context"
"sync"
"time"
logger "github.com/xraph/go-utils/log"
"github.com/xraph/go-utils/metrics"
)
// BatchProcessor handles efficient bulk request processing.
type BatchProcessor struct {
llmManager LLMManager
logger logger.Logger
metrics metrics.Metrics
// Configuration
maxBatchSize int
maxWaitTime time.Duration
maxConcurrency int
enableBatching bool
// Internal state
queue []BatchRequest
mu sync.Mutex
processingTimer *time.Timer
}
// BatchConfig configures batch processing.
type BatchConfig struct {
MaxBatchSize int // Maximum requests per batch
MaxWaitTime time.Duration // Maximum time to wait before processing
MaxConcurrency int // Maximum concurrent batches
EnableBatching bool // Enable/disable batching
}
// BatchRequest represents a single request in a batch.
type BatchRequest struct {
ID string
Prompt string
Model string
Options map[string]any
Result chan<- *Result
Error chan<- error
}
// BatchResult contains results from batch processing.
type BatchResult struct {
Successful int
Failed int
TotalTime time.Duration
Results []*Result
Errors []error
}
// NewBatchProcessor creates a new batch processor.
func NewBatchProcessor(
llmManager LLMManager,
logger logger.Logger,
metrics metrics.Metrics,
config BatchConfig,
) *BatchProcessor {
if config.MaxBatchSize == 0 {
config.MaxBatchSize = 10
}
if config.MaxWaitTime == 0 {
config.MaxWaitTime = 100 * time.Millisecond
}
if config.MaxConcurrency == 0 {
config.MaxConcurrency = 5
}
return &BatchProcessor{
llmManager: llmManager,
logger: logger,
metrics: metrics,
maxBatchSize: config.MaxBatchSize,
maxWaitTime: config.MaxWaitTime,
maxConcurrency: config.MaxConcurrency,
enableBatching: config.EnableBatching,
queue: make([]BatchRequest, 0, config.MaxBatchSize),
}
}
// Submit submits a request for batch processing.
func (bp *BatchProcessor) Submit(ctx context.Context, req BatchRequest) error {
if !bp.enableBatching {
// Process immediately if batching disabled
return bp.processImmediate(ctx, req)
}
bp.mu.Lock()
defer bp.mu.Unlock()
bp.queue = append(bp.queue, req)
// Process if batch is full
if len(bp.queue) >= bp.maxBatchSize {
go bp.processBatch()
bp.queue = make([]BatchRequest, 0, bp.maxBatchSize)
if bp.processingTimer != nil {
bp.processingTimer.Stop()
}
return nil
}
// Start/reset timer
if bp.processingTimer == nil {
bp.processingTimer = time.AfterFunc(bp.maxWaitTime, func() {
bp.processBatch()
})
}
return nil
}
// ProcessBatch processes all requests in a batch.
func (bp *BatchProcessor) ProcessBatch(ctx context.Context, requests []BatchRequest) *BatchResult {
start := time.Now()
result := &BatchResult{
Results: make([]*Result, 0, len(requests)),
Errors: make([]error, 0),
}
// Use worker pool for concurrency
semaphore := make(chan struct{}, bp.maxConcurrency)
var wg sync.WaitGroup
for _, req := range requests {
wg.Add(1)
semaphore <- struct{}{} // Acquire
go func(r BatchRequest) {
defer wg.Done()
defer func() { <-semaphore }() // Release
// Process individual request
builder := NewGenerateBuilder(ctx, bp.llmManager, bp.logger, bp.metrics)
builder.WithPrompt(r.Prompt)
if r.Model != "" {
builder.WithModel(r.Model)
}
res, err := builder.Execute()
if err != nil {
result.Failed++
result.Errors = append(result.Errors, err)
if r.Error != nil {
r.Error <- err
}
} else {
result.Successful++
result.Results = append(result.Results, res)
if r.Result != nil {
r.Result <- res
}
}
}(req)
}
wg.Wait()
result.TotalTime = time.Since(start)
if bp.metrics != nil {
bp.metrics.Counter("forge.ai.sdk.batch.processed",
metrics.WithLabel("status", "success"),
).Add(float64(result.Successful))
bp.metrics.Counter("forge.ai.sdk.batch.processed",
metrics.WithLabel("status", "failed"),
).Add(float64(result.Failed))
bp.metrics.Histogram("forge.ai.sdk.batch.duration").Observe(result.TotalTime.Seconds())
}
return result
}
func (bp *BatchProcessor) processBatch() {
bp.mu.Lock()
if len(bp.queue) == 0 {
bp.mu.Unlock()
return
}
batch := make([]BatchRequest, len(bp.queue))
copy(batch, bp.queue)
bp.queue = make([]BatchRequest, 0, bp.maxBatchSize)
bp.processingTimer = nil
bp.mu.Unlock()
if bp.logger != nil {
bp.logger.Info("processing batch",
F("size", len(batch)),
)
}
ctx := context.Background()
bp.ProcessBatch(ctx, batch)
}
func (bp *BatchProcessor) processImmediate(ctx context.Context, req BatchRequest) error {
builder := NewGenerateBuilder(ctx, bp.llmManager, bp.logger, bp.metrics)
builder.WithPrompt(req.Prompt)
if req.Model != "" {
builder.WithModel(req.Model)
}
res, err := builder.Execute()
if err != nil {
if req.Error != nil {
req.Error <- err
}
return err
}
if req.Result != nil {
req.Result <- res
}
return nil
}
// Flush processes all pending requests immediately.
func (bp *BatchProcessor) Flush(ctx context.Context) error {
bp.mu.Lock()
if len(bp.queue) == 0 {
bp.mu.Unlock()
return nil
}
batch := make([]BatchRequest, len(bp.queue))
copy(batch, bp.queue)
bp.queue = make([]BatchRequest, 0, bp.maxBatchSize)
bp.mu.Unlock()
bp.ProcessBatch(ctx, batch)
return nil
}
// GetStats returns batch processing statistics.
func (bp *BatchProcessor) GetStats() BatchStats {
bp.mu.Lock()
defer bp.mu.Unlock()
return BatchStats{
QueueSize: len(bp.queue),
}
}
// BatchStats contains batch processing statistics.
type BatchStats struct {
QueueSize int
}