/ examples / js / embeddings / embed-basic.ts
embed-basic.ts
 1  /**
 2   * Basic Embedding Example
 3   * 
 4   * Demonstrates using Agent.embed() for text embeddings
 5   * 
 6   * Run: npx ts-node examples/js/embeddings/embed-basic.ts
 7   */
 8  
 9  import { Agent } from '../../../src/praisonai-ts/dist/agent/simple';
10  import { embed, embedMany, cosineSimilarity } from '../../../src/praisonai-ts/dist/llm/embeddings';
11  
12  async function main() {
13    console.log('=== Basic Embedding Example ===\n');
14  
15    // Method 1: Using Agent.embed()
16    console.log('1. Agent.embed() - Single text');
17    const agent = new Agent({
18      instructions: 'You are a helpful assistant',
19      llm: 'openai/gpt-4o-mini',
20      verbose: false
21    });
22  
23    const singleEmbedding = await agent.embed('Hello world');
24    console.log(`   Dimensions: ${(singleEmbedding as number[]).length}`);
25    console.log(`   First 5 values: [${(singleEmbedding as number[]).slice(0, 5).map(v => v.toFixed(4)).join(', ')}...]`);
26  
27    // Method 2: Using Agent.embed() with multiple texts
28    console.log('\n2. Agent.embed() - Multiple texts');
29    const multiEmbeddings = await agent.embed(['Hello', 'World', 'How are you?']);
30    console.log(`   Count: ${(multiEmbeddings as number[][]).length}`);
31    console.log(`   Each has ${(multiEmbeddings as number[][])[0].length} dimensions`);
32  
33    // Method 3: Direct embed function
34    console.log('\n3. Direct embed() function');
35    const result = await embed('PraisonAI is an AI agent framework');
36    console.log(`   Dimensions: ${result.embedding.length}`);
37    console.log(`   Tokens used: ${result.usage?.tokens || 'N/A'}`);
38  
39    // Method 4: Batch embeddings
40    console.log('\n4. Batch embedMany() function');
41    const texts = [
42      'Machine learning is a subset of AI',
43      'Deep learning uses neural networks',
44      'Natural language processing handles text'
45    ];
46    const batchResult = await embedMany(texts);
47    console.log(`   Embedded ${batchResult.embeddings.length} texts`);
48    console.log(`   Total tokens: ${batchResult.usage?.tokens || 'N/A'}`);
49  
50    // Method 5: Similarity comparison
51    console.log('\n5. Cosine Similarity');
52    const emb1 = await embed('I love programming');
53    const emb2 = await embed('Coding is my passion');
54    const emb3 = await embed('The weather is nice today');
55  
56    const sim12 = cosineSimilarity(emb1.embedding, emb2.embedding);
57    const sim13 = cosineSimilarity(emb1.embedding, emb3.embedding);
58  
59    console.log(`   "I love programming" vs "Coding is my passion": ${(sim12 * 100).toFixed(1)}%`);
60    console.log(`   "I love programming" vs "The weather is nice": ${(sim13 * 100).toFixed(1)}%`);
61  
62    console.log('\n=== Complete ===');
63  }
64  
65  main().catch(console.error);