A step-by-step guide from your first embedding to full RAG with a local LLM.
Install the package and generate an embedding in a few lines:
dotnet new console -n EmbeddingDemo
cd EmbeddingDemo
dotnet add package ElBruno.LocalEmbeddingsusing ElBruno.LocalEmbeddings;
// Create the generator (downloads model automatically on first run)
// Async factory is recommended in ASP.NET/UI contexts.
await using var generator = await LocalEmbeddingGenerator.CreateAsync();
// Generate an embedding — single-string convenience method
var embedding = await generator.GenerateEmbeddingAsync("Hello, world!");
float[] vector = embedding.Vector.ToArray();
Console.WriteLine($"Dimensions: {vector.Length}"); // 384
Console.WriteLine($"First 3 values: {vector[0]:F4}, {vector[1]:F4}, {vector[2]:F4}");The first run downloads the default model (sentence-transformers/all-MiniLM-L6-v2) and caches it locally. Subsequent runs load instantly.
Compatibility note:
new LocalEmbeddingGenerator()is still supported, but it may block while resolving/downloading the model.
Tip:
GenerateEmbeddingAsync(string)returns a singleEmbedding<float>directly. If you need the fullGeneratedEmbeddingscollection, useGenerateAsync(string)instead. For multiple texts, use the batch overloadGenerateAsync(IEnumerable<string>).
Embeddings turn text into vectors. Similar texts produce vectors that point in similar directions. Cosine similarity measures this — 1.0 means identical, 0.0 means unrelated.
using ElBruno.LocalEmbeddings.Extensions; // for CosineSimilarity
var embeddings = await generator.GenerateAsync(["I love programming", "I enjoy coding"]);
float similarity = embeddings[0].CosineSimilarity(embeddings[1]);
Console.WriteLine($"Similarity: {similarity:P1}"); // ~85%+Try comparing unrelated sentences to see the difference:
var embeddings = await generator.GenerateAsync(["I love programming", "The weather is nice today"]);
float similarity = embeddings[0].CosineSimilarity(embeddings[1]);
Console.WriteLine($"Similarity: {similarity:P1}"); // much lowerNeed a full all-pairs matrix (like model.similarity(...) in SentenceTransformers)? Use Similarity:
using ElBruno.LocalEmbeddings.Extensions;
var embeddings = await generator.GenerateAsync(new[]
{
"The weather is lovely today.",
"It's so sunny outside!",
"He drove to the stadium."
});
float[,] matrix = embeddings.Similarity();
Console.WriteLine(matrix[0, 1]); // similarity between sentence 0 and 1Process many texts in a single call for better throughput:
var documents = new[]
{
"Machine learning is a subset of artificial intelligence.",
"JavaScript is widely used for web development.",
"C# is developed by Microsoft for .NET applications."
};
var embeddings = await generator.GenerateAsync(documents);
Console.WriteLine($"Generated {embeddings.Count} embeddings, each with {embeddings[0].Vector.Length} dimensions");Batching is more efficient than calling GenerateAsync once per string because the ONNX runtime can optimize memory and computation across the batch.
Use FindClosestAsync to search a collection by meaning instead of keywords:
using ElBruno.LocalEmbeddings.Extensions;
// Build a searchable collection
var docs = new[]
{
"Python for data science",
"JavaScript for web apps",
"C# for .NET development",
"Rust for systems programming",
"Swift for iOS development"
};
var docEmbeddings = await generator.GenerateAsync(docs);
// Search by meaning (one-line helper)
var results = await generator.FindClosestAsync(
query: "What language for building websites?",
corpus: docs,
corpusEmbeddings: docEmbeddings,
topK: 2,
minScore: 0.3f);
foreach (var result in results)
Console.WriteLine($" {result.Score:P0} — {result.Text}");
// Output: JavaScript for web apps ranks highestFindClosestAsync computes cosine similarity against every item and returns the top matches above the minimum score threshold.
Register LocalEmbeddings with IServiceCollection for production apps:
using ElBruno.LocalEmbeddings.Extensions;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.DependencyInjection;
var services = new ServiceCollection();
services.AddLocalEmbeddings(options =>
{
options.ModelName = "sentence-transformers/all-MiniLM-L6-v2";
options.MaxSequenceLength = 256;
});
var provider = services.BuildServiceProvider();
var generator = provider.GetRequiredService<IEmbeddingGenerator<string, Embedding<float>>>();
var result = await generator.GenerateAsync(["DI works!"]);
Console.WriteLine($"Dimensions: {result[0].Vector.Length}");Note: The single-string extension methods (
GenerateAsync(string)andGenerateEmbeddingAsync(string)) work onIEmbeddingGenerator<string, Embedding<float>>too — they're auto-discovered from theElBruno.LocalEmbeddingsnamespace.
The AddLocalEmbeddings() method registers:
IOptions<LocalEmbeddingsOptions>— configurationHttpClientviaIHttpClientFactory— for model downloadsIEmbeddingGenerator<string, Embedding<float>>— the generator (singleton)
See Dependency Injection docs for all registration overloads including IConfiguration binding from appsettings.json.
When your app needs a real vector-store abstraction (instead of in-memory tuple search), use the companion package ElBruno.LocalEmbeddings.VectorData.
dotnet add package ElBruno.LocalEmbeddings.VectorDatausing ElBruno.LocalEmbeddings.VectorData.Extensions;
using Microsoft.Extensions.VectorData;
services.AddLocalEmbeddingsWithInMemoryVectorStore(
options => options.ModelName = "sentence-transformers/all-MiniLM-L6-v2")
.AddVectorStoreCollection<int, ProductRecord>("products");This keeps embedding generation local while providing a dependency-light in-memory vector store implementation aligned with the standard Microsoft.Extensions.VectorData abstractions.
Retrieval-Augmented Generation (RAG) combines embeddings-based search with an LLM to answer questions using your own data. The pattern:
User question
→ Embed the question (LocalEmbeddings)
→ Find similar documents (cosine similarity)
→ Build a prompt with the retrieved context
→ Send to LLM (phi4-mini)
→ Stream the response
Two complete RAG samples are included:
| Sample | LLM Provider | How to Run |
|---|---|---|
| RagOllama | Ollama + OllamaSharp |
ollama pull phi4-mini then dotnet run |
| RagFoundryLocal | Foundry Local + OpenAI client | Install Foundry Local then dotnet run |
Both use LocalEmbeddingGenerator for embeddings and IChatClient (from Microsoft.Extensions.AI) for chat completions, so the RAG logic is identical — only the LLM provider changes.
Tip: The RagOllama sample uses the companion package
ElBruno.LocalEmbeddings.KernelMemorywhich integrates directly with Microsoft Kernel Memory. Instead of building the RAG pipeline manually, the single call.WithLocalEmbeddings()onKernelMemoryBuilderhandles embedding registration. See Kernel Memory Integration for details.
// 1. Embed the user's question (single-string convenience method)
var queryEmbedding = await embeddingGenerator.GenerateEmbeddingAsync(userQuestion);
// 2. Find the most relevant documents
var results = vectorStore.Search(queryEmbedding, topK: 3);
// 3. Build a prompt with retrieved context
var context = string.Join("\n\n", results.Select(r => r.Content));
var prompt = $"""
Answer the question using only the context below.
Context:
{context}
Question: {userQuestion}
""";
// 4. Stream the LLM response
await foreach (var chunk in chatClient.GetStreamingResponseAsync(prompt))
Console.Write(chunk);- API Reference — Full class and method documentation
- Configuration — All options, supported models, cache locations
- Alternative Models — Step-by-step local model download + non-default model hello world
- Dependency Injection — All DI overloads and
IConfigurationbinding - Kernel Memory Integration — Use local embeddings with Microsoft Kernel Memory for semantic memory / RAG
- VectorData Integration — Use local embeddings with Microsoft.Extensions.VectorData abstractions
- Samples README — All sample projects with prerequisites and run instructions
Dive into embeddings and local AI on multiple platforms:
- 📖 Check the blog at elbruno.com for detailed posts on RAG patterns, model selection, and production tips
- 🎙️ Listen to No Tienen Nombre podcast (Spanish) for conversations about AI and development culture
- 📹 Watch tutorials on YouTube for live demos and end-to-end walkthroughs
- 🔔 Follow @elbruno on Twitter/X for quick tips and releases