Recursive AI

Steer a running local LLM in C#

OneLLM is a free, open-source LLM and agent library for .NET from Recursive AI. MIT or Apache-2.0.

Queue a correction for the next turn without stopping the current tool.

Terminal
dotnet add package RecursiveAI.OneLlm

Requires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.

You’ll need a local llama.cpp or other OpenAI-compatible server on port 8080; setup is below the code.

The first eight lines steer the run with MessageAsync; the Palette class only sets up the local model and a slow tool to steer while it runs.

C#
using var demo = new Demo.Palette();
var (run, finishTool) =
    await demo.WaitForToolAsync();
await run.MessageAsync("Say blue.");
Console.WriteLine("Correction queued.");
finishTool.SetResult();
var result = await run.AwaitAsync();
Console.WriteLine($"Reply: {result.Text}");
 
namespace Demo
{
    using OneLlm;
    using OneLlm.Agents;
    using OneLlm.Catalog;
    using OneLlm.Definitions;
    using OneLlm.Providers;
    using OneLlm.Providers.OpenAI;
    using OneLlm.Tools;
 
    sealed class Palette : IDisposable
    {
        private readonly CancellationTokenSource timeout =
            new(TimeSpan.FromSeconds(30));
 
        public async Task<(AgentRun, TaskCompletionSource)>
            WaitForToolAsync()
        {
            var ct = timeout.Token;
            var toolStarted = NewSignal();
            var finishTool = NewSignal();
            var catalog = CatalogLayer.FromYaml(
                CatalogLayer.Code, """
                name: local
                models:
                  - name: local-model
                """);
            var runtime = new Runtime
            {
                Catalog = ModelCatalog.Create([catalog]),
                Providers = new ProviderRegistry(_ => null)
            };
            var url = new UriBuilder
            { Port = 8080, Path = "v1/" }.Uri;
            var provider = new OpenAICompatibleProvider(
                "local", new() { BaseUrl = url },
                TimeProvider.System);
            runtime.Providers.Set("local", provider);
            runtime.Tools.Add(Tool.Create("load_palette",
                async (CancellationToken token) =>
                {
                    toolStarted.SetResult();
                    await finishTool.Task.WaitAsync(token);
                    return "Blue and red are both available.";
                }));
            var definition = AgentDefinition.Parse("""
                name: palette
                model: local-model
                systemPrompt: >-
                  After the palette is loaded, say the color in the
                  most recent user message. Reply with one word.
                temperature: 0
                maxIterations: 4
                initialPrompts:
                  - user:
                      - text: Call load_palette, then choose red.
                references:
                  - tools: [load_palette]
                """);
            var run = await runtime.StartAgentAsync(definition,
                cancellationToken: ct);
            var finished = run.AwaitAsync(ct);
            if (await Task.WhenAny(toolStarted.Task,
                    finished) == finished)
            {
                await finished;
                throw new InvalidOperationException(
                    "The model did not call load_palette.");
            }
            return (run, finishTool);
        }
 
        static TaskCompletionSource NewSignal() => new(
            TaskCreationOptions.RunContinuationsAsynchronously);
 
        public void Dispose() => timeout.Dispose();
    }
}

Install llama.cpp and download qwen2.5-1.5b-instruct-q4_k_m.gguf. The model is not in the zip. Start the server on your own machine; --jinja enables the model’s tool-call template, and --alias gives it the name used in the C# example.

Terminal
llama-server -m qwen2.5-1.5b-instruct-q4_k_m.gguf \
  --alias local-model --port 8080 --jinja -c 2048

Leave the server running and open a second terminal. No API key is needed.

Unzip the example, then dotnet run.

Text
Correction queued.
Reply: blue

The first model turn requests load_palette. The C# tool signals that it has started, then waits until the host queues “Say blue.” Once the host releases the tool, OneLLM sends the tool result and the correction in the next model request. If the model replies without calling load_palette, the sample throws InvalidOperationException rather than treating the reply as a successful correction.

Variations

Inspect the next request without starting a model. Add using OneLlm.Messages; and using OneLlm.Testing; inside namespace Demo, then replace the url and provider setup inside WaitForToolAsync with the following. Keep runtime.Providers.Set("local", provider); as it is. Here the reply is fixed; it’s the last two messages in the request that demonstrate delivery order.

C#
var provider = new ScriptedProvider();
provider.Enqueue(
    new ScriptStep
    {
        ToolCalls = [new("palette", "load_palette", "{}")]
    },
    new ScriptStep
    {
        Chunks = ["blue"],
        Expect = request =>
        {
            var call = request.Messages[^2].ToolCalls.Single();
            var text = call.Result.OfType<TextPart>().Single();
            Console.WriteLine($"Tool result: {text.Text}");
            var update = request.Messages[^1].GetUserText();
            Console.WriteLine($"Next instruction: {update}");
        }
    });
Text
Correction queued.
Tool result: Blue and red are both available.
Next instruction: Say blue.
Reply: blue

The short answer

Keep the AgentRun returned by StartAgentAsync and call MessageAsync on it when the user changes an instruction. For a live run, OneLLM reads the correction at the next turn boundary. The current tool still finishes, and the next model request includes its result followed by the new instruction. Use AwaitAsync to get the result of the run. MessageAsync only queues the correction while the run is active.

Can you run an LLM locally from C#?

Yes. In this example, the C# app owns the conversation and runs the palette tool. llama.cpp loads the model and answers HTTP requests on the same machine. The program registers its provider as local and puts local-model under that provider in the model catalog. The same model name appears in the YAML definition and the server’s --alias flag. If you change the alias, change both C# references too.

This task requires more than a server that can generate text. The model must return a tool call on the first turn so that the app has work in progress when it sends the correction. A plain chat reply leaves the run waiting. If you swap models and get the “did not call” error, check tool-call support and the server’s chat template before debugging MessageAsync.

Can you send a message while a tool is running?

Yes. OneLLM does not edit the model request that’s already in flight, stop the tool, or undo what the tool did. In the palette example, the tool’s answer still names both available colors. The new instruction changes which color to choose, not what the tool has already found. In an app, show “queued” when MessageAsync returns and show the model’s reply separately. If the user actually wants to stop the work, use CancelAsync instead of sending a correction.

A waiting run behaves differently. A reply with no tool call puts the run into waiting; sending a new message then starts another segment of the same instance. If the run is waiting for approval, the message stays queued until the decisions are made. If it’s waiting on ask_user, a message from the app answers that question instead. Keep those states separate in your UI so users know whether they’re sending a correction, answering a question, or deciding whether a tool can run. See messages and steering for the delivery rules.

All onellm recipes