File size: 1,586 Bytes
8e944c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { llm, EMBEDDING_MODEL } from "./llm";

export async function generateEmbedding(
  text: string
): Promise<number[] | null> {
  try {
    const response = await llm.embeddings.create({
      model: EMBEDDING_MODEL,
      input: text.slice(0, 8000),
    });
    return response.data[0].embedding;
  } catch (error) {
    console.error("Failed to generate embedding:", error);
    return null;
  }
}

export function cosineSimilarity(a: number[], b: number[]): number {
  if (a.length !== b.length) return 0;
  let dotProduct = 0;
  let normA = 0;
  let normB = 0;
  for (let i = 0; i < a.length; i++) {
    dotProduct += a[i] * b[i];
    normA += a[i] * a[i];
    normB += b[i] * b[i];
  }
  if (normA === 0 || normB === 0) return 0;
  return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
}

export function findSimilarIdeas(
  targetEmbedding: number[],
  allIdeas: { id: string; title: string; embedding: string | null }[],
  excludeId: string,
  topK: number = 5
): { id: string; title: string; similarity: number }[] {
  const results: { id: string; title: string; similarity: number }[] = [];

  for (const idea of allIdeas) {
    if (idea.id === excludeId || !idea.embedding) continue;
    try {
      const embedding = JSON.parse(idea.embedding) as number[];
      const similarity = cosineSimilarity(targetEmbedding, embedding);
      results.push({ id: idea.id, title: idea.title, similarity });
    } catch {
      continue;
    }
  }

  return results
    .sort((a, b) => b.similarity - a.similarity)
    .slice(0, topK)
    .filter((r) => r.similarity > 0.3);
}