Claim Free Community License

Add Gen AI Capabilities to Your .NET App in Minutes

Unlock the full potential of Generative AI in your .NET applications with LM-Kit.NET.

Our free trial provides unlimited access to all featuresno time limits, no registration required. Start experimenting today and seamlessly integrate AI capabilities into your .NET ecosystem.

🔥 Discover Our Free Community Edition 🔥

Experience full, unrestricted access to LM-Kit.NET’s powerful AI capabilities at no cost. Tailored for developers, startups, and open-source enthusiasts, our Community Edition empowers you to build, test, and deploy state-of-the-art Generative AI solutions in your .NET apps without any licensing fees.

Full-Featured Cost-Free Community-Driver

Prerequisites

Before getting started, ensure your environment meets the following requirements:

Unlimited, No Signup Trial

Made by developers for developers! Our trial gate lets you explore everything without time limits or the need to share personal data. Access all features and test our platform freely.

Installing LM-Kit.NET via NuGet

Follow these simple steps to install the LM-Kit.NET SDK using NuGet Package Manager:

Option 1: Install via Console

  • Open the NuGet Package Manager Console in Visual Studio.
  • Run the following command:
				
					Install-Package LM-Kit.NET
				
			

Option 2: Install via UI

  • Right-click on your project in the Solution Explorer.
  • Select Manage NuGet Packages….
  • Search for LM-Kit.NET in the Browse tab.
  • Click Install to add the package to your project.

Optional: Enable CUDA Support (GPU Acceleration)

For enhanced performance using Nvidia GPU acceleration, install the appropriate CUDA backend:

For Windows:
				
					Install-Package LM-Kit.NET.Backend.Cuda13.Windows

				
			
For Linux:
				
					Install-Package LM-Kit.NET.Backend.Cuda12.Linux

				
			

Example Use Cases

				
					using LMKit.Model;
using LMKit.TextGeneration;

namespace YourNamespace
{
    class Program
    {
        static void Main(string[] args)
        {
            // Load the model
            var model = LM.LoadFromModelID("gemma3:4b");

            // Create a multi-turn conversation instance
            var chat = new MultiTurnConversation(model);

            // Submit a prompt and get the response.
            var response = chat.Submit("Why are cats so cute?");

            // Output the generated text
            Console.WriteLine("Response: " + response.Completion);
        }
    }
}
				
			
				
					using LMKit.Extraction;
using LMKit.Model;
using System;
using System.Collections.Generic;

// Initialize the language model 
var model = LM.LoadFromModelID("gemma3:4b");

// Create an instance of TextExtraction using the LLM
TextExtraction textExtraction = new TextExtraction(model);

// Define the elements to extract
textExtraction.Elements = new List<TextExtractionElement>
{
    new TextExtractionElement("Name", ElementType.String, "The person's full name"),
    new TextExtractionElement("Age", ElementType.Integer, "The person's age"),
    new TextExtractionElement("Birth Date", ElementType.Date, "The person's date of birth.")
};

// Set the content to extract data from
textExtraction.SetContent("Jane Smith, aged 28, born on 5 Nov of the year 1981");

// Perform the extraction synchronously
TextExtractionResult result = textExtraction.Parse();

// Access the extracted items
foreach (var item in result.Elements)
{
    Console.WriteLine($"{item.TextExtractionElement.Name}: {item.Value}");
}

				
			
				
					using LMKit.Extraction;
using LMKit.Model;
using System;
using System.Collections.Generic;

    // Initialize the vision language model 
    var clm = LM.LoadFromModelID("minicpm-o");

    // Create an instance of TextExtraction using the LLM
    var textExtraction = new TextExtraction(vlm);

    // Define the elements to extract
    textExtraction.Elements = new List<TextExtractionElement>
{
    new TextExtractionElement("Name", ElementType.String, "The person's full name"),
    new TextExtractionElement("Age", ElementType.Integer, "The person's age"),
    new TextExtractionElement("Birth Date", ElementType.Date, "The person's date of birth.")
};

    // Set the content to extract data from
    textExtraction.SetContent(new Attachment("d:\\id-card.jpeg"));

    // Perform the extraction synchronously
    TextExtractionResult result = textExtraction.Parse();

    // Access the extracted items
    foreach (var item in result.Elements)
    {
        Console.WriteLine($"{item.TextExtractionElement.Name}: {item.Value}");
    }

				
			
				
					using LMKit.TextGeneration;
