This function is a Server Action, as denoted by the "use server"; directive at the top of the file. This means that it can be called anywhere in your Next.js application. This function will take an input, run it through a Zod schema to ensure it adheres to the correct schema, and then creates a new resource in the database. This is the ideal location to generate and store embeddings of the newly created resources.
First, you call the generateEmbeddings function created in the previous step, passing in the source material (content). Once you have your embeddings of the source material, you can save them to the database, passing the resourceId alongside each embedding.
Add the following test function to your lib/ai/embedding.ts file:
Copy
// Test function - you can remove this after testingexport const testEmbeddingGeneration = async () => { const testContent = "This is a test document. It contains multiple sentences. Each sentence will become a chunk. The chunks will be converted to embeddings."; try { console.log("Testing embedding generation..."); const result = await generateEmbeddings(testContent); console.log("✅ Embedding generation successful!"); console.log(`📊 Generated ${result.length} embeddings`); console.log(`📝 First chunk: "${result[0]?.content}"`); console.log( `🔢 First embedding dimensions: ${result[0]?.embedding.length}` ); return result; } catch (error) { console.error("❌ Embedding generation failed:", error); throw error; }};
If everything is working correctly, you should see output similar to:
Copy
Testing embedding generation...✅ Embedding generation successful!📊 Generated 4 embeddings📝 First chunk: "This is a test document"🔢 First embedding dimensions: 1536Test completed successfully