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:11434
When 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 --version
Next, download a language model.
For this example, we will use Llama 3.2:
ollama pull llama3.2
This 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.2
You 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 list
Make 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 LocalLLMPrivacyApp
Install OllamaSharp:
dotnet add package OllamaSharp
OllamaSharp 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();
The history contains system, user, and assistant messages.
The system message provides instructions about the assistant's behavior. User messages contain questions, while assistant messages contain previous responses.
Sending conversation history allows the model to understand the context of the current request.
For production applications, do not maintain unlimited conversation history. Use context limits, message summarization, and appropriate retention policies.
Streaming Responses From a Local Model
For longer responses, displaying the complete output only after generation finishes can create a poor user experience.
Streaming allows the application to display response content as the model generates it.
Microsoft.Extensions.AI supports streaming through GetStreamingResponseAsync().
using Microsoft.Extensions.AI;
using OllamaSharp;
IChatClient chatClient = new OllamaApiClient(
new Uri("http://localhost:11434"),
"llama3.2"
);
Console.Write("Enter your question: ");
string prompt = Console.ReadLine() ?? "";
Console.WriteLine("\nAI Response:");
await foreach (
ChatResponseUpdate update in
chatClient.GetStreamingResponseAsync(prompt))
{
Console.Write(update.Text);
}
Console.WriteLine();
chatClient.Dispose();
Instead of waiting for the entire response, the application receives incremental updates.
This approach is useful for chat applications, internal developer assistants, and AI-powered support tools.
Streaming can also be implemented in ASP.NET Core applications using Server-Sent Events or another suitable streaming transport.
Protecting Sensitive Information
Choosing a local LLM is only one part of a secure AI architecture.
The application must also ensure that sensitive information does not leave the intended environment through other components.
Consider the following security practices.
Keep Ollama on a Local Interface
If the application and Ollama run on the same machine, use the loopback address:
http://localhost:11434
Avoid exposing the Ollama service to public network interfaces unless there is a specific requirement.
If remote access is necessary, place the service behind an appropriately secured network boundary and enforce authentication and authorization.
Avoid Logging Sensitive Prompts
Application logs should not automatically store complete prompts and responses.
A prompt may contain customer records, employee information, financial data, or internal source code.
Log operational information such as request identifiers, processing duration, model name, and failure categories instead of complete sensitive content.
Review Third-Party Dependencies
A local model does not mean every part of the application runs locally.
Review NuGet packages, monitoring services, logging providers, telemetry exporters, and other integrations to understand whether they transmit application data externally.
Protect Conversation History
Conversation history may contain confidential information.
Use appropriate access controls and retention policies when storing conversation data. Encrypt sensitive information at rest when required by the application's security requirements.
Verify Network Behavior
Use network monitoring and infrastructure controls to verify that prompts and responses are not being transmitted to external services.
Remember that downloading a model initially requires network access in most setups. Model updates and package restoration may also require internet access.
A local inference architecture should be tested rather than assumed to be completely offline.
Best Practices for Production Applications
Use Dependency Injection
Register the AI client through the .NET dependency injection container rather than creating a new client for every request.
For example:
using Microsoft.Extensions.AI;
using Microsoft.Extensions.DependencyInjection;
using OllamaSharp;
var builder = Host.CreateApplicationBuilder(args);
builder.Services.AddChatClient(
new OllamaApiClient(
new Uri("http://localhost:11434"),
"llama3.2"
)
);
var app = builder.Build();
IChatClient chatClient =
app.Services.GetRequiredService<IChatClient>();
var response = await chatClient.GetResponseAsync(
"Explain async and await in C#."
);
Console.WriteLine(response.Text);
This approach makes it easier to manage the AI client and inject it into application services.
Implement Cancellation and Timeouts
Model inference may take longer when processing large prompts or complex requests.
Use cancellation tokens to stop requests that are no longer needed. Configure appropriate timeouts and concurrency limits according to the available hardware.
Validate Model Output
Never assume that an LLM response is always correct.
If the model generates JSON, deserialize it into a defined C# model and validate required properties before using the result.
For financial, medical, legal, and other important business workflows, apply domain-specific validation and human review where appropriate.
Manage Local Resources
Local models consume RAM, CPU, GPU memory, and disk space.
Select a model that fits the available infrastructure. Monitor resource consumption and limit concurrent inference requests to avoid overwhelming the machine.
Pin and Test Model Versions
Model updates can change response quality and behavior.
Maintain a known model version for production deployments and test new versions before replacing the existing model.
Local LLM vs Cloud AI API
Both approaches have advantages. The correct choice depends on the application's requirements.
| Comparison | Local LLM | Cloud AI API |
|---|
| Data processing | Local infrastructure | External provider infrastructure |
| Internet requirement | Not required for local inference | Usually required |
| API usage charges | No cloud inference API charge | Depends on provider and usage |
| Hardware | Managed by application owner | Managed by provider |
| Model selection | Locally supported models | Provider-supported models |
| Scaling | Requires additional local resources | Provider infrastructure can scale |
| Maintenance | Model and runtime management | Provider manages model infrastructure |
| Privacy control | Greater infrastructure control | Depends on provider policies and configuration |
A local LLM is not automatically cheaper. Hardware, electricity, maintenance, model hosting, and operational support also have costs.
Similarly, cloud AI providers may offer stronger models and managed infrastructure that would be difficult to operate locally.
Common Mistakes and Troubleshooting
| Problem | Possible reason | Recommended solution |
|---|
| Connection refused | Ollama service is not running | Start Ollama |
| Model not found | Model is not installed locally | Run ollama pull |
| Slow responses | Limited hardware resources | Select a smaller model |
| High memory consumption | Large model or long context | Reduce model size and context |
| Conversation loses context | History is not included | Maintain ChatMessage history |
| Sensitive information appears in logs | Request logging captures prompts | Redact or disable sensitive logging |
| Unexpected external traffic | Other application components transmit data | Review network activity and dependencies |
| Incorrect AI response | Model limitations or unclear instructions | Improve prompts and validate output |
One important mistake is exposing the local model endpoint directly to the internet. Local model execution does not automatically provide endpoint authentication or application-level access control.
Another mistake is assuming that a local model always produces the same quality as a cloud-hosted model. Test the selected model against real application scenarios before deploying it.
Advantages and Disadvantages
Advantages
- Allows C# applications to communicate with locally hosted language models.
- Avoids sending prompts to an external cloud AI API when the complete inference workflow remains local.
- Provides greater control over sensitive data processing.
- Supports offline inference after the required components are installed.
- Reduces dependency on cloud AI API availability and usage-based inference charges.
- Integrates with Microsoft.Extensions.AI through IChatClient.
- Supports conversation history and streaming responses.
Disadvantages
- Requires suitable local hardware.
- Large models may consume significant memory and processing resources.
- Model quality varies depending on the selected model.
- Developers must manage model installation and updates.
- Scaling requires additional infrastructure planning.
- Local execution does not automatically provide authentication, authorization, or complete data protection.
Summary
Calling a local LLM from C# is a practical approach for applications that need greater control over AI processing and sensitive information.
By combining Ollama, OllamaSharp, and Microsoft.Extensions.AI, developers can communicate with locally hosted language models using the familiar IChatClient abstraction.
In this article, we explored how to install a local model, connect it to a C# application, send prompts, maintain conversation history, stream responses, and apply security practices.
The most important consideration is that privacy depends on the complete application architecture, not just the location of the language model. Developers must also protect local endpoints, review dependencies, control logging, and monitor network communication.
With proper configuration and security controls, local LLM integration provides a useful foundation for building privacy-conscious AI assistants, internal developer tools, and enterprise applications using C#.
Join the conversation! Your thoughts help the community grow.