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 Thought-Action-Observation data structures

struct Observation {
    std::string content;
    bool isError;
};

using ToolFn = std::function<Observation(const std::string&)>;
using ReasonFn = std::function<std::pair<std::string, std::string>(
    const std::string&, const std::vector<std::string>&)>;

2Step 2: Implement the ReAct loop: Thought -> Action -> Observation

std::string reactLoop(const std::string& query,
                       ReasonFn reason,
                       std::map<std::string, ToolFn>& tools,
                       int maxSteps = 5) {
    std::vector<std::string> history;
    history.push_back("Query: " + query);

    for (int i = 0; i < maxSteps; ++i) {
        // Thought + Action selection
        auto [thought, action] = reason(query, history);
        history.push_back("Thought: " + thought);

        if (action == "FINISH") return thought;

        // Execute the action
        auto it = tools.find(action);
        Observation obs = it != tools.end()
            ? it->second(thought)
            : Observation{"Unknown tool: " + action, true};

        history.push_back("Observation: " + obs.content);
    }

    return "Max steps reached";
}

3Step 3: Demonstrate with a simple tool

int main() {
    std::map<std::string, ToolFn> tools;
    tools["search"] = [](const std::string& q) -> Observation {
        return {"Result for: " + q, false};
    };

    auto answer = reactLoop(
        "What is C++20?",
        [n = 0](const std::string&,
                const std::vector<std::string>& hist) mutable
            -> std::pair<std::string, std::string> {
            if (++n >= 3) return {"C++20 is a major standard", "FINISH"};
            return {"I need to search for this", "search"};
        },
        tools
    );
    std::cout << "Answer: " << answer << "\n";
}

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.