Introduction
AI models are becoming part of everyday application development. Developers use them to summarize documents, answer questions, generate code, analyze data, and automate repetitive tasks. However, calling a hosted AI service is not always the right choice. Some applications process confidential information, need to work without an internet connection, or want to avoid paying for every model request.
Running a language model locally provides another option. Instead of sending prompts and documents to an external service, an application can communicate with a model running on the developer's own computer. The model handles the request locally, and the application receives the response through an HTTP endpoint.
Modern .NET makes this approach easier with file-based applications and Microsoft.Extensions.AI. You can create a small C# utility in a single source file, connect it to a local Llama server, and build a command-line chat application without creating a traditional solution or project file.
In this article, we will use Llama on Windows as the local model host and connect to it from a .NET 11 file-based application. We will also explore how the OpenAI-compatible API works, how to stream model responses, and how to manage conversation history.
What Is a Local Llama Model?
A local language model is an AI model that runs on your own computer instead of processing requests on a remote AI service. Llama is a model family that can be run through different local inference tools.
For this example, we will use Llama on Windows, a desktop application that manages local models and provides a server that .NET applications can call.
The application uses llama.cpp to run models on the computer. It provides a graphical interface for finding models, downloading them, selecting model settings, and chatting with them.
Once a model is running, Llama exposes an HTTP API on the local machine. By default, the endpoint is:
http://localhost:9931
The server supports OpenAI-compatible endpoints, including the chat completions endpoint and the models endpoint. This means a .NET application can use familiar OpenAI client libraries while communicating with the local server instead of a hosted OpenAI service.
The important distinction is that using an OpenAI-compatible API does not mean the request is sent to OpenAI. The endpoint determines where the request goes. In this example, the application communicates with the local Llama server.
Prerequisites
Before creating the application, prepare the local model environment.
You will need:
- .NET 11 SDK installed on your computer.
- Llama on Windows installed and running.
- At least one compatible model downloaded through the Llama application.
- A code editor or terminal for creating and running the C# file.
Open Llama from the Windows Start menu and select a model that fits your available memory and hardware. Smaller quantized models are generally easier to run on computers with limited resources, although the quality and speed of responses depend on the model and hardware.
After downloading a model, open it in the Llama chat interface and send a test prompt. This confirms that the model is available before connecting it to the .NET application.
You can also verify that the local server is responding by opening the following endpoint in a browser:
http://localhost:9931/v1/models
It should return information about the models available through the server.
Creating a C# File-Based Application
A file-based application allows you to run a C# program directly from a single source file. You do not need to create a solution file, a project file, or a separate dependency configuration file.
Create a file named LlamaChat.cs and add the following package references at the top:
#:package [email protected]
#:package [email protected]
These packages provide the common AI abstractions and the integration with the OpenAI-compatible client.
The package directives are processed by the .NET SDK. When the application runs, the SDK restores the required NuGet packages and builds the file-based application.
You can now add the C# implementation below the package references.
Connecting to the Local Llama Server
The first step is to create a client that points to the local server.
The OpenAI client supports custom endpoints through OpenAIClientOptions. We can use this feature to connect to Llama instead of the default hosted service.
using System.ClientModel;
using Microsoft.Extensions.AI;
using OpenAI;
var endpoint = Environment.GetEnvironmentVariable("LLAMA_ENDPOINT")
?? "http://localhost:9931/v1";
var model = Environment.GetEnvironmentVariable("LLAMA_MODEL")
?? "your-downloaded-model-id";
var options = new OpenAIClientOptions
{
Endpoint = new Uri(endpoint)
};
var openAIClient = new OpenAIClient(
new ApiKeyCredential("no-key-required"),
options);
IChatClient chatClient = openAIClient
.GetChatClient(model)
.AsIChatClient();
Console.WriteLine("Connected to the local Llama endpoint.");
The endpoint points to the local Llama server. If you have changed its port or configured a different local endpoint, you can provide the new address through the LLAMA_ENDPOINT environment variable.
The model value must match the model identifier exposed by the local server. It is not necessarily the friendly name displayed in the graphical interface.
The local server does not require a real API key by default. However, the OpenAI client expects a credential during initialization, so the example supplies a placeholder value.
The AsIChatClient method converts the provider-specific chat client into the common IChatClient abstraction. This is useful because the rest of the application can work with Microsoft.Extensions.AI rather than depending directly on a specific provider.
Building a Simple Chat Application
After creating the client, we can use it to send prompts and display responses.
The following implementation keeps the application simple. It reads user input from the terminal, sends the prompt to the local model, and prints the generated response.
using System.ClientModel;
using Microsoft.Extensions.AI;
using OpenAI;
var endpoint = Environment.GetEnvironmentVariable("LLAMA_ENDPOINT")
?? "http://localhost:9931/v1";
var model = Environment.GetEnvironmentVariable("LLAMA_MODEL")
?? "your-downloaded-model-id";
var openAIClient = new OpenAIClient(
new ApiKeyCredential("no-key-required"),
new OpenAIClientOptions
{
Endpoint = new Uri(endpoint)
});
IChatClient chatClient = openAIClient
.GetChatClient(model)
.AsIChatClient();
var history = new List<ChatMessage>
{
new(ChatRole.System,
"You are a helpful assistant. Give clear and practical answers.")
};
Console.WriteLine($"Connected to model: {model}");
Console.WriteLine("Type your question. Enter an empty line to exit.");
while (true)
{
Console.Write("\nYou: ");
var prompt = Console.ReadLine();
if (string.IsNullOrWhiteSpace(prompt))
{
break;
}
history.Add(new ChatMessage(ChatRole.User, prompt));
Console.Write("Llama: ");
var updates = new List<ChatResponseUpdate>();
await foreach (var update in chatClient.GetStreamingResponseAsync(history))
{
Console.Write(update.Text);
updates.Add(update);
}
Console.WriteLine();
history.AddMessages(updates);
}
Console.WriteLine("Chat session ended.");
The application starts by creating a conversation history containing a system message. This message provides basic instructions about how the assistant should respond.
Whenever the user enters a prompt, the application adds it to the history as a user message. The model receives the conversation history and generates a response.
The important part is GetStreamingResponseAsync. Instead of waiting for the complete answer, the application receives response updates as the model generates them. Each update is printed immediately, making the terminal experience feel more responsive.
After generation finishes, AddMessages adds the assistant response to the conversation history. The next request therefore includes previous messages, allowing the model to use earlier conversation context.
Without conversation history, every request would be treated as a separate interaction unless the model server maintains state independently.
Running the File-Based Application
Save the implementation as LlamaChat.cs.
Open a terminal in the directory containing the file and run:
dotnet run --file LlamaChat.cs
The .NET SDK restores the package references, builds the application, and starts it.
Make sure Llama is running and the selected model is available before sending a prompt.
If you want to use a different model, set the model identifier through an environment variable.
In PowerShell:
$env:LLAMA_MODEL="your-downloaded-model-id"
dotnet run --file LlamaChat.cs
You can also configure the server endpoint:
$env:LLAMA_ENDPOINT="http://localhost:9931/v1"
This keeps model selection and endpoint configuration outside the source file. It is particularly useful when the same utility needs to run against different local models or development environments.
Why Use Microsoft.Extensions.AI?
Microsoft.Extensions.AI provides a common abstraction for working with AI services in .NET applications. Its IChatClient interface helps separate application logic from the underlying model provider.
Without a common abstraction, application code can become closely tied to a particular client library. Changing providers may then require updates throughout the application.
With IChatClient, the application can focus on conversation history, prompt handling, streaming, and response processing.
| Area | Direct provider-specific client | IChatClient abstraction |
|---|
| Provider dependency | Tied to a specific client | Uses a common interface |
| Application logic | May contain provider-specific calls | Can remain provider-independent |
| Streaming | Depends on provider API | Common streaming methods |
| Provider replacement | May require more changes | Often requires changes mainly during client setup |
| Reusability | More difficult across providers | Easier to share application logic |
The abstraction does not make every provider feature identical. Some models support capabilities that others do not. However, it provides a consistent starting point for common chat operations.
This becomes useful when an application starts with a local model but may later need to support another local runtime or a hosted AI provider.
Handling Errors and Model Availability
A local model application should not assume that the server is always available. The user may close Llama, the model may not be downloaded, or the local server may be listening on a different port.
For a small utility, you can handle connection failures around the chat operation:
try
{
var response = await chatClient.GetResponseAsync(
"Explain dependency injection in C#.");
Console.WriteLine(response.Text);
}
catch (HttpRequestException ex)
{
Console.WriteLine(
$"Unable to connect to the local model server: {ex.Message}");
}
catch (OperationCanceledException)
{
Console.WriteLine("The model request was cancelled or timed out.");
}
This example is useful for a one-time request. In a larger chat application, apply similar error handling around the streaming loop and distinguish connection failures from model-generation failures.
You should also validate the model identifier before starting a long-running chat session. The local server provides a models endpoint that can be used to discover available model identifiers.
A production utility should provide a clear message when the endpoint is unavailable or the requested model cannot be found instead of displaying an unexplained exception.
Best Practices for Local AI Applications
Choose a model that fits available hardware
A model that is too large for the available memory may run slowly or fail to load. Start with a model that fits the computer's memory and processing capabilities. Test response quality and generation speed with representative prompts before selecting a model for regular use.
Keep endpoint configuration separate
Avoid hardcoding local server addresses and model identifiers throughout the application. Environment variables or configuration files make it easier to change the model without modifying the program.
Preserve conversation history carefully
Conversation history provides context, but it also increases the amount of data sent with every request. Long conversations can consume more memory and increase response time. Consider limiting the number of previous messages or summarizing older interactions.
Use streaming for interactive applications
Streaming allows users to see generated text as it becomes available. This is especially helpful when responses take several seconds. For background jobs that need the complete response before continuing, a non-streaming method may be simpler.
Handle unavailable models
Do not assume that the model is already loaded in memory. Some local runtimes load models when the first request arrives. The first response may therefore take longer than later responses.
Protect the local endpoint
A local endpoint is not automatically secure just because it uses localhost. Avoid exposing an unauthenticated model server to a public network. If other applications or machines need access, configure suitable authentication, network restrictions, and access controls.
Avoid sending sensitive data to unknown endpoints
A local setup can keep prompts on the computer, but this depends on the endpoint actually being local. Verify the configured address and understand how the model runtime handles requests before processing confidential information.
Common Mistakes to Avoid
One common mistake is using the wrong model identifier. The display name shown in the desktop interface may differ from the identifier returned by the models endpoint. Always use the identifier expected by the API.
Another mistake is connecting to the default hosted API endpoint instead of the local server. The custom endpoint must point to the local Llama address, including the API path.
Developers sometimes assume that installing the .NET packages is enough to run a model. The NuGet packages provide client functionality, not the model itself. A compatible local model runtime must be installed and running separately.
Finally, avoid treating streaming updates as complete conversation messages. A streaming response can contain multiple updates. Collect the updates and add the completed assistant response to the history after generation finishes.
Advantages and Disadvantages
Advantages
- Prompts and responses can remain on the local computer when using a genuinely local runtime.
- Applications can continue working without an internet connection after the model has been downloaded.
- There is no per-request hosted API charge for local inference.
- File-based applications make experimentation possible without creating a traditional project.
- Microsoft.Extensions.AI provides a common interface that helps reduce provider-specific application code.
- Streaming improves the experience of interactive command-line tools.
Disadvantages
- Model performance depends on the computer's CPU, GPU, memory, and model size.
- Downloading models can require several gigabytes of storage.
- The first request may take longer while the model loads.
- Local model quality and tool-calling support vary between models.
- Developers must manage the local runtime and its availability.
- A local model may not provide the same response quality or speed as a larger hosted model.
Summary
Calling a local Llama model from a C# file-based application is a practical way to experiment with AI without creating a traditional .NET project or depending on a hosted model API.
The local runtime provides an HTTP endpoint, while the OpenAI client and Microsoft.Extensions.AI provide a familiar way to communicate with it. The IChatClient abstraction keeps the application logic separate from the model provider, and GetStreamingResponseAsync makes it possible to display responses as they are generated.
This approach works well for command-line assistants, internal developer utilities, local document tools, and AI experiments. As the application grows, the same core logic can be moved into a traditional .NET project and extended with configuration, logging, dependency injection, and additional model capabilities.
Join the conversation! Your thoughts help the community grow.