using LMKit.Model;
using System;
using System.Collections.Generic;

 // Load the model
 var model = LM.LoadFromModelID("minicpm-o");

 // Create a multi-turn conversation instance
 var chat = new MultiTurnConversation(model);

 // Submit a prompt and get the response.
 var response = await chat.SubmitAsync(new Prompt("describe this image", new Attachment("d:\\image.webp")));

 // Output the generated text
 Console.WriteLine("Response: " + response.Completion);
				
			
				
					using LMKit.TextGeneration;

namespace YourNamespace
{
    class Program
    {
        static void Main(string[] args)
        {
            // Load the model
            var model = LM.LoadFromModelID("gemma3:4b");

            // Create a  TextTranslation  instance
            var textTranslation = new LMKit.Translation.TextTranslation(model);
            string text = "Allons boire une bière après le travail !";
            Language detectedLanguage = textTranslation.DetectLanguage(text);

            // Output the detected language
            Console.WriteLine($"Detected Language: {detectedLanguage}");
        }
    }
}
				
			
				
					using LMKit.Media.Audio;
using LMKit.Model;
using LMKit.Speech;

namespace YourNamespace
{
    class Program
    {
        static void Main(string[] args)
        {
            // Instantiate the Whisper model by ID.
            // See the full model catalog at: 
            // https://docs.lm-kit.com/lm-kit-net/guides/getting-started/model-catalog.html
            var model = LM.LoadFromModelID("whisper-large-turbo3");

            // Open the WAV file from disk for analysis
            var wavFile = new WaveFile(@"d:\discussion.wav");

            // Create the speech-to-text engine for streaming transcription and language detection
            var engine = new SpeechToText(model);

            // Detect the primary language spoken in the audio file; returns an ISO language code
            var language = engine.DetectLanguage(wavFile);

            // Output the detected language to the console
            Console.WriteLine($"Detected language: {language}");
        }
    }
}
				
			
				
					using LMKit.Media.Image;
using LMKit.Model;
using LMKit.Translation;

namespace YourNamespace
{
    class Program
    {
        static void Main(string[] args)
        {
            // Instantiate the translation model by ID.
            // See the full model catalog at:
            // https://docs.lm-kit.com/lm-kit-net/guides/getting-started/model-catalog.html
            var model = LM.LoadFromModelID("gemma3:4b");

            // Load a JPEG image from disk into an ImageBuffer in RGB format
            var image = ImageBuffer.LoadAsRGB(@"d:\image.jpeg");

            // Create the text-translation engine using the loaded model
            var engine = new TextTranslation(model);

            // Detect the primary language in the attached image
            var language = engine.DetectLanguage(image);

            // Write the detected language to the console
            Console.WriteLine($"Detected language: {language}");
        }
    }
}
				
			
				
					using LMKit;

namespace YourNamespace
{
    class Program
    {
        static void Main(string[] args)
        {
            // Load the AI model, because language barriers are so last century.
            var model = LM.LoadFromModelID("gemma3:4b");

            // Let the AI handle the translation, because Google Translate can't always save you.
            var translator = new LMKit.Translation.TextTranslation(model);

            // Translate something that sounds more philosophical in French than it probably is.
            string response = translator.Translate("Bonjour, comment vas-tu ? J'ai récemment lu un article fascinant sur l'impact de l'intelligence artificielle sur la littérature moderne. Qu'en penses-tu ?", LMKit.TextGeneration.Language.English);

            // Show off the AI's linguistic finesse with a dash of existential thought.
            Console.WriteLine("Translated version: " + response);
        }
    }
}

				
			
				
					using LMKit;

namespace YourNamespace
{
    class Program
    {
        static void Main(string[] args)
        {
            // Load the model
            var model = new LMKit.Model.LM("https://huggingface.co/lm-kit/lm-kit-sentiment-analysis-2.0-1b-gguf/resolve/main/lm-kit-sentiment-analysis-2.0-1b-q4.gguf?download=true");

            // Create a classifier
            var classifier = new LMKit.TextAnalysis.SentimentAnalysis(model)
            {
                NeutralSupport = true
            };

            // Ask the model for its hot take on our brilliance
            var sentiment = classifier.GetSentimentCategory("LM-Kit is so convenient, it practically runs on sunshine and good karma!");

            // Drumroll, please... the model's about to flatter us
            Console.WriteLine($"Sentiment: {sentiment}"); // Positive! Just like our developer optimism after 10 cups of coffee.
        }
    }
}
				
			
				
					using LMKit;

