1 | private cosineSimilarity(vecA: Embedding, vecB: Embedding): number { |
2 | const dotProduct = vecA.reduce((sum, value, index) => sum + value * vecB[index], 0); |
3 | const magnitudeA = Math.sqrt(vecA.reduce((sum, value) => sum + value ** 2, 0)); |
4 | const magnitudeB = Math.sqrt(vecB.reduce((sum, value) => sum + value ** 2, 0)); |
5 | |
6 | return magnitudeA > 0 && magnitudeB > 0 ? dotProduct / (magnitudeA * magnitudeB) : 0; |
7 | } |
8 | |
9 | findClosestEmbedding(queryEmbedding: Embedding): string | null { |
10 | let bestMatch: string | null = null; |
11 | let bestSimilarity = -Infinity; |
12 | |
13 | for (const [key, embedding] of this.embeddings.entries()) { |
14 | const similarity = this.cosineSimilarity(queryEmbedding, embedding); |
15 | if (similarity > bestSimilarity) { |
16 | bestSimilarity = similarity; |
17 | bestMatch = key; |
18 | } |
19 | } |
20 | |
21 | return bestMatch; |
22 | } |
23 | |
Codebase understanding
Start projects from scratch or load your existing code repository
Teamwork with AI
Assign tasks flexibly between human team members and specialized AI agents.
Integrate your existing environment