.NET Smart Components

repository·main·Indexed 19 days ago

https://github.com/dotnet/smartcomponents

A library of prebuilt, AI-powered UI components for Blazor and MVC/Razor Pages applications targeting .NET 6 or later. Features include Smart Paste for automated form filling, Smart TextArea for intelligent autocompletion, and Smart ComboBox for semantic suggestions. It also provides Local Embeddings for server-side semantic similarity and matching without requiring external AI services. Supports OpenAI, Azure OpenAI, and self-hosted OpenAI-compatible backends like Ollama.

Tokens
13.1K
Snippets
43
Records
56
Agent score
65%

What's inside .NET Smart Components

  1. Overview of .NET Smart Components

    main

    .NET Smart Components provides prebuilt, end-to-end AI-powered UI features for .NET applications. These components are designed to be dropped into existing user interfaces to improve productivity and user experience without requiring deep expertise in machine learning or prompt engineering.

    Supported UI frameworks include:

    • Blazor
    • MVC / Razor Pages

    Targeting .NET 6 or later.

  2. Use Smart Paste to automate form filling

    main

    Smart Paste is a UI component that provides a button to automatically fill out forms using data from the user's clipboard. It allows users to ingest data from external sources into your web application's forms without manual re-typing.

    Refer to the Smart Paste docs for detailed implementation instructions.

  3. Customize Smart TextArea suggestions with UserRole and UserPhrases

    main

    You can influence the AI's suggestions by providing context through UserRole and UserPhrases:

    • UserRole (or user-role): A string describing who is typing and why (e.g., "An HR agent replying to enquiries").
    • UserPhrases (or user-phrases): An array of strings (string[]) containing preferred tones, common phrases, policies, or URLs.

    Preventing Hallucinations with NEED_INFO: To prevent the AI from inventing specific data (like a specific price or ID), use the special token NEED_INFO in your phrases. The AI will stop the suggestion at that token, allowing the user to provide the actual value.

    <SmartTextArea @bind-Value="@text" UserRole="@userRole" UserPhrases="@userPhrases" />
    
    @code {
        string? text;
        string userRole = "Staff at a wild-west themed restaurant";
        string[] userPhrases = [
            "Yee-haw!",
            "Can I book you in for NEED_INFO",
            "Our website is at https://wildbrunch.example.com/"
        ];
    }
  4. Use Smart TextArea for intelligent autocompletion

    main
    Smart TextArea is an intelligent upgrade to the standard HTML <textarea>. It can be configured to autocomplete whole sentences based on your specific tone, policies, or URLs, helping users type faster and reducing errors.
  5. Choose an embedding format (Quantization)

    main

    You can reduce memory usage and increase search speed by using quantized embedding types. Specify the desired format as a generic parameter to Embed or EmbedRange.

    Supported Formats:

    TypeSize (bytes)Similarity MetricDescription
    EmbeddingF321536CosineRaw, unquantized float data. Maximum accuracy.
    EmbeddingI8388Cosinesbyte components + scale factor. High accuracy, significantly lower storage.
    EmbeddingI148HammingSingle-bit components. Massive storage reduction, moderate accuracy loss.

    Note: You can only compare embeddings of the same type.

    // Single embedding in I1 format
    var embedding = embedder.Embed<EmbeddingI1>(someString);
    
    // Batch embeddings in I1 format
    var candidates = embedder.EmbedRange<Sport, EmbeddingI1>(sports, x => x.Name);
  6. Use Local Embeddings for semantic similarity and matching

    main

    Local Embeddings is a general-purpose capability that runs entirely locally on your server's CPU. It does not require an external AI service. It allows you to:

    1. Compute the semantic similarity between two natural language strings.
    2. Find the closest matches from a set of candidate strings.

    This is useful for building custom features like semantic search or Retrieval-Augmented Generation (RAG).

    // Example: evaluating the semantic similarity between two strings
    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
    
    // Example: finding closest matches
    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"
  7. Use Smart ComboBox for semantic suggestions

    main
    Smart ComboBox upgrades the traditional combobox by providing suggestions based on semantic matching rather than just text matching. This helps users find relevant options even if they don't type the exact term.
  8. Style the Smart TextArea

    main

    The SmartTextArea renders as a standard HTML <textarea>. You can apply any CSS classes or HTML attributes (like class, placeholder, rows, or cols) directly to the component.

    Note for Scoped CSS: If you are using scoped CSS (e.g., .razor.css or .cshtml.css), you must use the ::deep pseudoselector to target the textarea because it is rendered in a child context.

    /* In a scoped CSS file */
    ::deep .my-textarea { 
        /* your styles */ 
    }
  9. Setup SmartComponents.LocalEmbeddings

    main

    To use SmartComponents.LocalEmbeddings in your application, you must add the project to your solution and reference it. To ensure the required ONNX embeddings model is automatically acquired during your build process, import the .targets file into your project file (.csproj).

    <Import Project="<REPO PATH>\src\SmartComponents.LocalEmbeddings\build\SmartComponents.LocalEmbeddings.targets" />
  10. Add Smart TextArea in Blazor

    main

    To use SmartTextArea in a Blazor application, ensure you have completed the initial Smart Component installation and configured an OpenAI backend. In your .razor file, add the <SmartTextArea> component. The UserRole and @bind-Value attributes are required. It integrates with Blazor's binding, forms, and validation systems similarly to InputTextArea.

    @page "/"
    @using SmartComponents
    
    <SmartTextArea @bind-Value="@text" UserRole="Generic professional" />
    
    @code {
        string? text; // Optionally, set an initial value here
    }
  11. Annotate form fields for better Smart Paste accuracy

    main

    Smart Paste automatically infers field meanings from <label>, name attributes, or nearby text. To improve accuracy or provide specific constraints to the AI, use the data-smartpaste-description attribute on <input>, <select>, or <textarea> elements.

    <!-- Provide specific format instructions -->
    <input data-smartpaste-description="The user's vehicle registration number which must be in the form XYZ-123" />
    
    <!-- Provide content constraints -->
    <textarea data-smartpaste-description="The job description which must start with JOB TITLE in all caps, and then contain one paragraph"></textarea>
    
    <!-- Provide logic for boolean/checkbox fields -->
    <input type="checkbox" data-smartpaste-description="True if the product description indicates this is for children, otherwise False" />
  12. Customize the Smart Paste button label and icon

    main

    You can customize the text label or the icon of the Smart Paste button by providing child content.

    • Text Label: Pass the desired text as child content to replace the default label.
    • Default Icon: Use the DefaultIcon (Blazor) or default-icon (MVC/Razor Pages) attribute to render the standard smart paste SVG icon.
    • Custom Icon: Instead of using the default icon attribute, pass your own <svg> or icon element as child content.
    // Custom text label in Blazor
    <SmartPasteButton>Smart paste, baby!</SmartPasteButton>
    
    // Custom icon and text in Blazor
    <SmartPasteButton>
        <svg>...</svg>
        Click me now!
    </SmartPasteButton>