namespace YourNamespace
{
    class Program
    {
        static void Main(string[] args)
        {
            // Load the model
            var model = new LMKit.Model.LM("https://huggingface.co/lm-kit/phi-3.5-mini-3.8b-instruct-gguf/resolve/main/Phi-3.5-mini-Instruct-Q4_K_M.gguf?download=true");

            // Create a classifier
            var classifier = new LMKit.TextAnalysis.EmotionDetection(model)
            {
                NeutralSupport = true// Because sometimes you just feel "meh"
            };

            // Ask the model for its hot take on our brilliance
            var emotion = classifier.GetEmotionCategory("I just tried to make spaghetti, and somehow ended up with a culinary masterpiece!");

            Console.WriteLine($"Emotion: {emotion}"); 
        }
    }
}
				
			
				
					using LMKit;

namespace YourNamespace
{
    class Program
    {
        static void Main(string[] args)
        {
            // Initialize the LLM model by providing the URL to the model file
            var model = LM.LoadFromModelID("gemma3:4b");

            // Create a text classifier using the loaded model
            var classifier = new LMKit.TextAnalysis.Categorization(model);

            // Define a list of categories that the classifier can choose from
            var categories = new string[]
            {
                "sport", "finance", "technology", "entertainment",
                "health", "education", "science", "travel",
                "lifestyle", "food", "gaming"
            };

            // Input text for classification
            var inputText = "Physical activity helps build strength, endurance, and promotes a sense of camaraderie among participants";

            // Get the most appropriate category for the input text from the list of categories
            int category = classifier.GetBestCategory(categories, inputText);

            // Output the predicted category to the console
            if (category != -1)
            {
                Console.WriteLine($"Category: {categories[category]}");
            }
            else
            {
                Console.WriteLine("No match");
            }
        }
    }
}

				
			
				
					using LMKit;

namespace YourNamespace
{
    class Program
    {
        static void Main(string[] args)
        {
            // Load the model - because we need the brains behind this operation!
            var model = LM.LoadFromModelID("gemma3:4b");

            // Create a TextRewriter instance - turning your casual thoughts into corporate gold.
            var rewriter = new LMKit.TextEnhancement.TextRewriter(model);

            // Submit a prompt and get a more professional response. 
            // Perfect for when you're trying to sound like you have your life together!
            string response = rewriter.Rewrite("I want to apply my candidature to LM-Kit as I would like to work with fancy people",
                                                LMKit.TextEnhancement.TextRewriter.CommunicationStyle.Professional);

            // Output the transformed text - hopefully making you sound like a polished professional, instead of a 'fancy people' fan.
            Console.WriteLine("Here’s a more professional style: " + response);
        }
    }
}

				
			
				
					using LMKit;

namespace YourNamespace
{
    class Program
    {
        static void Main(string[] args)
        {
            // Load the model like it's rocket science.
            var model = LM.LoadFromModelID("gemma3:4b");

            // Call in the grammar rescue squad.
            var corrector = new LMKit.TextEnhancement.TextCorrection(model);

            // Fix the world's weirdest sentence.
            string response = corrector.Correct("My cat don't never flyed to the moon because he too much tired from baking a pizza in the bathtub last Tuesday");

            // Display the miracle correction.
            Console.WriteLine("Corrected version: " + response);
        }
    }
}

				
			
				
					using LMKit.Embeddings;
using LMKit.Model;
using System.Diagnostics;

namespace ConsoleApp
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            var model = LM.LoadFromModelID("embeddinggemma-300m")
            Embedder embedder = new Embedder(model);

            Stopwatch sw = Stopwatch.StartNew();

            string input = "How do I bake a chocolate cake?";
            string[] examples = new string[]
            {
                "How do I bake a chocolate cake?",
                "What is the recipe for chocolate cake?",
                "I want to make a chocolate cake.",
                "Chocolate cake is delicious.",
                "How do I cook pasta?",
                "I need instructions to bake a cake.",
                "Baking requires precise measurements.",
                "I like vanilla ice cream.",
                "The weather is sunny today.",
                "What is the capital of France?",
                "Paris is a beautiful city.",
                "How can I improve my coding skills?",
                "Programming requires practice."
            };

            float[] inputEmbedding = await embedder.GetEmbeddingsAsync(input);
            float[][] exampleEmbeddings = await embedder.GetEmbeddingsAsync(examples);

            sw.Stop();

            Console.WriteLine($"Elapsed (ms): {Math.Round(sw.Elapsed.TotalMilliseconds)} - Similarities:");

            for (int index = 0; index < examples.Length; index++)
            {
                float similarity = Embedder.GetCosineSimilarity(inputEmbedding, exampleEmbeddings[index]);
                Console.WriteLine($"{similarity} {examples[index]}");
            }
        }
    }
}

				
			
				
					using System;
