Skip to content

IIterativeAgentLoop

NexusLabs.Needlr.AgentFramework

NexusLabs.Needlr.AgentFramework.Iterative

IIterativeAgentLoop Interface

Runs an iterative agent loop where each iteration builds a fresh prompt from workspace state instead of accumulating conversation history.

public interface IIterativeAgentLoop

Example

var workspace = new InMemoryWorkspace();
var options = new IterativeLoopOptions
{
    LoopName = "trip-planner",
    Instructions = "You plan multi-stop trips. Use tools to search and build itineraries.",
    Tools = [searchTool, addLegTool, getItineraryTool],
    PromptFactory = ctx =>
    {
        var itinerary = ctx.Workspace.FileExists("itinerary.json")
            ? ctx.Workspace.ReadFile("itinerary.json")
            : "No legs planned yet.";
        return $"Plan a 7-day trip to Japan. Current itinerary:\n{itinerary}";
    },
    MaxIterations = 15,
};

var context = new IterativeContext { Workspace = workspace };
var result = await loop.RunAsync(options, context, cancellationToken);

Console.WriteLine($"Completed in {result.Iterations.Count} iterations");
Console.WriteLine($"Total tokens: {result.Diagnostics?.AggregateTokenUsage.TotalTokens}");

Remarks

Unlike the standard FunctionInvokingChatClient approach (where conversation history grows with every tool call, producing O(n²) token cost), the iterative loop maintains O(n) cost by constructing independent prompts per iteration. The workspace (files) IS the memory — not the conversation.

Each iteration: 1. The PromptFactory builds a user message from the current workspace state and (optionally) last tool results. 2. The loop sends [system, user] to the LLM with available tools. 3. Tool calls are executed, updating the workspace. 4. Depending on ToolResultMode, tool results may be sent back to the model within the same iteration. 5. The iteration ends. The next iteration starts fresh.

The loop terminates when the model produces a text response (no tool calls), the maximum iteration count is reached, the IsComplete predicate fires, or the System.Threading.CancellationToken is cancelled.

Methods

IIterativeAgentLoop.RunAsync(IterativeLoopOptions, IterativeContext, CancellationToken) Method

Runs the iterative loop to completion.

System.Threading.Tasks.Task<NexusLabs.Needlr.AgentFramework.Iterative.IterativeLoopResult> RunAsync(NexusLabs.Needlr.AgentFramework.Iterative.IterativeLoopOptions options, NexusLabs.Needlr.AgentFramework.Iterative.IterativeContext context, System.Threading.CancellationToken cancellationToken=default(System.Threading.CancellationToken));

Parameters

options IterativeLoopOptions

Configuration for this run: instructions, tools, prompt factory, iteration limits, and tool result handling mode.

context IterativeContext

Mutable context carrying the workspace, tool results, and arbitrary state across iterations. The caller creates this and can pre-populate the workspace and state.

cancellationToken System.Threading.CancellationToken

Cancellation token. When cancelled, the loop completes the current tool execution (if any) and returns a partial result.

Returns

System.Threading.Tasks.Task<IterativeLoopResult>
A result containing per-iteration records, the final model response, aggregate diagnostics, and success/failure status.