Artificial intelligence is becoming an important part of modern .NET applications. Developers are integrating large language models (LLMs) into applications to generate content, answer questions, summarize documents, analyze information, and automate business tasks.
Most AI integrations use cloud-based services through external APIs. Although these services provide powerful models, they also introduce dependencies such as API costs, internet connectivity, rate limits, and data privacy considerations.
Running an LLM locally provides another option. Developers can download an open-weight model, run it on their own machines, and communicate with it from C# without sending prompts to a cloud AI provider.
Llama is one of the popular model families that developers can run locally. With Ollama and Microsoft.Extensions.AI, .NET developers can connect a local Llama model to a .NET 11 application using familiar C# APIs.
In this article, we will explore how to install Ollama, download a Llama model, configure a .NET 11 application, send prompts from C#, receive responses, implement streaming, and handle common issues when running local AI models.
Understanding Llama and Ollama
Before writing code, it is important to understand the difference between Llama and Ollama.
Llama is a family of large language models developed by Meta. These models can perform tasks such as text generation, question answering, summarization, and code assistance.
Ollama is a tool that helps developers download, manage, and run compatible AI models locally. It also provides an HTTP API that applications can use to communicate with running models.
In simple terms, Llama provides the AI model, while Ollama provides the runtime environment for running and accessing that model.
The following table explains their responsibilities.
Component | Responsibility |
|---|
Llama | Provides the language model |
Ollama | Downloads and runs the model |
.NET 11 | Hosts the application logic |
OllamaSharp | Connects C# applications to Ollama |
Microsoft.Extensions.AI | Provides common AI abstractions such as IChatClient |
This combination allows developers to build AI-powered applications without directly implementing the model inference process.
How Local LLM Integration Works
When a .NET application communicates with a local Llama model, it follows a straightforward request-response workflow.
The developer installs Ollama on the machine.
Ollama downloads the required Llama model.
Ollama starts its local model service.
The .NET application creates an AI client.
The application sends a prompt through the client.
Ollama passes the request to the loaded model.
The model generates a response.
The response is returned to the .NET application.
By default, Ollama exposes its local API at:
http://localhost:11434
The .NET application communicates with this endpoint using HTTP. Both the model and application can run on the same machine, so prompts do not need to be sent to an external AI provider.
Installing Ollama and Downloading Llama
The first requirement is to install Ollama.
Download and install the Ollama application for your operating system. It supports Windows, macOS, and Linux.
After installation, open a terminal and verify that Ollama is available:
ollama --version
Next, download a Llama model:
ollama pull llama3.2
This command downloads the model files required to run Llama 3.2.
The exact download size depends on the model variant. Make sure your machine has sufficient disk space and memory.
After the download completes, start the model:
ollama run llama3.2
You should now see an interactive prompt where you can communicate with the model.
For example:
>>> Explain dependency injection in .NET.
Dependency injection is a design pattern used to provide
dependencies to classes instead of creating them directly.
It helps improve testability, maintainability, and
separation of concerns.
This confirms that the model is working.
You can also list downloaded models using:
ollama list
To check whether the local service is responding, use:
curl http://localhost:11434/api/tags
This endpoint returns information about locally available models.
Creating a .NET 11 Console Application
Now that Ollama is configured, let's create a .NET 11 application that communicates with the local Llama model.
Make sure the .NET 11 SDK is installed.
Open a terminal and create a new console application:
dotnet new console -n LocalLlamaApp --framework net11.0
Navigate to the project directory:
cd LocalLlamaApp
Install the required NuGet package:
dotnet add package OllamaSharp
OllamaSharp provides the integration between C# applications and the Ollama API. It also supports integration with Microsoft.Extensions.AI.
The application will use IChatClient, which provides a common interface for communicating with different AI providers.
Connecting to the Local Llama Model From C#
Open Program.cs and replace its contents with the following implementation:
using Microsoft.Extensions.AI;
using OllamaSharp;
IChatClient chatClient =
new OllamaApiClient(
new Uri("http://localhost:11434"),
"llama3.2"
);
Console.WriteLine("Local Llama AI Application");
Console.WriteLine("Enter 'exit' to close the application.");
while (true)
{
Console.Write("\nYou: ");
string? prompt = Console.ReadLine();
if (string.IsNullOrWhiteSpace(prompt))
continue;
if (prompt.Equals(
"exit",
StringComparison.OrdinalIgnoreCase))
{
break;
}
try
{
var response =
await chatClient.GetResponseAsync(prompt);
Console.WriteLine("\nLlama: ");
Console.WriteLine(response.Text);
}
catch (Exception ex)
{
Console.WriteLine(
$"Error communicating with Llama: {ex.Message}"
);
}
}
chatClient.Dispose();
Let's understand the important parts of this implementation.
Creating the Ollama Client
IChatClient chatClient =
new OllamaApiClient(
new Uri("http://localhost:11434"),
"llama3.2"
);
This creates a connection to the local Ollama service.
The first argument specifies the Ollama API endpoint. The second argument identifies the model that the application should use.
Here, we use llama3.2 because it was downloaded in the previous step.
The variable is declared as IChatClient instead of OllamaApiClient. This is useful because Microsoft.Extensions.AI provides a common abstraction for different chat providers.
If you later replace Ollama with another compatible provider, much of the application code can remain unchanged.
Sending a Prompt
var response =
await chatClient.GetResponseAsync(prompt);
GetResponseAsync() sends the user's prompt to the configured model and waits for the response.
The operation is asynchronous because model inference can take time.
The returned response contains the generated text and other available response information.
Handling Errors
catch (Exception ex)
{
Console.WriteLine(
$"Error communicating with Llama: {ex.Message}"
);
}
Local AI applications can encounter connection failures, model loading errors, insufficient resources, and request timeouts.
Handling exceptions prevents one failed request from immediately terminating the console application.
For production applications, use structured logging and distinguish between connection errors, cancellation, model errors, and unexpected failures.
Maintaining Conversation History
The previous implementation sends every prompt independently. This means the model does not automatically remember earlier questions.
For example, if a user asks:
You: What is ASP.NET Core?
And then asks:
You: What are its advantages?
The model may not know that the second question refers to ASP.NET Core unless the previous conversation is included.
To maintain conversation context, use a collection of ChatMessage objects.
Replace the previous Program.cs implementation with the following:
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 .NET programming assistant."
)
];
Console.WriteLine("Local Llama Chat");
Console.WriteLine("Type 'exit' to stop.");
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
{
var response =
await chatClient.GetResponseAsync(history);
history.Add(response.Message);
Console.WriteLine(
$"\nLlama: {response.Text}"
);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
history.RemoveAt(history.Count - 1);
}
}
chatClient.Dispose();
The conversation history contains three important types of information.
System messages define the model's behavior.
User messages contain questions and instructions.
Assistant messages contain previously generated responses.
Passing the complete history allows the model to use previous messages when generating its next response.
However, conversation history grows with every interaction. Large histories consume additional memory and increase inference time. Production applications should implement conversation limits, summarization, or context-window management.
Streaming Llama Responses in .NET
For longer responses, waiting for the complete output can make an application feel slow.
Streaming provides a better user experience because the application can display generated text as it becomes available.
Microsoft.Extensions.AI supports streaming through GetStreamingResponseAsync().
The following example demonstrates streaming:
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("\nLlama Response:");
await foreach (
var 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 is particularly useful when building:
AI chat applications.
Developer assistants.
Document summarization tools.
AI-powered support systems.
Interactive learning applications.
In a web application, the same approach can be used with streaming HTTP responses or Server-Sent Events to display generated text in the browser.
Running the Application
Make sure Ollama is running and the Llama model is available.
Navigate to the project directory and execute:
dotnet run
You should see the following output:
Local Llama AI Application
Enter 'exit' to close the application.
You: Explain dependency injection in .NET.
Llama:
Dependency injection is a design pattern that allows
objects to receive their dependencies from an external
container rather than creating them directly.
It improves maintainability, testability, and flexibility.
The actual response will depend on the selected model, prompt, and available computing resources.
You can ask multiple questions and experiment with different prompts without requiring a cloud AI API.
Choosing the Right Llama Model
Not every model is suitable for every machine.
Larger models generally require more memory and computing resources. Smaller models are easier to run locally but may provide different levels of reasoning and response quality.
Consider the following factors when selecting a model:
Factor | What to consider |
|---|
Model size | Available RAM and GPU memory |
Quantization | Memory usage and quality trade-offs |
Context window | Amount of conversation or document content |
Response speed | CPU, GPU, and hardware capabilities |
Task requirements | Coding, chat, summarization, or reasoning |
License | Usage and distribution requirements |
For development and experimentation, a smaller model can be a practical starting point.
For complex coding tasks, document analysis, or advanced reasoning, test larger models when your hardware supports them.
Do not assume that a model with a larger parameter count will automatically provide better results for every application.
Best Practices for Production Applications
Keep Model Configuration Outside Source Code
Do not hardcode the model name and endpoint throughout the application.
Use application configuration so that developers can change the model or endpoint without modifying business logic.
For example, an appsettings.json file can contain:
{
"AI": {
"Endpoint": "http://localhost:11434",
"Model": "llama3.2"
}
}
For production deployments, keep environment-specific values in configuration providers and avoid exposing internal service details.
Manage Resource Consumption
Local models consume system resources, including memory, CPU, and GPU capacity.
Avoid sending too many simultaneous requests to a single model instance. Introduce concurrency limits and request queues where necessary.
Implement Cancellation and Timeouts
Model inference may take longer for complex prompts or large inputs.
Use cancellation tokens and configurable request timeouts so that abandoned requests do not continue consuming resources unnecessarily.
Protect Local Model Endpoints
A local endpoint should not automatically be treated as secure.
If Ollama is exposed beyond the local machine, protect it with appropriate network restrictions, authentication through a secured gateway, and access controls.
Do not expose an unrestricted model endpoint directly to the public internet.
Monitor Model Performance
Track request duration, failures, cancellation, model availability, and resource consumption.
This information helps identify whether an application is limited by the model, hardware, network, or application code.
Limit Conversation History
Sending the complete conversation with every request can increase processing time and memory usage.
Use a defined conversation window or summarization strategy to keep requests within the model's context limits.
Common Mistakes and Troubleshooting
Problem | Possible reason | Recommended solution |
|---|
Connection refused | Ollama is not running | Start the Ollama service |
Model not found | Model has not been downloaded | Run ollama pull llama3.2 |
Slow first response | Model loading into memory | Allow the model to initialize |
Out of memory | Model requires more resources | Use a smaller or quantized model |
Application cannot connect | Incorrect endpoint | Verify the Ollama endpoint |
Poor response quality | Model or prompt limitations | Test another model and improve instructions |
Conversation loses context | Previous messages are not included | Maintain chat history |
Long response delays | Large context or resource contention | Limit context and concurrent requests |
One common mistake is assuming that Ollama must be manually restarted every time the .NET application runs. Depending on the operating system and installation, Ollama may already be running as a background service.
Another mistake is selecting a model based only on its name. Always check the model's capabilities, memory requirements, context limits, and licensing before using it in an application.
Advantages and Disadvantages
Advantages
Runs AI models on local hardware.
Avoids sending prompts to an external cloud AI provider when configured entirely locally.
Removes dependency on cloud AI API availability.
Provides greater control over model selection and deployment.
Supports integration with existing C# and .NET applications.
Microsoft.Extensions.AI makes provider changes easier.
Supports streaming and conversational interactions.
Disadvantages
Requires sufficient local hardware resources.
Large models can consume significant memory and storage.
Response speed depends on available CPU and GPU capabilities.
Local model quality may differ from hosted models.
Developers are responsible for model installation and updates.
Production deployment requires additional resource management and security controls.
Summary
Running a local Llama model from a .NET 11 application provides developers with another way to integrate artificial intelligence into C# applications.
By combining Llama, Ollama, OllamaSharp, and Microsoft.Extensions.AI, developers can create applications that send prompts to locally running models, receive generated responses, maintain conversation history, and stream output.
In this article, we explored the complete integration process, from installing Ollama and downloading a model to creating a .NET console application and communicating with Llama through IChatClient.
For production applications, focus on model selection, resource management, request cancellation, endpoint security, and conversation history management.
Local LLM integration is particularly useful when an application needs greater control over its AI infrastructure or must process sensitive information without sending prompts to an external cloud AI provider. It also provides a practical starting point for developers who want to experiment with AI directly from the .NET ecosystem.
Join the conversation! Your thoughts help the community grow.