using LMKit.Data;
using LMKit.Embeddings;
using LMKit.Model;
using LMKit.Retrieval;

// 1. Load the pre-trained image embedding model
//    This model converts images into fixed-length float vectors that capture visual features.
var model = LM.LoadFromModelID("nomic-embed-vision");

// 2. Create or reset a local vector database on disk
//    We’ll store image embeddings here for later similarity searches.
//    If the file already exists, overwrite it to start fresh.
const string CollectionPath = @"d:\collection.ds";
var collection = DataSource.CreateFileDataSource(
    path: CollectionPath,
    identifier: "my-image-collection",
    model: model,
    overwrite: true
);

// 3. Instantiate an embedder to compute image vectors
//    The Embedder wraps the model and handles preprocessing (e.g. resizing, normalization).
var embedder = new Embedder(model);

// 4. Compute and store embeddings for several images
//    Each call:
//      a) Loads the image from disk.
//      b) Runs it through the embedding model.
//      c) Inserts the resulting float[] into our collection under a unique key.
collection.Upsert(
    sectionIdentifier: "house1",
    vector: embedder.GetEmbeddings(new Attachment(@"d:\house1.jpg"))
);

collection.Upsert(
    sectionIdentifier: "house2",
    vector: embedder.GetEmbeddings(new Attachment(@"d:\house2.jpg"))
);

collection.Upsert(
    sectionIdentifier: "cat1",
    vector: embedder.GetEmbeddings(new Attachment(@"d:\cat1.jpg"))
);

collection.Upsert(
    sectionIdentifier: "cat2",
    vector: embedder.GetEmbeddings(new Attachment(@"d:\cat2.jpg"))
);

collection.Upsert(
    sectionIdentifier: "dog1",
    vector: embedder.GetEmbeddings(new Attachment(@"d:\dog1.jpg"))
);

collection.Upsert(
    sectionIdentifier: "dog2",
    vector: embedder.GetEmbeddings(new Attachment(@"d:\dog2.jpg"))
);

// 5. Compute the embedding for a new query image
//    We’ll search for the most visually similar stored images.
var queryVector = embedder.GetEmbeddings(new Attachment(@"d:\cat3.webp"));

// 6. Perform the similarity search across our collection
//    VectorSearch.FindMatchingPartitions returns TextPartitions ordered by cosine similarity.
//    We expect "cat1" and "cat2" to be the closest matches.
var similarPartitions = VectorSearch.FindMatchingPartitions(
    dataSources: [collection],
    model: model,
    vector: queryVector
);

// 7. Use the results
//    Each returned partition contains its section identifier (e.g. "cat1")
//    and similarity score—ideal for presenting the top-k closest images.
foreach (var partition in similarPartitions)
{
    Console.WriteLine($"{partition.SectionIdentifier}: score = {partition.Similarity:F4}");
}
				
			
				
					using LMKit;
using LMKit.TextAnalysis;
using System;
using System.IO;

namespace YourNamespace
{
    class Program
    {
        static void Main(string[] args)
        {
            var model = LM.LoadFromModelID("gemma3:4b");

            // Load the text content from a local file
            string testCase = File.ReadAllText("content.txt");

            // Initialize the KeywordExtraction engine with the loaded model
            KeywordExtraction engine = new(model)
            {
                // Set how many keywords to extract
                KeywordCount = 8
            };

            // Extract the keywords from the provided text
            var result = engine.ExtractKeywords(testCase);

            Console.WriteLine("Extracted Keywords:");
            foreach (var keyword in result)
            {
                Console.WriteLine("- " + keyword.Value);
            }
        }
    }
}




				
			
				
					using LMKit;
using LMKit.TextAnalysis;
using System;
using System.IO;

namespace YourNamespace
{
    class Program
    {
        static void Main(string[] args)
        {
            // Load the model (e.g. Gemma3 Vision 4B)
            var model = LM.LoadFromModelID("gemma3:4b");

            // Read the text content from a local file
            string content = File.ReadAllText("content.txt");

            // Initialize the PII extraction engine with the loaded model
            PiiExtraction engine = new(model);

            // Extract PII entities from the text
            var entities = engine.Extract(content);

            Console.WriteLine("Detected PII Entities:");
            foreach (var entity in entities)
            {
                // entity.EntityDefinition.Label is the type (e.g., "PERSON", "EMAIL")
                // entity.Value is the text match
                // entity.Confidence is the model’s confidence score
                Console.WriteLine($"- {entity.EntityDefinition.Label}: \"{entity.Value}\" (confidence={entity.Confidence:0.##})");
            }
        }
    }
}

				
			
				
					using LMKit;
