-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathembedding_manager.go
More file actions
637 lines (545 loc) · 18.5 KB
/
embedding_manager.go
File metadata and controls
637 lines (545 loc) · 18.5 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
package main
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"math"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"time"
)
// EmbeddingConfig contains configuration for embedding generation
type EmbeddingConfig struct {
Enabled bool `json:"enabled"`
ModelPath string `json:"model_path"`
ModelType string `json:"model_type"` // "onnx" or "pytorch" or "ollama"
ModelURL string `json:"model_url"` // URL for downloading the model
VocabURL string `json:"vocab_url"` // URL for downloading the vocabulary
CacheEnabled bool `json:"cache_enabled"`
CacheSize int `json:"cache_size"`
BatchSize int `json:"batch_size"`
EmbbedingSize int `json:"embedding_size"`
Dimensions int `json:"dimensions"` // Embedding dimension size
UseOllama bool `json:"use_ollama"`
OllamaURL string `json:"ollama_url"`
OllamaModel string `json:"ollama_model"`
CommonCommands []string `json:"common_commands"`
ContextIncluded bool `json:"context_included"`
DirectoryIncluded bool `json:"directory_included"`
NumThreads int `json:"num_threads"`
UseGPU bool `json:"use_gpu"`
MaxTokenLength int `json:"max_token_length"`
}
// EmbeddingRequest represents a request to generate an embedding
type EmbeddingRequest struct {
Command string `json:"command"`
Directory string `json:"directory"`
Context map[string]string `json:"context"`
Timestamp time.Time `json:"timestamp"`
}
// EmbeddingResponse represents the response from an embedding request
type EmbeddingResponse struct {
ID string `json:"id"`
Command string `json:"command"`
Directory string `json:"directory"`
Embedding []float32 `json:"embedding"`
IsFromCmd bool `json:"is_from_cmd"`
IsFromCtx bool `json:"is_from_ctx"`
Normalized bool `json:"normalized"`
Score float32 `json:"score"`
Timestamp time.Time `json:"timestamp"`
}
// EmbeddingCache is a simple cache for embeddings
type EmbeddingCache struct {
Embeddings map[string]EmbeddingResponse
MaxSize int
Mutex sync.RWMutex
}
// EmbeddingManager handles the generation of embeddings
type EmbeddingManager struct {
config EmbeddingConfig
configPath string
cache *EmbeddingCache
onnxRuntime *ONNXRuntime
mutex sync.RWMutex
isInitialized bool
}
// NewEmbeddingManager creates a new embedding manager
func NewEmbeddingManager() (*EmbeddingManager, error) {
// Set up config directory in user's home directory
homeDir, err := os.UserHomeDir()
if err != nil {
homeDir = os.Getenv("HOME")
}
// Use ~/.config/delta/embeddings directory
configDir := filepath.Join(homeDir, ".config", "delta", "embeddings")
err = os.MkdirAll(configDir, 0755)
if err != nil {
return nil, fmt.Errorf("failed to create embeddings directory: %v", err)
}
configPath := filepath.Join(configDir, "embedding_config.json")
modelPath := filepath.Join(configDir, "models", "embedding_model.onnx")
// Create a cache
cache := &EmbeddingCache{
Embeddings: make(map[string]EmbeddingResponse),
MaxSize: 1000,
Mutex: sync.RWMutex{},
}
// Default configuration
defaultConfig := EmbeddingConfig{
Enabled: false,
ModelPath: modelPath,
ModelType: "onnx",
ModelURL: "https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2/resolve/main/model.onnx",
VocabURL: "https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2/resolve/main/vocab.txt",
CacheEnabled: true,
CacheSize: 1000,
BatchSize: 4,
EmbbedingSize: 384,
UseOllama: true,
OllamaURL: "http://localhost:11434",
OllamaModel: "phi4:latest",
CommonCommands: []string{"cd", "ls", "git", "docker", "npm", "python", "make"},
ContextIncluded: true,
DirectoryIncluded: true,
NumThreads: 4,
UseGPU: false,
MaxTokenLength: 128,
}
// Start with default configuration
// Note: We don't load from ConfigManager here to avoid circular dependencies
// The ConfigManager will update this manager's config after initialization
config := defaultConfig
// Create the manager
manager := &EmbeddingManager{
config: config,
configPath: configPath,
cache: cache,
mutex: sync.RWMutex{},
isInitialized: false,
}
// No need to load configuration here anymore
// The ConfigManager will handle this after initialization
return manager, nil
}
// Initialize initializes the embedding manager
func (em *EmbeddingManager) Initialize() error {
em.mutex.Lock()
defer em.mutex.Unlock()
// Setup cache
em.cache.MaxSize = em.config.CacheSize
// Create models directory if it doesn't exist
modelsDir := filepath.Dir(em.config.ModelPath)
err := os.MkdirAll(modelsDir, 0755)
if err != nil {
return fmt.Errorf("failed to create models directory: %v", err)
}
// Check if we should use ONNX
if em.config.ModelType == "onnx" && !em.config.UseOllama {
// Define the vocab path
vocabPath := filepath.Join(modelsDir, "vocab.txt")
// Check if ONNX model exists, if not, download it
if _, err := os.Stat(em.config.ModelPath); os.IsNotExist(err) {
fmt.Printf("Embedding model not found at %s. Attempting to download...\n", em.config.ModelPath)
if em.config.ModelURL == "" {
fmt.Println("No model URL specified. Falling back to Ollama.")
em.config.UseOllama = true
} else {
// Download the model
err = DownloadONNXEmbeddingModel(em.config.ModelPath, em.config.ModelURL)
if err != nil {
fmt.Printf("Failed to download embedding model: %v\n", err)
fmt.Println("Falling back to Ollama for embeddings.")
em.config.UseOllama = true
} else {
fmt.Printf("Successfully downloaded embedding model to %s\n", em.config.ModelPath)
}
}
}
// Check if vocab file exists, if not, download it
if _, err := os.Stat(vocabPath); os.IsNotExist(err) && !em.config.UseOllama {
fmt.Printf("Vocab file not found at %s. Attempting to download...\n", vocabPath)
if em.config.VocabURL == "" {
fmt.Println("No vocab URL specified. Falling back to Ollama.")
em.config.UseOllama = true
} else {
// Download the vocab file using a simple HTTP GET request
err = DownloadONNXEmbeddingModel(vocabPath, em.config.VocabURL)
if err != nil {
fmt.Printf("Failed to download vocab file: %v\n", err)
fmt.Println("Falling back to Ollama for embeddings.")
em.config.UseOllama = true
} else {
fmt.Printf("Successfully downloaded vocab file to %s\n", vocabPath)
}
}
}
// Initialize ONNX Runtime if model and vocab files exist
if !em.config.UseOllama {
// Create ONNX runtime configuration
onnxConfig := ONNXRuntimeConfig{
ModelPath: em.config.ModelPath,
VocabPath: vocabPath,
Dimension: em.config.EmbbedingSize,
MaxLength: em.config.MaxTokenLength,
BatchSize: em.config.BatchSize,
NumThreads: em.config.NumThreads,
UseGPU: em.config.UseGPU,
UseFP16: false, // Default to FP32 for better accuracy
GPUDeviceID: 0, // Default GPU device
}
// Initialize the ONNX runtime
onnxRuntime, err := NewONNXRuntime(onnxConfig)
if err != nil {
fmt.Printf("Failed to create ONNX runtime: %v\n", err)
fmt.Println("Falling back to Ollama for embeddings.")
em.config.UseOllama = true
} else {
// Initialize the ONNX runtime
err = onnxRuntime.Initialize()
if err != nil {
fmt.Printf("Failed to initialize ONNX runtime: %v\n", err)
fmt.Println("Falling back to Ollama for embeddings.")
em.config.UseOllama = true
} else {
// Store the ONNX runtime
em.onnxRuntime = onnxRuntime
fmt.Println("Successfully initialized ONNX runtime for embeddings.")
}
}
}
}
em.isInitialized = true
return nil
}
// loadConfig loads the embedding configuration from disk
func (em *EmbeddingManager) loadConfig() error {
// Check if config file exists
_, err := os.Stat(em.configPath)
if os.IsNotExist(err) {
return fmt.Errorf("config file does not exist")
}
// Read the config file
data, err := os.ReadFile(em.configPath)
if err != nil {
return err
}
// Unmarshal the JSON data
return json.Unmarshal(data, &em.config)
}
// saveConfig saves the embedding configuration to disk
func (em *EmbeddingManager) saveConfig() error {
// Marshal the config to JSON with indentation for readability
data, err := json.MarshalIndent(em.config, "", " ")
if err != nil {
return err
}
// Create directory if it doesn't exist
dir := filepath.Dir(em.configPath)
if err = os.MkdirAll(dir, 0755); err != nil {
return err
}
// Write to file
return os.WriteFile(em.configPath, data, 0644)
}
// IsEnabled returns whether embeddings are enabled
func (em *EmbeddingManager) IsEnabled() bool {
em.mutex.RLock()
defer em.mutex.RUnlock()
return em.config.Enabled && em.isInitialized
}
// Enable enables embeddings
func (em *EmbeddingManager) Enable() error {
em.mutex.Lock()
defer em.mutex.Unlock()
if !em.isInitialized {
return fmt.Errorf("embedding manager not initialized")
}
em.config.Enabled = true
return em.saveConfig()
}
// Disable disables embeddings
func (em *EmbeddingManager) Disable() error {
em.mutex.Lock()
defer em.mutex.Unlock()
em.config.Enabled = false
return em.saveConfig()
}
// GenerateEmbedding generates an embedding for a command
func (em *EmbeddingManager) GenerateEmbedding(request EmbeddingRequest) (*EmbeddingResponse, error) {
if !em.IsEnabled() {
return nil, fmt.Errorf("embedding generation not enabled")
}
// Check cache first
cacheKey := em.generateCacheKey(request)
if em.config.CacheEnabled {
if cachedEmbedding := em.getFromCache(cacheKey); cachedEmbedding != nil {
return cachedEmbedding, nil
}
}
// Prepare the input for embedding
var embedding []float32
var err error
if em.config.UseOllama {
// Generate embedding using Ollama
embedding, err = em.generateEmbeddingWithOllama(request)
} else if em.config.ModelType == "onnx" {
// Generate embedding using ONNX model
embedding, err = em.generateEmbeddingWithONNX(request)
} else {
// Fallback to a placeholder embedding for demonstration
embedding, err = em.generatePlaceholderEmbedding(request)
}
if err != nil {
return nil, err
}
// Create the response
response := &EmbeddingResponse{
ID: cacheKey,
Command: request.Command,
Directory: request.Directory,
Embedding: embedding,
IsFromCmd: true,
IsFromCtx: em.config.ContextIncluded,
Normalized: true,
Score: 1.0,
Timestamp: time.Now(),
}
// Add to cache
if em.config.CacheEnabled {
em.addToCache(cacheKey, *response)
}
return response, nil
}
// generateEmbeddingWithOllama generates an embedding using Ollama
func (em *EmbeddingManager) generateEmbeddingWithOllama(request EmbeddingRequest) ([]float32, error) {
// Get the AI manager to use Ollama
ai := GetAIManager()
if ai == nil || !ai.IsEnabled() {
return nil, fmt.Errorf("AI manager not available")
}
// Build the prompt for embedding
prompt := request.Command
// Add directory context if enabled
if em.config.DirectoryIncluded && request.Directory != "" {
prompt = fmt.Sprintf("Directory: %s\nCommand: %s", request.Directory, request.Command)
}
// Add additional context if enabled
if em.config.ContextIncluded && len(request.Context) > 0 {
contextStr := ""
for key, value := range request.Context {
contextStr += fmt.Sprintf("%s: %s\n", key, value)
}
prompt = fmt.Sprintf("%s\n%s", contextStr, prompt)
}
// Call Ollama to generate embedding
// This is a placeholder - actual Ollama embedding API call would go here
// In a real implementation, we would:
// 1. Call the Ollama embedding API
// 2. Parse the response
// 3. Return the embedding
// For now, return a placeholder embedding by hashing the command
return em.generatePlaceholderEmbedding(request)
}
// generateEmbeddingWithONNX generates an embedding using ONNX model
func (em *EmbeddingManager) generateEmbeddingWithONNX(request EmbeddingRequest) ([]float32, error) {
// Check if ONNX runtime is initialized
if em.onnxRuntime == nil {
return nil, fmt.Errorf("ONNX runtime not initialized")
}
// Build the input text for the model
var inputText string
// Start with the command
inputText = request.Command
// Add directory context if enabled
if em.config.DirectoryIncluded && request.Directory != "" {
inputText = fmt.Sprintf("Directory: %s\nCommand: %s", request.Directory, inputText)
}
// Add additional context if enabled
if em.config.ContextIncluded && len(request.Context) > 0 {
contextStr := ""
for key, value := range request.Context {
contextStr += fmt.Sprintf("%s: %s\n", key, value)
}
inputText = fmt.Sprintf("%s\n%s", contextStr, inputText)
}
// Generate the embedding using the ONNX runtime
embedding, err := em.onnxRuntime.GenerateEmbedding(inputText)
if err != nil {
return nil, fmt.Errorf("failed to generate embedding with ONNX: %v", err)
}
// Ensure the embedding is normalized
normalizeVector(embedding)
return embedding, nil
}
// generatePlaceholderEmbedding generates a placeholder embedding for demonstration
func (em *EmbeddingManager) generatePlaceholderEmbedding(request EmbeddingRequest) ([]float32, error) {
// Create a deterministic embedding based on the command
// This is just for demonstration purposes
commandHash := sha256.Sum256([]byte(request.Command))
dirHash := sha256.Sum256([]byte(request.Directory))
// Create an embedding of the configured size
embedding := make([]float32, em.config.EmbbedingSize)
// Fill with values derived from the hash
for i := 0; i < em.config.EmbbedingSize; i++ {
if i < 32 {
// Use command hash for first part
embedding[i] = float32(commandHash[i]) / 255.0
} else if i < 64 {
// Use directory hash for second part
embedding[i] = float32(dirHash[i-32]) / 255.0
} else {
// Use a combination for the rest
embedding[i] = float32((commandHash[i%32] + dirHash[i%32])) / 510.0
}
}
// Normalize the embedding
normalizeVector(embedding)
return embedding, nil
}
// generateCacheKey generates a cache key for an embedding request
func (em *EmbeddingManager) generateCacheKey(request EmbeddingRequest) string {
// Create a string containing all components for the key
keyComponents := []string{request.Command, request.Directory}
// Add context values if included
if em.config.ContextIncluded && len(request.Context) > 0 {
contextKeys := make([]string, 0, len(request.Context))
for key := range request.Context {
contextKeys = append(contextKeys, key)
}
// Sort for deterministic ordering
sort.Strings(contextKeys)
for _, key := range contextKeys {
keyComponents = append(keyComponents, key, request.Context[key])
}
}
// Join all components and hash
keyString := strings.Join(keyComponents, "|")
hash := sha256.Sum256([]byte(keyString))
return hex.EncodeToString(hash[:])
}
// getFromCache gets an embedding from the cache
func (em *EmbeddingManager) getFromCache(key string) *EmbeddingResponse {
em.cache.Mutex.RLock()
defer em.cache.Mutex.RUnlock()
if embedding, ok := em.cache.Embeddings[key]; ok {
// Clone the embedding to avoid modification
clonedEmbedding := embedding
return &clonedEmbedding
}
return nil
}
// addToCache adds an embedding to the cache
func (em *EmbeddingManager) addToCache(key string, embedding EmbeddingResponse) {
em.cache.Mutex.Lock()
defer em.cache.Mutex.Unlock()
// Add to cache
em.cache.Embeddings[key] = embedding
// If cache is full, remove oldest entries
if len(em.cache.Embeddings) > em.cache.MaxSize {
// Find oldest entries
type cacheEntry struct {
key string
timestamp time.Time
}
entries := make([]cacheEntry, 0, len(em.cache.Embeddings))
for k, v := range em.cache.Embeddings {
entries = append(entries, cacheEntry{k, v.Timestamp})
}
// Sort by timestamp (oldest first)
sort.Slice(entries, func(i, j int) bool {
return entries[i].timestamp.Before(entries[j].timestamp)
})
// Remove oldest entries until we're under the limit
for i := 0; i < len(entries)-em.cache.MaxSize; i++ {
delete(em.cache.Embeddings, entries[i].key)
}
}
}
// GetStats returns statistics about the embedding system
func (em *EmbeddingManager) GetStats() map[string]interface{} {
em.mutex.RLock()
defer em.mutex.RUnlock()
cacheSize := 0
if em.cache != nil {
em.cache.Mutex.RLock()
cacheSize = len(em.cache.Embeddings)
em.cache.Mutex.RUnlock()
}
return map[string]interface{}{
"enabled": em.config.Enabled,
"initialized": em.isInitialized,
"model_path": em.config.ModelPath,
"model_type": em.config.ModelType,
"embedding_size": em.config.EmbbedingSize,
"use_ollama": em.config.UseOllama,
"ollama_model": em.config.OllamaModel,
"cache_enabled": em.config.CacheEnabled,
"cache_size": em.config.CacheSize,
"batch_size": em.config.BatchSize,
"context_included": em.config.ContextIncluded,
"directory_included": em.config.DirectoryIncluded,
"common_commands": em.config.CommonCommands,
"cache_entries": cacheSize,
}
}
// UpdateConfig updates the embedding configuration
func (em *EmbeddingManager) UpdateConfig(config EmbeddingConfig) error {
em.mutex.Lock()
defer em.mutex.Unlock()
em.config = config
// Update cache size
if em.cache != nil {
em.cache.MaxSize = config.CacheSize
}
// Update ConfigManager if available
configManager := GetConfigManager()
if configManager != nil {
err := configManager.UpdateEmbeddingConfig(&config)
if err != nil {
fmt.Printf("Warning: Failed to update config manager: %v\n", err)
// Continue anyway and try to save locally
}
}
// Always save locally as well for backward compatibility
return em.saveConfig()
}
// Close closes the embedding manager
func (em *EmbeddingManager) Close() error {
em.mutex.Lock()
defer em.mutex.Unlock()
// Nothing to close for now
return nil
}
// Helper functions
// normalizeVector normalizes a vector to unit length
func normalizeVector(vec []float32) {
var sum float32
for _, v := range vec {
sum += v * v
}
length := float32(math.Sqrt(float64(sum)))
if length > 0 {
for i := range vec {
vec[i] /= length
}
}
}
// Global EmbeddingManager instance
var globalEmbeddingManager *EmbeddingManager
// GetEmbeddingManager returns the global EmbeddingManager instance
func GetEmbeddingManager() *EmbeddingManager {
if globalEmbeddingManager == nil {
var err error
globalEmbeddingManager, err = NewEmbeddingManager()
if err != nil {
fmt.Printf("Error initializing embedding manager: %v\n", err)
return nil
}
}
return globalEmbeddingManager
}