(value: string)
| 15 | } |
| 16 | |
| 17 | export function embedText(value: string): Float32Array { |
| 18 | const vector = new Float32Array(EMBEDDING_DIMENSIONS) |
| 19 | const tokens = tokenize(value) |
| 20 | |
| 21 | for (const token of tokens) { |
| 22 | const hash = hashToken(token) |
| 23 | for (let index = 0; index < 4; index++) { |
| 24 | const raw = hash.readUInt32BE(index * 4) |
| 25 | const dimension = raw % EMBEDDING_DIMENSIONS |
| 26 | const sign = (hash[index + 16]! & 1) === 0 ? 1 : -1 |
| 27 | vector[dimension]! += sign |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | let norm = 0 |
| 32 | for (const value of vector) { |
| 33 | norm += value * value |
| 34 | } |
| 35 | norm = Math.sqrt(norm) |
| 36 | |
| 37 | if (norm > 0) { |
| 38 | for (let index = 0; index < vector.length; index++) { |
| 39 | vector[index]! /= norm |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | return vector |
| 44 | } |
| 45 | |
| 46 | export function embeddingToSqlInput(embedding: Float32Array): Buffer { |
| 47 | return Buffer.from(embedding.buffer.slice(0)) |
no test coverage detected