using LMKit.TextAnalysis;
using System;
using System.IO;

namespace YourNamespace
{
    class Program
    {
        static void Main(string[] args)
        {
            // Load your preferred model (e.g. Gemma 3 Vision 4B)
            LM model = LM.LoadFromModelID("gemma3:4b");

            // Read the text to analyze from a file
            string content = File.ReadAllText("content.txt");

            // Initialize the Named Entity Recognition engine
            NamedEntityRecognition ner = new(model);

            // Recognize entities in the text
            var entities = ner.Recognize(content);

            Console.WriteLine("Extracted Named Entities:");
            foreach (var entity in entities)
            {
                // EntityDefinition.Label is the category (e.g. "PERSON", "ORG", "LOCATION")
                // entity.Value is the matched text
                // entity.Confidence is the confidence score
                Console.WriteLine($"- {entity.EntityDefinition.Label}: \"{entity.Value}\" (confidence={entity.Confidence:0.##})");
            }
        }
    }
}

				
			
				
					using LMKit;

namespace YourNamespace
{
    class Program
    {
        static void Main(string[] args)
        {
            // Load the language model from the catalog.
            var model = LM.LoadFromModelID("gemma3:4b");

            // Initialize the summarizer with the desired parameters.
            // Here we enable title generation, content summarization, and set a maximum length for the summary.
            var summarizer = new LMKit.TextGeneration.Summarizer(model)
            {
                GenerateTitle = true,
                GenerateContent = true,
                MaxContentWords = 300
            };

            // Read the content from the file and generate a summary using the model.
            var result = summarizer.Summarize(File.ReadAllText("blog-article.txt"));

            // Display the generated title and summary to the console.
            Console.WriteLine("Title: " + result.Title);
            Console.WriteLine("Summary: " + result.Content);
        }
    }
}

				
			
				
					using LMKit;
using LMKit.Configuration;

namespace YourNamespace
{
    class Program
    {
        static void Main(string[] args)
        {
            // Enable KV (key-value) cache recycling 
            LMKit.GlobalConfiguration.EnableKVCacheRecycling = true;
            
            // Disable model caching 
            LMKit.GlobalConfiguration.EnableModelCache = false;
            
            // Enable token healing 
            LMKit.GlobalConfiguration.EnableTokenHealing = true;
            
            // Discover more parameters in the LMKit.GlobalConfiguration static class.

            // Code to use LM-Kit.NET goes here
        }
    }
}

				
			
				
					using LMKit.Media.Audio;
using LMKit.Model;
using LMKit.Speech;

namespace YourNamespace
{
    class Program
    {
        static void Main(string[] args)
        {
            // Instantiate the Whisper model by ID.
            // See the full model catalog at: 
            // https://docs.lm-kit.com/lm-kit-net/guides/getting-started/model-catalog.html
            var model = LM.LoadFromModelID("whisper-large-turbo3");

            // Open the WAV file from disk for transcription
            var wavFile = new WaveFile(@"d:\discussion.wav");

            // Create the speech-to-text engine for streaming, multi-turn transcription
            var engine = new SpeechToText(model);

            // Print each segment of transcription as it’s received (e.g., real-time display)
            engine.OnNewSegment += (sender, e) =>
                Console.WriteLine(e.Segment);

            // Transcribe the entire WAV file; returns the full transcription information
            var transcription = engine.Transcribe(wavFile);

            // TODO: handle transcription results (e.g., save to file or process further)
        }
    }
}
				
			
				
					using LMKit.Model;
using LMKit.TextGeneration;
using LMKit.TextGeneration.Chat;
using LMKit.Agents.Tools;
using System;

// Initialize the language model
var model = LM.LoadFromModelID("qwen3:4b");

// Create a multi-turn conversation with tool support
MultiTurnConversation chat = new MultiTurnConversation(model);

// Register tools using the LMFunctionToolBinder
LMFunctionToolBinder toolBinder = new LMFunctionToolBinder();
toolBinder.ImportFunctions(typeof(WeatherTools));
chat.Tools = toolBinder.Tools;
chat.ToolPolicy = new ToolCallPolicy(ToolChoice.Auto);

