(text: string)
| 76 | * @returns Vector embedding (simplified) |
| 77 | */ |
| 78 | export async function getEmbeddings(text: string): Promise<number[]> { |
| 79 | // This is an improved embedding function that creates a better vector representation |
| 80 | // Still simple but designed to create more topical differentiation |
| 81 | |
| 82 | const view = new Float32Array(1024); |
| 83 | |
| 84 | // Extract key terms and topics from the text |
| 85 | const keywordExtraction = extractKeywords(text); |
| 86 | |
| 87 | // Use a more sophisticated hash function that weights important terms |
| 88 | const termWeights = keywordExtraction.reduce( |
| 89 | (acc, item) => { |
| 90 | acc[item.term] = item.score; |
| 91 | return acc; |
| 92 | }, |
| 93 | {} as { [key: string]: number }, |
| 94 | ); |
| 95 | |
| 96 | // Fill the vector with values based on term importance and positions |
| 97 | const terms = Object.keys(termWeights); |
| 98 | |
| 99 | // Fill base vector with simple hash |
| 100 | for (let i = 0; i < view.length; i++) { |
| 101 | // Simple hash function for demo purposes |
| 102 | let hash = 0; |
| 103 | for (let j = 0; j < text.length; j += 10) { |
| 104 | // Sample text at intervals |
| 105 | hash = (hash << 5) - hash + text.charCodeAt(j) + i; |
| 106 | hash = hash & hash; // Convert to 32bit integer |
| 107 | } |
| 108 | // Normalize between -0.5 and 0.5 (base values) |
| 109 | view[i] = (hash % 100) / 200; |
| 110 | } |
| 111 | |
| 112 | // Enhance with keyword features |
| 113 | for (const term of terms) { |
| 114 | // Use term to seed a portion of the vector |
| 115 | const weight = termWeights[term]; |
| 116 | const termHash = simpleHash(term); |
| 117 | const startPos = termHash % 900; // Avoid last section |
| 118 | |
| 119 | // Enhance specific positions based on term |
| 120 | for (let i = 0; i < Math.min(term.length * 4, 50); i++) { |
| 121 | const pos = (startPos + i * 3) % 900; |
| 122 | // Add weighted value based on term importance |
| 123 | view[pos] += weight * 0.5 * (Math.sin(termHash + i) * 0.5 + 0.5); |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | // Normalize vector to unit length (important for cosine similarity) |
| 128 | normalizeVector(view); |
| 129 | |
| 130 | return Array.from(view); |
| 131 | } |
| 132 | |
| 133 | /** |
| 134 | * Extract keywords and their importance from text |
no test coverage detected