🧠From Static Predictors to Autonomous Solvers: The Mechanics of the ReAct Framework
Traditional Large Language Models operate as passive text predictors: they receive a prompt and generate a completion in a single forward pass without interacting with external environments. Autonomous AI Agents break this paradigm by combining reasoning and acting into a dynamic loop. Formulated by Yao et al. (2022), the ReAct (Reasoning and Acting) Framework empowers LLMs to alternate between generating explicit mental reasoning traces (Thought), executing external tool calls or API queries (Action), and parsing tool execution responses (Observation). This iterative feedback loop enables agents to solve complex, multi-step problems that require real-time information retrieval and environmental interaction.
import re
from openai import OpenAI
client = OpenAI()
class SimpleReActAgent:
def __init__(self, system_prompt: str, tools: dict):
self.system_prompt = system_prompt
self.tools = tools
self.history = [{"role": "system", "content": system_prompt}]
def run(self, user_query: str, max_iterations: int = 5) -> str:
self.history.append({"role": "user", "content": user_query})
for i in range(max_iterations):
response = client.chat.completions.create(
model="gpt-4o",
messages=self.history,
temperature=0.0
)
assistant_message = response.choices.message.content
self.history.append({"role": "assistant", "content": assistant_message})
print(f"\n--- Iteration {i+1} ---\n{assistant_message}")
# Check if agent has formulated a final answer
if "Final Answer:" in assistant_message:
return assistant_message.split("Final Answer:")[-1].strip()
# Parse Thought, Action, and Action Input using Regex
action_match = re.search(r"Action:\s*(.+)", assistant_message)
input_match = re.search(r"Action Input:\s*(.+)", assistant_message)
if action_match and input_match:
action_name = action_match.group(1).strip()
action_arg = input_match.group(1).strip().strip('"\'')
if action_name in self.tools:
print(f"[Executing Tool: {action_name} with arg: {action_arg}]")
observation = self.tools[action_name](action_arg)
else:
observation = f"Error: Tool '{action_name}' not found."
observation_msg = f"Observation: {observation}"
print(observation_msg)
self.history.append({"role": "user", "content": observation_msg})
else:
break
return "Agent reached maximum iterations without final answer."
from langchain_openai import ChatOpenAI
from langchain.agents import AgentExecutor, create_react_agent
from langchain_community.tools.tavily_search import TavilySearchResults
from langchain import hub
# 1. Initialize LLM and Tools
llm = ChatOpenAI(model="gpt-4o", temperature=0)
tools = [TavilySearchResults(max_results=3)]
# 2. Pull standard ReAct prompt template from LangChain Hub
prompt = hub.pull("hwchase17/react")
# 3. Construct ReAct Agent and Executor
agent = create_react_agent(llm, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True, handle_parsing_errors=True)
# 4. Execute complex multi-step query requiring real-time web retrieval
response = agent_executor.invoke({
"input": "What is the current stock price of NVIDIA, and who is their current CEO?"
})
print(response["output"])
import sqlite3
from langchain.tools import tool
@tool
def query_order_database(order_id: str) -> str:
"""Queries SQLite order database for shipping status and delivery date given an order ID."""
conn = sqlite3.connect("ecommerce.db")
cursor = conn.cursor()
cursor.execute("SELECT status, delivery_date, customer_email FROM orders WHERE order_id = ?", (order_id,))
row = cursor.fetchone()
conn.close()
if row:
return f"Order {order_id} status is '{row[0]}', expected delivery: {row[1]}, customer: {row[2]}"
return f"Order {order_id} not found in database."
@tool
def process_store_refund(order_id: str) -> str:
"""Processes a full refund for a delayed or lost order ID."""
return f"Successfully processed refund for order {order_id}. Confirmation email dispatched."
# Bound to ReAct Agent Executor to handle incoming customer support escalations autonomously.
import pandas as pd
from langchain_experimental.agents import create_pandas_dataframe_agent
from langchain_openai import ChatOpenAI
df = pd.read_csv("enterprise_sales_2026.csv")
llm = ChatOpenAI(model="gpt-4o", temperature=0)
# Create Pandas DataFrame Agent (operates on ReAct reasoning loop)
python_agent = create_pandas_dataframe_agent(
llm,
df,
verbose=True,
allow_dangerous_code=True
)
response = python_agent.invoke("Which product category generated the highest total revenue in Q3, and what was the percentage growth over Q2?")
print(response["output"])
@tool
def parse_failed_ssh_attempts(log_file_path: str) -> str:
"""Parses auth logs to return top IP addresses with excessive failed SSH login attempts."""
# Returns formatted IP frequency report
return "Top attacking IPs: 192.168.1.105 (482 attempts), 45.33.22.11 (195 attempts)"
@tool
def generate_iptables_rule(ip_address: str) -> str:
"""Generates and applies an iptables firewall drop rule for a malicious IP address."""
return f"Successfully executed: iptables -A INPUT -s {ip_address} -j DROP"
# Agent reasons through log anomalies and autonomously issues firewall mitigation rules.
import boto3
from langchain.tools import tool
@tool
def list_unattached_ebs_volumes() -> str:
"""Scans AWS region for unattached EBS storage volumes wasting cloud budget."""
ec2 = boto3.client('ec2', region_name='us-east-1')
volumes = ec2.describe_volumes(Filters=[{'Name': 'status', 'Values': ['available']}])
vol_ids = [v['VolumeId'] for v in volumes['Volumes']]
return f"Found {len(vol_ids)} unattached volumes: {vol_ids}"
@tool
def delete_ebs_volume(volume_id: str) -> str:
"""Deletes an unattached EBS volume after confirmation."""
ec2 = boto3.client('ec2', region_name='us-east-1')
ec2.delete_volume(VolumeId=volume_id)
return f"Volume {volume_id} successfully deleted."
@tool
def fetch_github_issue(issue_number: int) -> str:
"""Fetches issue description and stack trace from GitHub repository."""
return "Issue #104: NullPointerException in payment_gateway.py line 45 when user payload lacks currency field."
@tool
def create_pull_request(branch_name: str, pr_title: str, commit_message: str) -> str:
"""Creates a git branch, commits code patch, and opens GitHub pull request."""
return f"Pull request '{pr_title}' successfully opened on branch '{branch_name}'."
@tool
def extract_invoice_pdf(pdf_path: str) -> str:
"""Extracts vendor name, line items, and total amount from invoice PDF using OCR."""
return "Vendor: CloudScale Inc, Amount: $4,250.00, PO Number: PO-99821"
@tool
def verify_purchase_order_match(po_number: str, invoice_amount: float) -> str:
"""Verifies if invoice amount matches approved purchase order in SAP/ERP system."""
return "Match verified: PO-99821 approved for $4,250.00."
@tool
def query_clinical_trials(condition: str, biomarker: str) -> str:
"""Queries clinicaltrials.gov for recruiting trials matching condition and genetic biomarker."""
return "Found 2 active Phase III trials: NCT049211 (Inclusion: EGFR mutation positive)"
@tool
def evaluate_patient_eligibility(patient_id: str, trial_id: str) -> str:
"""Compares patient EHR lab results against trial inclusion/exclusion criteria."""
return "Patient meets all inclusion criteria for trial NCT049211."
import time
class AgentCircuitBreaker:
def __init__(self, max_steps: int = 8, max_execution_time_sec: float = 30.0):
self.max_steps = max_steps
self.max_time = max_execution_time_sec
def monitor(self, start_time: float, current_step: int):
if current_step > self.max_steps:
raise RuntimeError("Circuit Breaker Tripped: Maximum reasoning steps exceeded (infinite loop risk).")
if (time.time() - start_time) > self.max_time:
raise TimeoutError("Circuit Breaker Tripped: Maximum execution time exceeded.")