// Optional: Monitor tool invocations
chat.AfterToolInvocation += (sender, e) =>
{
    Console.WriteLine($"Tool called: {e.ToolCall.Name}");
};

// Submit a prompt that will trigger tool usage
var response = chat.Submit("What's the current weather in Paris?");

Console.WriteLine(response.Content);

// Tool definitions using LMFunctionAttribute
public static class WeatherTools
{
    [LMFunction("GetCurrentWeather", "Gets the current weather for a specified city")]
    public static string GetCurrentWeather(
        [LMFunctionParameter("The name of the city")] string city,
        [LMFunctionParameter("Temperature unit: 'celsius' or 'fahrenheit'")] string unit = "celsius")
    {
        // In a real application, this would call a weather API
        return $"Weather in {city}: 18°{(unit == "celsius" ? "C" : "F")}, partly cloudy";
    }
}
				
			
				
					using LMKit.Model;
using LMKit.Retrieval;
using LMKit.TextGeneration;
using LMKit.TextGeneration.Chat;
using System;

// Load the embedding model for vector search
var embeddingModel = LM.LoadFromModelID("embeddinggemma-300m");

// Load the language model for response generation
var chatModel = LM.LoadFromModelID("qwen3:4b");

// Create the RAG engine with both models
RagEngine ragEngine = new RagEngine(embeddingModel, chatModel);

// Create an in-memory data source for storing document chunks
DataSource dataSource = DataSource.CreateInMemoryDataSource();
ragEngine.AddDataSource(dataSource);

// Import text content into the RAG system
ragEngine.ImportText(
    "LM-Kit.NET is a comprehensive SDK for .NET developers that enables local AI inference " +
    "with zero cloud dependencies. It supports text generation, embeddings, RAG, tool calling, " +
    "vision models, speech-to-text, and many other AI capabilities. The SDK emphasizes privacy " +
    "and data sovereignty by running everything on-device.",
    section: "product-overview"
);

ragEngine.ImportText(
    "LM-Kit.NET supports multiple backends including CPU, CUDA for NVIDIA GPUs, and Vulkan " +
    "for cross-platform GPU acceleration. It runs on Windows, Linux, and macOS, with support " +
    "for both x64 and ARM64 architectures.",
    section: "platforms"
);

ragEngine.ImportText(
    "The tool calling feature allows AI models to invoke external functions during conversations. " +
    "Developers can define tools using the LMFunctionAttribute and register them with the " +
    "LMFunctionToolBinder. This enables building sophisticated AI agents that can interact " +
    "with APIs, databases, and other services.",
    section: "tool-calling"
);

// Query the RAG system with a user question
string question = "What platforms does LM-Kit support?";

// Find relevant document partitions
var matches = ragEngine.FindMatchingPartitions(question, maxPartitionCount: 3);

Console.WriteLine("Retrieved passages:");
foreach (var match in matches)
{
    Console.WriteLine($"  - Score: {match.Similarity:F3} | {match.Content.Substring(0, Math.Min(80, match.Content.Length))}...");
}

// Generate a response using retrieved context
var response = ragEngine.QueryPartitions(question);

Console.WriteLine($"\nQuestion: {question}");
Console.WriteLine($"Answer: {response.Content}");
				
			
				
					using LMKit.Model;
using LMKit.Retrieval;
using System;

// Load the embedding model for document indexing
var embeddingModel = LM.LoadFromModelID("embeddinggemma-300m");

// Load the language model for response generation
var chatModel = LM.LoadFromModelID("qwen3:4b");

// Create a PdfChat instance for conversational document Q&A
PdfChat pdfChat = new PdfChat(embeddingModel, chatModel);

// Optional: Monitor document import progress
pdfChat.DocumentImportProgress += (sender, e) =>
{
    Console.WriteLine($"Importing: {e.Phase} - {e.ProgressPercentage:F0}%");
};

// Optional: Monitor when relevant passages are retrieved
pdfChat.PassageRetrievalCompleted += (sender, e) =>
{
    Console.WriteLine($"Retrieved {e.Partitions.Count} relevant passages");
};

// Import a PDF document
DocumentIndexingResult indexResult = pdfChat.ImportDocument("company-report.pdf");

Console.WriteLine($"Document indexed: {indexResult.PageCount} pages, {indexResult.PartitionCount} partitions");

// Start asking questions about the document
string[] questions = 
{
    "What are the main findings in this report?",
    "Can you summarize the financial highlights?",
    "What recommendations are provided?"
};

