![]() |
|
[DevBlog MS] Run local models in your .NET apps with Llama on Windows - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: C#, Visual Basic & .NET (https://sickgaming.net/forum-79.html) +--- Thread: [DevBlog MS] Run local models in your .NET apps with Llama on Windows (/thread-116101.html) |
[DevBlog MS] Run local models in your .NET apps with Llama on Windows - xSicKxBot - 11-23-2026 Running AI models locally lets you keep your prompts and responses on your PC, work offline after downloading a model, and experiment without paying per request. Getting started can take some setup: finding a model that fits your hardware, downloading it, and running a server your apps can call. Llama on Windows takes care of that for you. It’s a tray app that helps you find, download, and chat with open models on your PC. Once a model is running, your .NET apps can use it too. In this post, you’ll install Llama, download a model, and call it from a .NET 11 C# file-based app. You can find the complete code in the Llama on Windows .NET sample repository. What is Llama on Windows? Llama is a Windows 11 app that lives in your system tray. It’s built with .NET 10 and WinUI 3, it’s powered by llama.cpp, and it’s brought to you by the Hugging Face and llama.cpp teams. From the tray, you can:
![]() Under the hood, Llama manages a llama.cpp server for you. Models run on your PC and are stored in the standard Hugging Face cache, so other tools like the Code: llamaLlama is open source and free to download at llama.app. You can find the source code in the Llama-Windows repository on GitHub. Install Llama Llama is available in the Microsoft Store, which means you can install it with winget from a terminal: Code: winget install 9PPPSM6Q21Q6 --source msstoreYou can also get Llama from llama.app. Once it’s installed, open Llama from the Start menu. The Llama icon appears in your system tray. Download a model and start chatting
![]() When the download completes, select the model to see its details. Choose a context length, using the memory-fit indicators as a guide, then select Chat with model. ![]() Try asking a question in the browser chat. For example, ask for ideas for a small .NET app you could build with a local model. ![]() That’s it! You’re chatting with a model running on your PC. Llama loads models when you use them and unloads them after they’ve been idle for five minutes, so you don’t have to manage memory yourself. You can change the idle timeout in Llama’s settings. Use Llama from your .NET apps Chatting in the tray is a great way to try out models. When you’re ready to build something with them, you can call the same models from your code. Llama runs a llama.cpp server on Code: http://localhost:9931Code: /v1/chat/completionsCode: /v1/modelsIn .NET, you can use the OpenAI library together with Microsoft.Extensions.AI to work with Llama through Code: IChatClientWhat you’ll need
You can install the .NET 11 SDK with winget as well: Code: winget install Microsoft.DotNet.SDK.11Create the app The sample repository includes the complete app. With file-based apps, you don’t need a project file. Create a file called llama-chat.cs and add the following code: Code: #!/usr/bin/env dotnet
#:package Microsoft.Extensions.AI@11.0.0
#:package Microsoft.Extensions.AI.OpenAI@11.0.0
using System.ClientModel;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Text.Json;
using Microsoft.Extensions.AI;
using OpenAI;
// Llama serves an OpenAI-compatible API on localhost. Set LLAMA_ENDPOINT if you changed the port.
var endpoint = Environment.GetEnvironmentVariable("LLAMA_ENDPOINT") ?? "http://localhost:9931/v1";
using var http = new HttpClient();
// Ask Llama which models it can serve. This also tells us whether it's running.
List<string> models;
try
{
models = [.. (await GetLlamaModelsAsync()).Select(m => m.GetProperty("id").GetString()!)];
}
catch (HttpRequestException)
{
Console.WriteLine($"Couldn't reach Llama at {endpoint}. Open Llama from the Start menu and try again.");
return 1;
}
if (models.Count == 0)
{
Console.WriteLine("Llama doesn't have any models yet. Open Llama from the system tray and download a model.");
return 1;
}
Console.WriteLine("Models available in Llama:");
models.ForEach(m => Console.WriteLine($" {m}"));
// Use the model passed as an argument, or the first one Llama reports.
var model = args.Length > 0 ? args[0] : models[0];
Console.WriteLine($"\nChatting with {model}. Press Enter on an empty line to exit.");
// No API key is required by default, but the OpenAI client expects a value.
IChatClient client = new OpenAIClient(new ApiKeyCredential("no-key-required"), new OpenAIClientOptions { Endpoint = new Uri(endpoint) })
.GetChatClient(model)
.AsIChatClient()
.AsBuilder()
.UseFunctionInvocation()
.Build();
var options = new ChatOptions
{
Tools = [AIFunctionFactory.Create(GetMachineInfo), AIFunctionFactory.Create(ListModels)]
};
List<ChatMessage> history = [new(ChatRole.System, "You are a helpful assistant running locally on the user's PC. Keep answers short.")];
while (true)
{
Console.Write("\nYou: ");
var prompt = Console.ReadLine();
if (string.IsNullOrWhiteSpace(prompt))
{
break;
}
history.Add(new(ChatRole.User, prompt));
Console.Write("Llama: ");
List<ChatResponseUpdate> updates = [];
await foreach (var update in client.GetStreamingResponseAsync(history, options))
{
Console.Write(update.Text);
updates.Add(update);
}
Console.WriteLine();
history.AddMessages(updates);
}
return 0;
// Calls GET /v1/models. Llama adds details such as load status to the standard OpenAI response.
async Task<List<JsonElement>> GetLlamaModelsAsync()
{
using var json = JsonDocument.Parse(await http.GetStringAsync($"{endpoint}/models"));
return [.. json.RootElement.GetProperty("data").EnumerateArray().Select(m => m.Clone())];
}
[Description("Lists the models downloaded in Llama on this PC, whether each one is loaded in memory, and which one the user is chatting with.")]
async Task<string> ListModels()
{
var lines = (await GetLlamaModelsAsync()).Select(m =>
{
var id = m.GetProperty("id").GetString();
var status = m.TryGetProperty("status", out var s) ? s.GetProperty("value").GetString() : "unknown";
return $"{id} ({status}){(id == model ? ", current chat" : "")}";
});
return string.Join(Environment.NewLine, lines);
}
[Description("Gets the name, operating system, processor count, and .NET version of the computer the user is chatting from.")]
static string GetMachineInfo() =>
$"{Environment.MachineName}, {RuntimeInformation.OSDescription}, {Environment.ProcessorCount} logical processors, .NET {Environment.Version}";Run the app Make sure Llama is running, then run the app: Code: dotnet run llama-chat.csThe app lists the models Llama has and starts a chat with the first one. To pick a different model, pass its ID as an argument. You can copy a model’s ID from its details in the Llama tray. Code: dotnet run llama-chat.cs -- ggml-org/gemma-4-E4B-it-GGUF:Q4_0You don’t need to load the model first. Llama loads it on the first request, so that first response might take a little longer. The app gives the model two tools: Code: GetMachineInfoCode: ListModelsCode: MYPCCode: You: Which models do I have, and which one am I talking to? Use your tool.
Llama: You have the following model: `ggml-org/gemma-4-E4B-it-GGUF:Q4_0`.
You are currently chatting with **gemma-4-E4B-it**.
You: What computer am I on? Use your tool.
Llama: You are on a **MYPC** running **Microsoft Windows 10.0.26200** with **16 logical processors** and **.NET 11.0.0**.
You: Why is the sky blue?
Llama: The sky appears blue due to a phenomenon called **Rayleigh scattering**.Tool calling depends on the model you choose. If a model ignores the tools, try a larger model or one that lists tool support on its Hugging Face model card. How it works Let’s walk through the main parts of the app. Find the models. The app calls Code: GET /v1/modelsCreate the chat client. The app creates an Code: OpenAIClientCode: AsIChatClient()Code: IChatClientCode: UseFunctionInvocation()Add tools. Code: AIFunctionFactory.CreateCode: GetMachineInfoCode: ListModelsCode: DescriptionCode: Microsoft.Extensions.AIChat. Code: GetStreamingResponseAsyncBecause the chat loop only depends on Code: IChatClientWatch the announcement Watch the announcement of Llama on Windows in the .NET Conf 2026 keynote. Next steps We’re excited to see what you build with local models and .NET. Here’s where to go next:
Thanks to the Hugging Face and llama.cpp teams for building Llama on Windows. For issues or feature requests for Llama itself, open an issue in the Llama-Windows repository. Share what you’re building with local models and .NET in the comments below. The post Run local models in your .NET apps with Llama on Windows appeared first on .NET Blog. |