### Run the Blazor sample application Source: https://github.com/dotnet/smartcomponents/blob/main/README.md Navigate to the sample directory and start the application using the .NET CLI. ```console cd samples/ExampleBlazorApp dotnet run ``` -------------------------------- ### Generate Quantized Embeddings Source: https://github.com/dotnet/smartcomponents/blob/main/docs/local-embeddings.md Examples of generating single embeddings or ranges of embeddings using specific quantization formats. ```cs // To produce a single embedding: var embedding = embedder.Embed(someString); // Or to produce a set of (item, embedding) pairs: var candidates = embedder.EmbedRange(sports, x => x.Name); ``` -------------------------------- ### Define Sport Class Source: https://github.com/dotnet/smartcomponents/blob/main/docs/local-embeddings.md Example class structure for storing objects alongside their corresponding embeddings. ```csharp class Sport { public string Name { get; init; } public EmbeddingF32 Embedding { get; init; } } ``` -------------------------------- ### Clone the repository Source: https://github.com/dotnet/smartcomponents/blob/main/README.md Use these commands to download the source code and navigate into the project directory. ```console git clone https://github.com/dotnet/smartcomponents.git cd smartcomponents ``` -------------------------------- ### Configure Smart Components services Source: https://github.com/dotnet/smartcomponents/blob/main/docs/getting-started-blazor.md Register the necessary services in the application's Program.cs file. ```cs builder.Services.AddSmartComponents(); ``` -------------------------------- ### Implement custom inference backend Source: https://github.com/dotnet/smartcomponents/blob/main/docs/smart-paste.md Use a custom backend implementation by registering it during the Smart Components service configuration. ```cs builder.Services.AddSmartComponents() .WithInferenceBackend(); class MyCustomInferenceBackend : IInferenceBackend { ... } ``` -------------------------------- ### Import Build Targets Source: https://github.com/dotnet/smartcomponents/blob/main/docs/local-embeddings.md Add the required targets to your project file to enable local model acquisition during the build process. ```xml ``` -------------------------------- ### Configure OpenAI or Azure OpenAI Settings Source: https://github.com/dotnet/smartcomponents/blob/main/docs/configure-openai-backend.md JSON configuration structure for connecting to OpenAI or Azure OpenAI services. ```json "SmartComponents": { "ApiKey": "your key here", "DeploymentName": "gpt-3.5-turbo", // Required for Azure OpenAI only. If you're using OpenAI, remove the following line. "Endpoint": "https://YOUR_ACCOUNT.openai.azure.com/" } ``` -------------------------------- ### Configure Self-Hosted Endpoint Settings Source: https://github.com/dotnet/smartcomponents/blob/main/docs/configure-openai-backend.md JSON configuration structure for connecting to self-hosted endpoints like Ollama. ```json "SmartComponents": { "SelfHosted": true, "DeploymentName": "mistral:7b", // Or "llama2:13b" etc. "Endpoint": "http://localhost:11434/" } ``` -------------------------------- ### Register Smart Components tag helpers Source: https://github.com/dotnet/smartcomponents/blob/main/docs/getting-started-mvc-razor-pages.md Enable Smart Components tag helpers by adding them to the _ViewImports.cshtml file. ```cshtml @addTagHelper *, SmartComponents.AspNetCore ``` -------------------------------- ### Configure API Endpoint Source: https://github.com/dotnet/smartcomponents/blob/main/docs/smart-combobox.md Register the endpoint in Program.cs to handle Smart ComboBox requests. ```cs var candidates = new[] { "Transport", "Rent", "Payroll", "Party" }; app.MapSmartComboBox("api/accounting-categories", request => candidates); ``` -------------------------------- ### Customize AI Inference Prompt Source: https://github.com/dotnet/smartcomponents/blob/main/docs/smart-textarea.md Override the default prompt generation by subclassing SmartTextAreaInference and registering it as a singleton service. ```csharp class MySmartTextAreaInference : SmartTextAreaInference { public override ChatParameters BuildPrompt( SmartTextAreaConfig config, string textBefore, string textAfter) { var prompt = base.BuildPrompt(config, textBefore, textAfter); prompt.Messages!.Add(new(ChatMessageRole.System, "The suggestions must ALWAYS BE IN ALL CAPS.")); prompt.Temperature = 0.5f; // Less deterministic, more creative (default = 0) return prompt; } } ``` ```csharp builder.Services.AddSingleton(); ``` -------------------------------- ### Prepare Sport Data Source: https://github.com/dotnet/smartcomponents/blob/main/docs/local-embeddings.md Generate an array of Sport objects with pre-computed embeddings. ```csharp var sportNames = new[] { "Soccer", "Tennis", "Swimming", "Horse riding", "Golf", "Gymnastics" }; var sports = sportNames.Select(name => new Sport { Name = name, Embedding = embedder.Embed(name) }).ToArray(); ``` -------------------------------- ### Configure Smart Textarea UI via Attributes Source: https://github.com/dotnet/smartcomponents/blob/main/docs/smart-textarea.md Use the data-inline-suggestions attribute to force either inline or overlay suggestion styles regardless of device type. ```html ``` ```html ``` -------------------------------- ### Initialize SemanticTextMemory with LocalEmbedder Source: https://github.com/dotnet/smartcomponents/blob/main/docs/local-embeddings.md Instantiate a LocalEmbedder and pass it to the SemanticTextMemory constructor to enable local embedding generation. ```cs var storage = new VolatileMemoryStore(); // Requires a reference to Microsoft.SemanticKernel.Plugins.Memory using var embedder = new LocalEmbedder(); var semanticTextMemory = new SemanticTextMemory(storage, embedder); // ... and now use semanticTextMemory to store and search for items ``` -------------------------------- ### Register OpenAI Inference Backend in Program.cs Source: https://github.com/dotnet/smartcomponents/blob/main/docs/configure-openai-backend.md Registers the OpenAI inference backend in the .NET dependency injection container. ```cs builder.Services.AddSmartComponents() .WithInferenceBackend(); ``` -------------------------------- ### Compute String Embeddings Source: https://github.com/dotnet/smartcomponents/blob/main/docs/local-embeddings.md Initialize the LocalEmbedder and generate vector embeddings for input strings. ```csharp using var embedder = new LocalEmbedder(); var cat = embedder.Embed("Cats can be blue"); var dog = embedder.Embed("Dogs can be red"); var snooker = embedder.Embed("Snooker world champion Stephen Hendry"); ``` -------------------------------- ### Perform similarity search on database entities Source: https://github.com/dotnet/smartcomponents/blob/main/docs/local-embeddings.md Load a subset of entities from the database and use LocalEmbedder to find the closest matches. ```cs using var dbContext = new MyDbContext(); // Load whatever subset of the data you want to consider // No need to fetch all the columns - only need ID/embedding pairs var currentUserDocs = await dbContext.Documents .Where(x => x.OwnerId == currentUserId) .Select(x => new { x.DocumentId, x.EmbeddingI8Buffer }) .ToListAsync(); // Perform the similarity search int[] matchingDocIds = LocalEmbedder.FindClosest( embedder.Embed(searchText), currentUserDocs.Select(x => (x.DocumentId, new EmbeddingI8(x.EmbeddingI8Buffer))), maxResults: 5); // Load the complete entities for the matching documents var matchingDocs = await dbContext.Documents .Where(x => matchingDocIds.Contains(x.DocumentId)) .ToDictionaryAsync(x => x.DocumentId); var matchingDocsInOrder = matchingDocIds.Select(x => matchingDocs[x]); ``` -------------------------------- ### Rendered HTML Structure Source: https://github.com/dotnet/smartcomponents/blob/main/docs/smart-combobox.md The runtime HTML structure of the Smart ComboBox input and its associated suggestion dropdown element. ```html
Suggestion 1/div>
Suggestion 2 (selected)
Suggestion 3
``` -------------------------------- ### Configuring Maximum Suggestions Source: https://github.com/dotnet/smartcomponents/blob/main/docs/smart-combobox.md Set the maximum number of suggestions displayed by the component. ```html ``` ```html ``` -------------------------------- ### Annotate form fields for AI inference Source: https://github.com/dotnet/smartcomponents/blob/main/docs/smart-paste.md Use the data-smartpaste-description attribute to provide specific instructions to the language model for individual fields. ```html ``` -------------------------------- ### Configure custom embedding model in .csproj Source: https://github.com/dotnet/smartcomponents/blob/main/docs/local-embeddings.md Specify the ONNX model URL and vocabulary file URL within a PropertyGroup in your .csproj file to override the default model. ```xml https://huggingface.co/TaylorAI/gte-tiny/resolve/main/onnx/model_quantized.onnx https://huggingface.co/TaylorAI/gte-tiny/resolve/main/vocab.txt ``` -------------------------------- ### Perform Similarity Search Source: https://github.com/dotnet/smartcomponents/blob/main/docs/local-embeddings.md Find the closest matches for a target string using the FindClosest method. ```csharp var candidates = sports.Select(a => (a, a.Embedding)); var target = embedder.Embed("ball game"); Sport[] closest = LocalEmbedder.FindClosest(target, candidates, maxResults: 3); // Displays: Soccer, Golf, Tennis Console.WriteLine(string.Join(", ", closest.Select(x => x.Name))); ``` -------------------------------- ### Configure SmartTextArea in Blazor Source: https://github.com/dotnet/smartcomponents/blob/main/docs/smart-textarea.md Use the SmartTextArea component in a Blazor file with bound values for text, role, and phrases. ```razor @code { string? text; string userRole = "Staff at a wild-west themed restaurant called 'The Wild Brunch', replying to a booking enquiry"; string[] userPhrases = [ "Yee-haw!", "So you wanna mosey on down for a bite?", "Why sure, we can cook you up somethin' special", "We're open everyday except Tuesdays (that's when we're at the rodeo)", "Sorry pardner, even if you're the sherrif, we gotta stick to our policy!", "Can I book you in for NEED_INFO", "How can I help you, kind stranger?", "Our website is at https://wildbrunch.example.com/" ]; } ``` -------------------------------- ### Configure smart-textarea in MVC/Razor Pages Source: https://github.com/dotnet/smartcomponents/blob/main/docs/smart-textarea.md Use the smart-textarea tag helper in MVC or Razor Pages with server-side variables for role and phrases. ```cshtml @{ ViewData["Title"] = "Home Page"; string userRole = "Maintainer of this open-source project replying to GitHub issues"; string[] userPhrases = [ "Thankyou for contacting us.", "To investigate, we'll need a repro as a public Git repo.", "Could you please post a screenshot of NEED_INFO", "This sounds like a usage question. This issue tracker is intended for bugs and feature proposals. Unfortunately we don't have capacity to answer general usage questions and would recommend StackOverflow for a faster response.", "We don't accept ZIP files as repros.", ]; } ``` -------------------------------- ### Style the Smart Paste button with CSS Source: https://github.com/dotnet/smartcomponents/blob/main/docs/smart-paste.md Apply custom styles using the default class or the disabled state during server processing. ```css /* Applies to all smart paste buttons all the time */ .smart-paste-button { /* your styles here */ } /* Applies to smart paste buttons while they are waiting for a server response */ .smart-paste-button:disabled { /* your styles here */ } ``` -------------------------------- ### Configuring Similarity Threshold Source: https://github.com/dotnet/smartcomponents/blob/main/docs/smart-combobox.md Adjust the similarity threshold to filter suggestion matches based on input text. ```html ``` ```html ``` -------------------------------- ### Customize AI inference prompt Source: https://github.com/dotnet/smartcomponents/blob/main/docs/smart-paste.md Register a custom subclass of SmartPasteInference to modify the system prompt and model parameters. ```cs class MySmartPasteInference : SmartPasteInference { public override ChatParameters BuildPrompt(SmartPasteRequestData data) { var prompt = base.BuildPrompt(data); prompt.Messages!.Add(new ChatMessage(ChatMessageRole.System, "All form field values must be in ALL CAPS")); prompt.Temperature = 0.5f; // Less deterministic, more creative return prompt; } } ``` ```cs builder.Services.AddSingleton(); ``` -------------------------------- ### Implement Semantic Matching Source: https://github.com/dotnet/smartcomponents/blob/main/docs/smart-combobox.md Use the LocalEmbedder service to perform semantic matching within the MapSmartComboBox handler. ```cs // Compute the embeddings once up front var embedder = app.Services.GetRequiredService(); var categories = embedder.EmbedRange(new[] { "Groceries", "Utilities", "Rent", "Mortgage", "Car Payment", "Car Insurance", "Health Insurance", "Life Insurance", "Home Insurance", "Gas", "Public Transportation", "Dining Out", "Entertainment", "Travel", "Clothing", "Electronics", "Home Improvement", "Gifts", "Charity", "Education", "Childcare", "Pet Care", "Other" }); app.MapSmartComboBox("api/accounting-categories", request => embedder.FindClosest(request.Query, categories)); ``` -------------------------------- ### Persist and load embeddings using file storage Source: https://github.com/dotnet/smartcomponents/blob/main/docs/local-embeddings.md Access the raw memory of an embedding via the Buffer property to save it to disk and reconstruct it later. ```cs // Normally you'd store embeddings in a database, not a file on disk, // but for simplicity let's use a file var originalEmbedding = embedder.Embed("The chickens are here to see you"); using (var file = File.OpenWrite("somefile")) { await file.WriteAsync(originalEmbedding.Buffer); } // Now load it back from disk. Be sure to use the same embedding type. var loadedBuffer = File.ReadAllBytes("somefile"); var loadedEmbedding = new EmbeddingF32(loadedBuffer); // Displays "1" (the embeddings are identical) Console.WriteLine(originalEmbedding.Similarity(loadedEmbedding)); ``` -------------------------------- ### Register Local Embedder Service Source: https://github.com/dotnet/smartcomponents/blob/main/docs/smart-combobox.md Register the LocalEmbedder service in the dependency injection container. ```cs builder.Services.AddSingleton(); ``` -------------------------------- ### Apply Scoped CSS Source: https://github.com/dotnet/smartcomponents/blob/main/docs/smart-textarea.md Use the ::deep pseudoselector in scoped CSS files to target the rendered textarea. ```css ::deep .my-textarea { /* ... */ } ``` -------------------------------- ### Add Smart ComboBox in MVC/Razor Pages Source: https://github.com/dotnet/smartcomponents/blob/main/docs/smart-combobox.md Use the smart-combobox tag in a CSHTML file with the required url attribute. ```cshtml ``` -------------------------------- ### Styling with Scoped CSS Source: https://github.com/dotnet/smartcomponents/blob/main/docs/smart-combobox.md Use the ::deep pseudoselector to target suggestion classes when using scoped CSS files. ```css ::deep .smartcombobox-suggestions { /* ... */ } ``` -------------------------------- ### Find closest matches with Local Embeddings Source: https://github.com/dotnet/smartcomponents/blob/main/README.md Identify the top N closest semantic matches from a collection of candidates for a given input string. ```csharp // Find closest matches to "ball game" var candidates = embedder.EmbedRange(["Soccer", "Tennis", "Swimming", "Horse riding", "Golf", "Gymnastics"]); var closest = LocalEmbedder.FindClosest( embedder.Embed("ball game"), candidates, maxResults: 3); Console.WriteLine(string.Join(", ", closest)); // "Soccer, Golf, Tennis" ``` -------------------------------- ### Style Smart Paste button with scoped CSS Source: https://github.com/dotnet/smartcomponents/blob/main/docs/smart-paste.md Use the ::deep pseudoselector to target the button when using scoped CSS files. ```css ::deep .smart-paste-button { /* ... */ } ::deep .smart-paste-button:disabled { /* ... */ } ``` -------------------------------- ### Style Smart TextArea Source: https://github.com/dotnet/smartcomponents/blob/main/docs/smart-textarea.md Apply standard HTML attributes and CSS classes to the rendered textarea element. ```razor ``` ```cshtml ``` -------------------------------- ### Add Smart TextArea in MVC / Razor Pages Source: https://github.com/dotnet/smartcomponents/blob/main/docs/smart-textarea.md Use the smart-textarea tag in a .cshtml file with the required user-role attribute. ```cshtml ``` -------------------------------- ### Add Smart TextArea in Blazor Source: https://github.com/dotnet/smartcomponents/blob/main/docs/smart-textarea.md Use the SmartTextArea component in a .razor file with required UserRole and @bind-Value attributes. ```razor @page "/" @using SmartComponents @code { string? text; // Optionally, set an initial value here } ``` -------------------------------- ### Evaluate semantic similarity with Local Embeddings Source: https://github.com/dotnet/smartcomponents/blob/main/README.md Calculate the semantic similarity between a search term and multiple text candidates using the local embedder. ```csharp var article1 = embedder.Embed("Vacation allowance policy"); var article2 = embedder.Embed("Returning a company vehicle"); var article3 = embedder.Embed("How to get your boss fired"); var searchTerm = embedder.Embed("car"); Console.WriteLine(searchTerm.Similarity(article1)); // Outputs: 0.41 Console.WriteLine(searchTerm.Similarity(article2)); // Outputs: 0.70 Console.WriteLine(searchTerm.Similarity(article3)); // Outputs: 0.38 ``` -------------------------------- ### Use EmbedRange for Candidates Source: https://github.com/dotnet/smartcomponents/blob/main/docs/local-embeddings.md Use EmbedRange as a shorthand to generate candidate tuples from a collection of objects. ```csharp var candidates = embedder.EmbedRange(sports, x => x.Name); Sport[] closest = LocalEmbedder.FindClosest( embedder.Embed("ball game"), candidates, maxResults: 3); ``` -------------------------------- ### Populate an embedding buffer Source: https://github.com/dotnet/smartcomponents/blob/main/docs/local-embeddings.md Convert an embedding to a byte array for storage using the ToArray method. ```cs var doc = new Document { // ... set other properties here ... EmbeddingI8Buffer = embedder.Embed(title).Buffer.ToArray() }; ``` -------------------------------- ### Add Smart ComboBox in Blazor Source: https://github.com/dotnet/smartcomponents/blob/main/docs/smart-combobox.md Use the SmartComboBox component within a Razor file, ensuring the Url and @bind-Value attributes are provided. ```razor @code { string? text; // Optionally, set a default value here } ``` -------------------------------- ### Define an entity with an embedding buffer Source: https://github.com/dotnet/smartcomponents/blob/main/docs/local-embeddings.md Store raw embedding data in an Entity Framework model using a byte array property. ```cs public class Document { public int DocumentId { get; set; } public int OwnerId { get; set; } public required string Title { get; set; } public required string Body { get; set; } // It's helpful to use the property name to keep track of which // format of embedding is being used public required byte[] EmbeddingI8Buffer { get; set; } } ``` -------------------------------- ### Add SmartPasteButton to a Blazor form Source: https://github.com/dotnet/smartcomponents/blob/main/docs/smart-paste.md Integrate the SmartPasteButton component within a standard Blazor form to enable intelligent clipboard data extraction. ```razor @page "/" @using SmartComponents

