Recursive AI

Delegate a task to a subagent in C#

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

Give the parent two tools: one to start a separate run and one to wait for its result.

Terminal
dotnet add package RecursiveAI.OneLlm

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

In the parent’s YAML definition:

YAML
references:
  - tools: [run_agent_async, await_agent]

Unzip the example, then dotnet run.

Here agentSwarmUri takes the registered name sorter; the parent then waits on the instance ID it gets back. The downloaded example prints Child returned: apple, pear.

The full program

Both agent definitions and the input “Sort pear and apple” are inside Program.cs. Register the child using runtime.AgentDefinitions.Add before starting the parent. Here the in-process ScriptedProvider, which ignores the model name gpt-6-luna when choosing its reply, supplies the sorting reply and makes the parent’s tool calls, so you can see the handoff without a model server or API key. The library does the actual work of starting the child and returning its result to the parent.

C#
using System.Text.Json;
using System.Text.RegularExpressions;
using OneLlm;
using OneLlm.Definitions;
using OneLlm.Messages;
using OneLlm.Testing;
 
var runtime = new Runtime();
var stub = new ScriptedProvider("openai");
runtime.Providers.Set("openai", stub);
 
runtime.AgentDefinitions.Add("sorter", AgentDefinition.Parse("""
    name: sorter
    model: gpt-6-luna
    systemPrompt: Sort the list and call task_complete.
    references:
      - tools: [task_complete]
    """));
 
var parent = AgentDefinition.Parse("""
    name: coordinator
    model: gpt-6-luna
    systemPrompt: Delegate sorting and return the child's list.
    initialPrompts:
      - user: [{text: Sort pear and apple.}]
    references:
      - tools: [run_agent_async, await_agent, task_complete]
    """);
 
string? childId = null;
stub.Fallback = request =>
{
    if (request.System?.StartsWith("Sort the list") == true)
        return Complete("child-done", "apple, pear");
 
    var calls = request.Messages.SelectMany(m => m.ToolCalls).ToArray();
    if (calls.Length == 0)
        return Call("start", "run_agent_async", """
            {"agentSwarmUri":"sorter","prompt":"Sort pear and apple."}
            """);
 
    if (calls.Length == 1)
    {
        var id = Regex.Match(Text(calls[0]), @"Instance Id: (\S+)");
        if (!id.Success)
            throw new InvalidOperationException("No child ID returned.");
        childId = id.Groups[1].Value;
        return Call("wait", "await_agent",
            JsonSerializer.Serialize(new { ids = new[] { childId } }));
    }
 
    var list = Regex.Match(Text(calls[1]), @"apple, pear");
    if (!list.Success)
        throw new InvalidOperationException("No sorted list returned.");
    Console.WriteLine($"Child returned: {list.Value}");
    return Complete("parent-done", list.Value);
};
 
var result = await runtime.RunAgentAsync(parent);
Console.WriteLine($"{result.StopReason}: {result.Text}");
 
static string Text(ToolCall call) =>
    string.Concat(call.Result.OfType<TextPart>().Select(p => p.Text));
 
static ScriptStep Call(string id, string name, string args) =>
    new() { ToolCalls = [new(id, name, args)] };
 
static ScriptStep Complete(string id, string result) =>
    Call(id, "task_complete", JsonSerializer.Serialize(
        new { result, summary = "Sorting complete." }));
Text
Child returned: apple, pear
Completed: apple, pear

The identifier you pass to run_agent_async for a new run is the child’s registered name, not its future instance ID. If you misspell the name and it can’t resolve the definition, the parent gets a tool error instead of a child result.

Variations

Check which call started the child. Add this after the run and before the helper methods. The example’s callback saves childId when the parent receives it, so the host can use it to look up the child. This prints start.

C#
if (childId is not null)
{
    var child = await runtime.Store.LoadAsync(childId);
    Console.WriteLine(child?.CallerToolCallId);
}

With a real model. Set OPENAI_API_KEY in your environment and change both definitions to model: gpt-5-mini. Replace the stub setup with the provider registration below, and remove childId, stub.Fallback, and the three helper methods at the end. Keep both definitions, the child registration, and runtime.RunAgentAsync(parent). The output above is from the offline run.

C#
using OneLlm;
using OneLlm.Providers.OpenAI;
 
var runtime = new Runtime();
var key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")
    ?? throw new InvalidOperationException("Set OPENAI_API_KEY.");
var provider = new OpenAIProvider(
    new OpenAIOptions { ApiKey = new Secret(key) }, TimeProvider.System);
runtime.Providers.Set("openai", provider);

The short answer

Register a named child definition on the Runtime and list run_agent_async and await_agent as tools in the parent’s definition. The parent calls run_agent_async with agentSwarmUri set to that name and prompt set to the work to do. Starting the child gives back an instance ID, not the answer. Pass that ID in await_agent’s ids array to get the child’s result.

What is a subagent in AI?

A subagent is a second agent that the main agent starts to do part of the job and report back.

In OneLLM, the child is its own instance in the same runtime. It has its own definition and instructions, so “sort this list” can be a complete assignment even if the parent was doing a bigger job. Pass the facts the child needs in the delegation prompt instead of assuming it can infer them from the parent’s instructions. The child’s instance records the caller and the tool call that started it. That lets you see which handoff produced a particular answer even if several runs used the same registered definition.

The child in this example has only task_complete and no file access is needed to load its definition. A host-registered definition can choose its own tools. Its grants, meaning permissions such as which file roots it can use, are still limited by the parent’s grants. The agent docs distinguish this from loading a definition from a file, which also limits the tools to the parent’s set plus task_complete.

When should you use subagents?

Use a child when the work needs its own instructions and has a result the parent can use without reading the child’s full conversation. A parent preparing a catalog, for example, can send a list of product labels to a child that normalizes them, then assemble the catalog itself. If the job is just sorting a list deterministically in production, call a C# method instead. Sorting here makes it easy to tell whether the result crossed the handoff.

Wait for the child before using its answer. The agent tools table notes that a message for the caller can end an await_agent wait, so in an app that can receive other messages, check that the tool response actually contains the result you need before treating the task as done.

All onellm recipes