Artificial intelligence is becoming a common feature in modern applications. Developers use large language models (LLMs) to generate text, summarize documents, answer questions, analyze data, and automate different tasks.
Most AI integrations use cloud-based services. An application sends a prompt to an external API, the service processes the request, and the generated response is returned. Although this approach provides access to powerful models, it may not be suitable for every application.
For example, an enterprise application may process employee records, financial information, customer details, internal source code, or confidential business documents. Sending this information to an external AI provider may introduce privacy, security, compliance, and operational concerns.
Running a local LLM provides an alternative. Developers can download a model, execute it on their own infrastructure, and communicate with it directly from C# without sending prompts to a cloud AI API.
In this article, we will explore how to call a local LLM from C#, configure Ollama, integrate Microsoft.Extensions.AI, maintain conversation history, implement streaming, and apply security practices to protect sensitive information.
Why Call a Local LLM From C#?
A local LLM runs on a machine or infrastructure controlled by the application owner. Instead of sending prompts to an external AI provider, the application communicates with a locally hosted model service.
Consider an employee management application that uses AI to summarize employee feedback.
If the application sends employee information to an external AI API, the data leaves the organization's environment. Depending on the provider, configuration, and applicable agreements, this may introduce additional data handling requirements.
With a locally hosted model, the application can process the same information within its controlled infrastructure.
Some common reasons for choosing local LLM integration include:
- Processing confidential business information.
- Reducing dependency on external AI services.
- Avoiding per-request cloud AI API charges.
- Supporting offline or restricted-network environments.
- Maintaining greater control over model versions and deployment.
- Building internal AI assistants for enterprise applications.
However, local execution does not automatically guarantee complete security. Developers must also protect the model endpoint, local files, application logs, and infrastructure.
Understanding the Local LLM Architecture
To call a local LLM from C#, we need a model runtime that exposes an interface for application communication.
Ollama is a practical option because it allows developers to download and execute supported language models locally.
The architecture contains four main components:
| Component | Responsibility |
|---|---|
| C# application | Sends prompts and processes responses |
| Microsoft.Extensions.AI | Provides common AI abstractions |
| Ollama | Runs the model and exposes an HTTP API |
| Local LLM | Generates responses from the supplied prompts |
The request flow is straightforward:
- The user enters a question in the C# application.
- The application sends the prompt to the local Ollama endpoint.
- Ollama passes the request to the selected model.
- The model generates a response.
- Ollama returns the response to the C# application.
The default Ollama endpoint is:
http://localhost:11434When the application and Ollama run on the same machine, communication can remain within that machine.
This is different from a cloud-based architecture, where prompts are transmitted to an external provider over the internet.
Installing Ollama and Downloading a Local Model
First, install Ollama on your development machine.
After installation, open a terminal and verify that it is available:
ollama --versionNext, download a language model.
For this example, we will use Llama 3.2:
ollama pull llama3.2This command downloads the required model files from the Ollama model registry.
An internet connection is generally required for the initial download. After the model is downloaded, local inference can run without an internet connection, provided that the runtime and application dependencies are already available.
Start the model:
ollama run llama3.2You can test it directly from the terminal:
>>> Explain the benefits of dependency injection in C#.
Dependency injection helps reduce tight coupling between
classes. It improves testability, maintainability, and
flexibility by providing dependencies from external sources.You can also check the locally installed models:
ollama listMake sure the model name used in your C# application matches the installed model.
Creating a C# Application
Now, let's create a console application that communicates with the local LLM.
Create a new project:
dotnet new console -n LocalLLMPrivacyApp
cd LocalLLMPrivacyAppInstall OllamaSharp:
dotnet add package OllamaSharpOllamaSharp provides a C# client for communicating with Ollama. It also integrates with Microsoft.Extensions.AI through the IChatClient abstraction.
This allows application code to communicate with different AI providers through a common interface.
Connecting to the Local LLM Using IChatClient
Open Program.cs and add the following code:
using Microsoft.Extensions.AI;
using OllamaSharp;
IChatClient chatClient = new OllamaApiClient(
new Uri("http://localhost:11434"),
"llama3.2"
);
Console.WriteLine("Local AI Assistant");
Console.WriteLine("Enter 'exit' to close.");
while (true)
{
Console.Write("\nYou: ");
string? prompt = Console.ReadLine();
if (string.IsNullOrWhiteSpace(prompt))
continue;
if (prompt.Equals(
"exit",
StringComparison.OrdinalIgnoreCase))
{
break;
}
try
{
ChatResponse response =
await chatClient.GetResponseAsync(prompt);
Console.WriteLine("\nAI Response:");
Console.WriteLine(response.Text);
}
catch (Exception ex)
{
Console.WriteLine(
$"Local AI processing failed: {ex.Message}"
);
}
}
chatClient.Dispose();Let's understand the important parts.
Creating the Local AI Client
IChatClient chatClient = new OllamaApiClient(
new Uri("http://localhost:11434"),
"llama3.2"
);This creates a connection to the locally running Ollama service.
The URI identifies the local API endpoint, while the model name specifies which language model should generate responses.
The application uses IChatClient instead of depending directly on OllamaApiClient throughout its business logic.
This separation is useful when you need to replace Ollama with another compatible AI provider later.
Sending User Prompts
ChatResponse response =
await chatClient.GetResponseAsync(prompt);The GetResponseAsync() method sends the user's prompt to the configured model and waits for the generated response.
The method is asynchronous because generating a response may take time, depending on the model and available hardware resources.
Displaying the Response
Console.WriteLine(response.Text);The Text property provides the generated response.
The application can display this response in a console, save it to a file, or return it through an ASP.NET Core API.
The important point is that the application communicates with the local model endpoint rather than an external cloud AI API.
Maintaining Conversation History
A local LLM does not automatically remember every previous request.
For example, consider the following conversation:
User: What is ASP.NET Core?
AI: ASP.NET Core is a framework for building web applications.
User: What are its advantages?The second question depends on the first question. If the application sends only the latest prompt, the model may not understand what the user means by "its."
To maintain conversation context, store previous messages and send them with each request.
using Microsoft.Extensions.AI;
using OllamaSharp;
IChatClient chatClient = new OllamaApiClient(
new Uri("http://localhost:11434"),
"llama3.2"
);
List<ChatMessage> history =
[
new ChatMessage(
ChatRole.System,
"You are a helpful C# programming assistant."
)
];
while (true)
{
Console.Write("\nYou: ");
string? prompt = Console.ReadLine();
if (string.IsNullOrWhiteSpace(prompt))
continue;
if (prompt.Equals(
"exit",
StringComparison.OrdinalIgnoreCase))
{
break;
}
history.Add(
new ChatMessage(ChatRole.User, prompt)
);
try
{
ChatResponse response =
await chatClient.GetResponseAsync(history);
history.Add(response.Message);
Console.WriteLine(
$"\nAI: {response.Text}"
);
}
catch (Exception ex)
{
history.RemoveAt(history.Count - 1);
Console.WriteLine(
$"Request failed: {ex.Message}"
);
}
}
chatClient.Dispose();
Join the conversation! Your thoughts help the community grow.