Agentic AIC#verifiedVerified

ReAct Agent Pattern in C#

Interleaves chain-of-thought Reasoning with Action execution, enabling LLMs to dynamically plan, act, and observe in a loop.

How to Implement the ReAct Agent Pattern in C#

1Step 1: Define the Tool and AgentStep types

public interface ITool
{
    string Name { get; }
    string Description { get; }
    Task<string> ExecuteAsync(string input);
}

public record AgentStep(
    string Thought, string Action,
    string ActionInput, string Observation);

2Step 2: Implement the ReAct reasoning loop

public static class ReactLoop
{
    private const int MaxSteps = 10;

    public static async Task<string> RunAsync(
        string query, IReadOnlyList<ITool> tools,
        Func<string, Task<string>> llm)
    {
        var steps = new List<AgentStep>();

        for (var i = 0; i < MaxSteps; i++)
        {
            // Reason about what to do next
            var prompt = BuildPrompt(query, tools, steps);
            var response = await llm(prompt);

            // Parse thought and action from response
            var (thought, action, actionInput, isFinal, finalAnswer) =
                ParseResponse(response);

            if (isFinal) return finalAnswer;

            // Execute the chosen tool
            var tool = tools.FirstOrDefault(t => t.Name == action)
                ?? throw new InvalidOperationException(
                    $"Unknown tool: {action}");

            var observation = await tool.ExecuteAsync(actionInput);
            steps.Add(new AgentStep(thought, action, actionInput, observation));
        }

        return "Max steps reached without final answer.";
    }

3Step 3: Build the prompt and parse LLM responses

    private static string BuildPrompt(
        string query, IReadOnlyList<ITool> tools, List<AgentStep> steps)
    {
        var toolNames = string.Join(", ", tools.Select(t => t.Name));
        return $"Query: {query}\nTools: {toolNames}";
    }

    private static (string Thought, string Action, string ActionInput,
        bool IsFinal, string FinalAnswer) ParseResponse(string response)
    {
        return ("", "", "", false, "");
    }
}

ReAct Agent Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

ReAct Agent Pattern in the Real World

Like a detective investigating a case: they form a hypothesis (Thought), gather evidence by interviewing witnesses or examining clues (Action), analyze what they found (Observation), and then refine their theory. They keep investigating until they solve the case.