Building an AI-powered application does not always require a large solution, multiple projects, or a complex application structure. Sometimes, you only need a small utility that accepts a question, sends it to a local language model, and displays the response.
Modern C# makes this easier with file-based apps. Starting with the .NET 10 SDK, developers can create and run C# applications from a single source file without maintaining a traditional project file.
This approach is useful for experimenting with AI models, creating command-line utilities, automating development tasks, and building small internal tools.
In this article, we will build a local AI chat tool using a C# file-based app, Ollama, and Microsoft.Extensions.AI. The application will communicate with a locally hosted language model, maintain conversation history, save conversations to a JSON file, and reload previous messages when restarted.
What Is a C# File-Based App?
Traditionally, creating a C# application requires a project file, source files, and sometimes additional configuration files.
A typical console application has a structure similar to this:
LocalAIChat/
│
├── LocalAIChat.csproj
├── Program.cs
├── Models/
│ └── ChatMessage.cs
└── Services/
└── AIChatService.csThis structure works well for larger applications because it separates responsibilities and makes the code easier to maintain.
However, it can feel unnecessary when you only want to create a small utility or test an idea.
A file-based app allows you to put the entire application in one C# file and run it directly through the .NET CLI.
For example:
Console.WriteLine("Hello from a C# file-based app!");Save the code in a file named hello.cs and run it using:
dotnet run hello.csThe .NET SDK automatically generates the necessary build configuration behind the scenes.
File-based apps support regular C# language features, including classes, interfaces, methods, asynchronous programming, and NuGet packages. You can also use special directives at the beginning of the file to configure package dependencies.
Why Use a File-Based App for Local AI?
A local AI chat utility is a good example of where file-based development can be useful.
You may want to test different language models, experiment with prompts, or create an internal assistant without building a complete desktop or web application.
A file-based app provides several benefits:
- No traditional .csproj file is required.
- NuGet dependencies can be declared directly in the source file.
- The application can run from the command line.
- Conversation history can be stored in local files.
- You can experiment with AI functionality without creating a large solution.
However, file-based apps are not intended to replace every project-based application. If the application grows to include multiple services, a graphical interface, complex configuration, or extensive testing, a traditional .NET project is usually a better choice.
Understanding the Application Architecture
We will build a simple command-line assistant that communicates with an Ollama model.
The application will contain four main responsibilities.
Component | Responsibility |
|---|---|
C# file-based app | Handles user input and application flow |
Ollama | Runs the local language model |
Microsoft.Extensions.AI | Provides the common IChatClient abstraction |
JSON conversation file | Stores messages between application sessions |
The request flow works as follows:
- The user enters a question in the console.
- The application adds the question to the conversation history.
- The chat history is sent to the local Ollama model.
- The model generates a response.
- The application displays the response and adds it to the history.
- The updated conversation is saved to a local JSON file.
When the application starts again, it loads the saved messages and continues the previous conversation.
Preparing the Local AI Environment
Before creating the C# file, install Ollama on your machine.
After installation, open a terminal and download a model:
ollama pull llama3.2The command downloads the model files required by Ollama.
Once the download is complete, run the model:
ollama run llama3.2Ollama normally exposes its local API at:
http://localhost:11434You can verify that the service is responding by checking the installed models:
ollama listKeep the Ollama service available while running the C# application. The application will communicate with this local endpoint to generate responses.
The initial model download requires internet access. After downloading the model and restoring the required .NET packages, local inference can work without a cloud AI API.
Creating the C# File-Based Application
Create a new file named local-ai-chat.cs.
We will use the OllamaSharp package to connect to Ollama and Microsoft.Extensions.AI to work with the common chat abstraction.
Unlike a traditional project, you do not need to run dotnet new or create a project file.
At the beginning of the C# file, add the package directive:
#:package OllamaSharpThis tells the .NET SDK to include the OllamaSharp NuGet package when building the file-based application.
The package provides the Ollama client implementation that we will use through IChatClient.
We will also use System.Text.Json, which is part of the .NET framework, to save and load conversation history.
Building the Local AI Chat Tool
Now, add the following code to local-ai-chat.cs.
#:package OllamaSharp
using System.Text.Json;
using Microsoft.Extensions.AI;
using OllamaSharp;
const string ModelName = "llama3.2";
string dataDirectory = Path.Combine(
Environment.GetFolderPath(
Environment.SpecialFolder.LocalApplicationData),
"LocalAIChat"
);
string historyFile = Path.Combine(
dataDirectory,
"conversation.json"
);
Directory.CreateDirectory(dataDirectory);
IChatClient chatClient = new OllamaApiClient(
new Uri("http://localhost:11434"),
ModelName
);
List<ChatMessage> history = await LoadHistoryAsync();
if (history.Count == 0)
{
history.Add(
new ChatMessage(
ChatRole.System,
"You are a helpful assistant. " +
"Answer questions clearly and accurately."
)
);
}
using CancellationTokenSource cancellation = new();
Console.CancelKeyPress += (_, e) =>
{
e.Cancel = true;
cancellation.Cancel();
};
Console.WriteLine("Local AI Chat");
Console.WriteLine($"Model: {ModelName}");
Console.WriteLine("Enter 'exit' to close the application.");
try
{
while (!cancellation.IsCancellationRequested)
{
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)
);
Console.Write("\nAI: ");
try
{
var responseBuilder = new System.Text.StringBuilder();
await foreach (
ChatResponseUpdate update in
chatClient.GetStreamingResponseAsync(
history,
cancellationToken: cancellation.Token))
{
Console.Write(update.Text);
responseBuilder.Append(update.Text);
}
string answer = responseBuilder.ToString();
Console.WriteLine();
history.Add(
new ChatMessage(
ChatRole.Assistant,
answer
)
);
await SaveHistoryAsync(history);
}
catch (OperationCanceledException)
{
Console.WriteLine("\nRequest cancelled.");
break;
}
catch (Exception ex)
{
history.RemoveAt(history.Count - 1);
Console.WriteLine(
$"\nUnable to generate a response: {ex.Message}"
);
}
}
}
finally
{
chatClient.Dispose();
}
async Task<List<ChatMessage>> LoadHistoryAsync()
{
if (!File.Exists(historyFile))
return [];
try
{
string json = await File.ReadAllTextAsync(historyFile);
List<StoredMessage>? messages =
JsonSerializer.Deserialize<List<StoredMessage>>(json);
return messages?
.Select(message => new ChatMessage(
message.Role switch
{
"system" => ChatRole.System,
"user" => ChatRole.User,
"assistant" => ChatRole.Assistant,
_ => throw new InvalidDataException(
$"Unsupported message role: {message.Role}")
},
message.Content
))
.ToList() ?? [];
}
catch (JsonException)
{
Console.WriteLine(
"Conversation file is invalid. Starting a new conversation."
);
return [];
}
}
async Task SaveHistoryAsync(List<ChatMessage> messages)
{
List<StoredMessage> storedMessages = messages
.Where(message =>
message.Role == ChatRole.System ||
message.Role == ChatRole.User ||
message.Role == ChatRole.Assistant)
.Select(message => new StoredMessage(
message.Role.ToString().ToLowerInvariant(),
string.Concat(
message.Contents
.OfType<TextContent>()
.Select(content => content.Text)
)
))
.ToList();
string json = JsonSerializer.Serialize(
storedMessages,
new JsonSerializerOptions
{
WriteIndented = true
}
);
string temporaryFile = historyFile + ".tmp";
await File.WriteAllTextAsync(temporaryFile, json);
File.Move(temporaryFile, historyFile, true);
}
sealed record StoredMessage(
string Role,
string Content
);
Join the conversation! Your thoughts help the community grow.