Name:

Address line 1:

City:

Zip/postal code:

@code { string? name, addr1, city, zip; } ``` -------------------------------- ### Assess Semantic Similarity Source: https://github.com/dotnet/smartcomponents/blob/main/docs/local-embeddings.md Calculate the similarity score between two embeddings using the Similarity method. ```csharp var kitten = embedder.Embed("Kittens!!!"); Console.WriteLine(kitten.Similarity(kitten)); // 1.00 Console.WriteLine(kitten.Similarity(cat)); // 0.65 Console.WriteLine(kitten.Similarity(dog)); // 0.53 Console.WriteLine(kitten.Similarity(snooker)); // 0.37 ``` -------------------------------- ### Customize Smart Paste button label Source: https://github.com/dotnet/smartcomponents/blob/main/docs/smart-paste.md Provide child content to the button tag to override the default label with custom text or icons. ```razor Smart paste, baby! ``` ```cshtml Smart paste, baby! ``` -------------------------------- ### Render custom icon in Smart Paste button Source: https://github.com/dotnet/smartcomponents/blob/main/docs/smart-paste.md Supply custom child content to the button component to override the default icon. ```razor ... Click me now! ``` ```html ... Click me now! ``` -------------------------------- ### Add Smart Paste button to MVC/Razor Pages form Source: https://github.com/dotnet/smartcomponents/blob/main/docs/smart-paste.md Insert the smart-paste-button tag within a form to enable automatic field population from the clipboard. ```cshtml

Name:

Address line 1:

City:

Zip/postal code:

``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.