Skip to content

Latest commit

 

History

History
246 lines (174 loc) · 10 KB

getting-started.md

File metadata and controls

246 lines (174 loc) · 10 KB

Getting Started — ElBruno.LocalEmbeddings

A step-by-step guide from your first embedding to full RAG with a local LLM.

Step 1: Hello World — Generate Your First Embedding

Install the package and generate an embedding in a few lines:

dotnet new console -n EmbeddingDemo
cd EmbeddingDemo
dotnet add package ElBruno.LocalEmbeddings
using 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 single Embedding<float> directly. If you need the full GeneratedEmbeddings collection, use GenerateAsync(string) instead. For multiple texts, use the batch overload GenerateAsync(IEnumerable<string>).

Step 2: Compare Two Sentences — Cosine Similarity

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 lower

Need 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 1

Step 3: Batch Processing — Embed Multiple Documents

Process 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.

Step 4: Semantic Search — Find Relevant Documents

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 highest

FindClosestAsync computes cosine similarity against every item and returns the top matches above the minimum score threshold.

Step 5: Dependency Injection — Use in Real Applications

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) and GenerateEmbeddingAsync(string)) work on IEmbeddingGenerator<string, Embedding<float>> too — they're auto-discovered from the ElBruno.LocalEmbeddings namespace.

The AddLocalEmbeddings() method registers:

  • IOptions<LocalEmbeddingsOptions> — configuration
  • HttpClient via IHttpClientFactory — for model downloads
  • IEmbeddingGenerator<string, Embedding<float>> — the generator (singleton)

See Dependency Injection docs for all registration overloads including IConfiguration binding from appsettings.json.

Step 6 (Optional): Plug into Microsoft.Extensions.VectorData

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.VectorData
using 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.

Step 7: RAG — Combine with a Local LLM

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.KernelMemory which integrates directly with Microsoft Kernel Memory. Instead of building the RAG pipeline manually, the single call .WithLocalEmbeddings() on KernelMemoryBuilder handles embedding registration. See Kernel Memory Integration for details.

Key code pattern (from both samples)

// 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);

What's Next?


Want Deeper Insights? 📚

Dive into embeddings and local AI on multiple platforms: