What is the ReAct framework for AI agents and how is it implemented?
ReAct (Reasoning + Acting) interleaves chain-of-thought reasoning with action execution. The agent follows a Thought-Action-Observation loop: Thought (reason about what to do next), Action (execute a tool call), Observation (process the result), and repeat until the task is complete. Implementation: prompt the LLM with the ReAct format, parse its output to extract actions, execute them, and append observations. Example flow: user asks "What's the weather in the city where Apple is headquartered?" - Thought: I need to find Apple's headquarters location - Action: search("Apple headquarters location") - Observation: Cupertino, California - Thought: Now I need the weather for Cupertino - Action: getweather("Cupertino, CA") - Observation: 72F, sunny - Final answer: 72F and sunny. Advantages over simple tool calling: explicit reasoning traces improve debuggability, the agent can plan multi-step strategies, and reasoning helps with ambiguous queries. LangChain and LlamaIndex provide ReAct agent implementations. Optimization: limit maximum iterations (typically 5-10) to prevent infinite loops, implement early termination when confidence is high, and cache tool results for repeated queries.