foreach (string question in questions)
{
    Console.WriteLine($"\nQ: {question}");
    
    DocumentQueryResult result = pdfChat.Query(question);
    
    Console.WriteLine($"A: {result.Content}");
    
    // Show source references
    if (result.References.Count > 0)
    {
        Console.WriteLine("Sources:");
        foreach (var reference in result.References)
        {
            Console.WriteLine($"  - Page {reference.PageNumber}: {reference.Excerpt.Substring(0, Math.Min(60, reference.Excerpt.Length))}...");
        }
    }
}

// You can also import multiple documents for cross-document Q&A
pdfChat.ImportDocument("quarterly-update.pdf");
pdfChat.ImportDocument("product-roadmap.pdf");

var crossDocResult = pdfChat.Query("How does the roadmap align with the quarterly goals?");
Console.WriteLine($"\nCross-document answer: {crossDocResult.Content}");
				
			
				
					using LMKit.Mcp.Client;
using LMKit.Model;
using LMKit.TextGeneration;
using LMKit.TextGeneration.Chat;
using System;

// Initialize the language model
var model = LM.LoadFromModelID("qwen3:4b");

// Create a multi-turn conversation
MultiTurnConversation chat = new MultiTurnConversation(model);
chat.MaximumCompletionTokens = 1024;

// Connect to a remote MCP server via HTTP/SSE
// Public MCP servers examples:
// - "https://time.mcp.inevitable.fyi/mcp" (Time & timezone utilities)
// - "https://mcp.deepwiki.com/mcp" (Ask questions over public GitHub repos)
// - "https://learn.microsoft.com/api/mcp" (Microsoft Learn documentation)
// - "https://currency-mcp.wesbos.com/mcp" (Currency conversion)
McpClient mcpClient = new McpClient("https://time.mcp.inevitable.fyi/mcp");

// Optional: For servers requiring authentication
// mcpClient.SetBearerToken("your-api-token");

// Optional: Monitor MCP communication
mcpClient.Sending += (sender, e) =>
{
    Console.WriteLine($"[MCP] Sending: {e.Method}");
};

mcpClient.Received += (sender, e) =>
{
    Console.WriteLine($"[MCP] Received: {e.Method} (Status: {e.StatusCode})");
};

// Optional: Handle authentication failures
mcpClient.AuthFailed += (sender, e) =>
{
    Console.WriteLine($"[MCP] Authentication failed: {e.StatusCode}");
};

// Optional: React to server catalog changes
mcpClient.CatalogChanged += (sender, e) =>
{
    Console.WriteLine($"[MCP] Catalog changed: {e.Kind}");
};

// Register MCP tools with the conversation
chat.Tools.Register(mcpClient);

// List available tools from the MCP server
Console.WriteLine("Available MCP tools:");
foreach (var tool in mcpClient.Tools)
{
    Console.WriteLine($"  - {tool.Name}: {tool.Description}");
}

// Monitor tool invocations
chat.AfterToolInvocation += (sender, e) =>
{
    Console.WriteLine($"[Tool] {e.ToolCall.Name} executed");
};

// Use MCP tools through natural conversation
Console.WriteLine("\n--- Conversation ---\n");

var response = chat.Submit("What time is it in Tokyo and New York?");
Console.WriteLine($"Assistant: {response.Content}");

response = chat.Submit("What's the time difference between Paris and Sydney?");
Console.WriteLine($"Assistant: {response.Content}");

// Clean up
mcpClient.Dispose();
				
			
				
					using LMKit.Data;
using LMKit.Extraction.Ocr;
using LMKit.Model;
using System;
using System.IO;
using System.Text;

// Load the LightOnOCR vision model optimized for document OCR
var model = LM.LoadFromModelID("lightonocr1025:1b");

// Create the VLM OCR engine
VlmOcr ocr = new VlmOcr(model);

// Load the PDF document
string pdfPath = "document.pdf";
Attachment attachment = new Attachment(pdfPath);

Console.WriteLine($"Processing: {pdfPath}");
Console.WriteLine($"Total pages: {attachment.PageCount}\n");

// Process each page and collect markdown output
StringBuilder markdownOutput = new StringBuilder();

for (int pageIndex = 0; pageIndex < attachment.PageCount; pageIndex++)
{
    Console.WriteLine($"Processing page {pageIndex + 1}/{attachment.PageCount}...");

    // Run OCR on the current page
    var result = ocr.Run(attachment, pageIndex);

    // Add page separator and content
    markdownOutput.AppendLine($"<!-- Page {pageIndex + 1} -->");
    markdownOutput.AppendLine(result.PageElement.Text);
    markdownOutput.AppendLine();

    // Display stats
    Console.WriteLine($"  Tokens: {result.TextGeneration.GeneratedTokens.Count}");
    Console.WriteLine($"  Speed: {result.TextGeneration.TokenGenerationRate:F1} tok/s");
    Console.WriteLine($"  Quality: {result.TextGeneration.QualityScore:F2}");
}

// Save the markdown output
string outputPath = Path.ChangeExtension(pdfPath, ".md");
File.WriteAllText(outputPath, markdownOutput.ToString());

Console.WriteLine($"\nMarkdown saved to: {outputPath}");

// Display the result
Console.WriteLine("\n--- Extracted Markdown ---\n");
Console.WriteLine(markdownOutput.ToString());
				
			
				
					using LMKit.Data;
using LMKit.Extraction;
using LMKit.Model;
using System;
using System.Collections.Generic;

// Load a vision-capable model for invoice processing
var model = LM.LoadFromModelID("qwen3-vl:4b");

// Create the text extraction engine
TextExtraction extractor = new TextExtraction(model);
extractor.Title = "Invoice";
extractor.Description = "Extract structured data from an invoice document";

// Define the invoice fields to extract
extractor.Elements = new List<TextExtractionElement>
{
    new TextExtractionElement("InvoiceNumber", ElementType.String, "The unique invoice identifier"),
    new TextExtractionElement("InvoiceDate", ElementType.Date, "The date the invoice was issued"),
    new TextExtractionElement("DueDate", ElementType.Date, "The payment due date"),
    new TextExtractionElement("VendorName", ElementType.String, "The name of the vendor or supplier"),
    new TextExtractionElement("VendorAddress", ElementType.String, "The vendor's full address"),
    new TextExtractionElement("CustomerName", ElementType.String, "The name of the customer or buyer"),
    new TextExtractionElement("CustomerAddress", ElementType.String, "The customer's full address"),
    new TextExtractionElement("Subtotal", ElementType.Number, "The subtotal amount before tax"),
    new TextExtractionElement("TaxAmount", ElementType.Number, "The total tax amount"),
    new TextExtractionElement("TotalAmount", ElementType.Number, "The total amount due"),
    new TextExtractionElement("Currency", ElementType.String, "The currency code (e.g., USD, EUR)"),
    new TextExtractionElement("PaymentTerms", ElementType.String, "Payment terms or conditions"),
    new TextExtractionElement("LineItems", ElementType.String, "Description of items or services with quantities and prices")
        { IsArray = true }
};

// Load the invoice PDF
string invoicePath = "invoice.pdf";
Attachment invoice = new Attachment(invoicePath);

Console.WriteLine($"Processing invoice: {invoicePath}");
Console.WriteLine($"Pages: {invoice.PageCount}\n");

// Set the invoice content for extraction
extractor.SetContent(invoice);

// Perform structured extraction
TextExtractionResult result = extractor.Parse();

// Display extracted invoice data
Console.WriteLine("--- Extracted Invoice Data ---\n");

foreach (var element in result.Elements)
{
    string value = element.Value?.ToString() ?? "N/A";
    
    if (element.TextExtractionElement.IsArray && element.Value is IEnumerable<object> items)
    {
        Console.WriteLine($"{element.TextExtractionElement.Name}:");
        foreach (var item in items)
        {
            Console.WriteLine($"  - {item}");
        }
    }
    else
    {
        Console.WriteLine($"{element.TextExtractionElement.Name}: {value}");
    }
}

// Access specific fields programmatically
var invoiceNumber = result.GetValue<string>("InvoiceNumber");
var totalAmount = result.GetValue<decimal>("TotalAmount");
var invoiceDate = result.GetValue<DateTime>("InvoiceDate");

Console.WriteLine($"\n--- Summary ---");
Console.WriteLine($"Invoice #{invoiceNumber}");
Console.WriteLine($"Date: {invoiceDate:d}");
Console.WriteLine($"Total: {totalAmount:C}");
				
			

Ready to Deploy? Choose Our Free Community License!

🚀 Take Your App to the Next Level with LM-Kit.NET’s Community Edition 🚀

Whether you’re developing new AI-powered solutions or enhancing existing applications, our Community License offers powerful, cross-platform AI capabilities for free. Enjoy the full spectrum of Generative AI tools, from text generation and RAG to content retrieval and more, all packed in a single, easy-to-use SDK.

Deploy with confidence, no strings attached, and start transforming your ideas into reality today.