{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# ReAct Implementation: Reasoning + Acting for Complex Problem Solving\n",
    "\n",
    "This notebook demonstrates the implementation and usage of ReAct (Reasoning + Acting) pattern in OpenDistillery for complex business problem solving.\n",
    "\n",
    "## What is ReAct?\n",
    "ReAct combines reasoning and acting in language models by having them:\n",
    "1. **Think** - Generate reasoning traces\n",
    "2. **Act** - Take actions based on reasoning\n",
    "3. **Observe** - Process action results\n",
    "4. **Repeat** - Continue until solution is found\n",
    "\n",
    "## Business Applications:\n",
    "- Strategic planning and analysis\n",
    "- Multi-step problem solving\n",
    "- Research and investigation\n",
    "- Complex decision making"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Setup and imports\n",
    "import requests\n",
    "import json\n",
    "import time\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "from datetime import datetime\n",
    "from typing import Dict, List, Any, Optional\n",
    "import asyncio\n",
    "import numpy as np\n",
    "\n",
    "# OpenDistillery connection\n",
    "API_BASE = \"http://localhost:8000\"\n",
    "API_KEY = \"opd_demo_enterprise_key_12345\"\n",
    "headers = {\"Authorization\": f\"Bearer {API_KEY}\", \"Content-Type\": \"application/json\"}\n",
    "\n",
    "# Configure visualization\n",
    "plt.style.use('seaborn-v0_8')\n",
    "sns.set_palette(\"husl\")\n",
    "%matplotlib inline\n",
    "\n",
    "print(\"🧠 ReAct Implementation Notebook Ready!\")\n",
    "print(f\"📅 Session: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. Understanding ReAct Components"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Define ReAct action space for business problems\n",
    "REACT_ACTIONS = {\n",
    "    \"research\": {\n",
    "        \"description\": \"Research information on a specific topic\",\n",
    "        \"parameters\": [\"topic\", \"scope\", \"sources\"],\n",
    "        \"output_format\": \"structured_data\"\n",
    "    },\n",
    "    \"analyze\": {\n",
    "        \"description\": \"Analyze data or information\",\n",
    "        \"parameters\": [\"data\", \"analysis_type\", \"metrics\"],\n",
    "        \"output_format\": \"analysis_results\"\n",
    "    },\n",
    "    \"calculate\": {\n",
    "        \"description\": \"Perform calculations or modeling\",\n",
    "        \"parameters\": [\"formula\", \"variables\", \"assumptions\"],\n",
    "        \"output_format\": \"numerical_results\"\n",
    "    },\n",
    "    \"compare\": {\n",
    "        \"description\": \"Compare options or alternatives\",\n",
    "        \"parameters\": [\"options\", \"criteria\", \"weights\"],\n",
    "        \"output_format\": \"comparison_matrix\"\n",
    "    },\n",
    "    \"synthesize\": {\n",
    "        \"description\": \"Synthesize information into insights\",\n",
    "        \"parameters\": [\"information\", \"perspective\", \"context\"],\n",
    "        \"output_format\": \"insights\"\n",
    "    },\n",
    "    \"recommend\": {\n",
    "        \"description\": \"Generate recommendations\",\n",
    "        \"parameters\": [\"analysis\", \"constraints\", \"objectives\"],\n",
    "        \"output_format\": \"recommendations\"\n",
    "    }\n",
    "}\n",
    "\n",
    "def display_react_actions():\n",
    "    \"\"\"Display available ReAct actions\"\"\"\n",
    "    print(\"🎯 Available ReAct Actions:\")\n",
    "    print(\"=\" * 50)\n",
    "    \n",
    "    for action, details in REACT_ACTIONS.items():\n",
    "        print(f\"\\n🔹 {action.upper()}\")\n",
    "        print(f\"   Description: {details['description']}\")\n",
    "        print(f\"   Parameters: {', '.join(details['parameters'])}\")\n",
    "        print(f\"   Output: {details['output_format']}\")\n",
    "\n",
    "display_react_actions()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. Business Case Study: Market Entry Strategy"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Define a complex business problem for ReAct solving\n",
    "market_entry_problem = {\n",
    "    \"problem_statement\": \"\"\"\n",
    "    TechCorp wants to enter the European SaaS market with their AI-powered \n",
    "    customer service platform. They need to determine:\n",
    "    1. Which European country to enter first\n",
    "    2. Optimal pricing strategy\n",
    "    3. Market size and competitive landscape\n",
    "    4. Required investment and timeline\n",
    "    5. Risk mitigation strategies\n",
    "    \"\"\",\n",
    "    \n",
    "    \"context\": {\n",
    "        \"company\": \"TechCorp\",\n",
    "        \"product\": \"AI-powered customer service platform\",\n",
    "        \"target_market\": \"European SaaS market\",\n",
    "        \"company_size\": \"500 employees\",\n",
    "        \"annual_revenue\": \"$50M\",\n",
    "        \"current_markets\": [\"USA\", \"Canada\"],\n",
    "        \"budget\": \"$10M for market entry\",\n",
    "        \"timeline\": \"18 months\"\n",
    "    },\n",
    "    \n",
    "    \"constraints\": {\n",
    "        \"budget_limit\": 10000000,\n",
    "        \"timeline_months\": 18,\n",
    "        \"compliance_requirements\": [\"GDPR\", \"local_regulations\"],\n",
    "        \"language_requirements\": \"local_language_support\",\n",
    "        \"team_size_limit\": 50\n",
    "    },\n",
    "    \n",
    "    \"success_criteria\": {\n",
    "        \"revenue_target\": \"$5M ARR in 24 months\",\n",
    "        \"customer_target\": \"100 enterprise customers\",\n",
    "        \"market_share\": \"5% in target segment\",\n",
    "        \"profitability\": \"Break-even in 30 months\"\n",
    "    }\n",
    "}\n",
    "\n",
    "print(\"🎯 Business Problem: Market Entry Strategy\")\n",
    "print(\"=\" * 60)\n",
    "print(f\"Company: {market_entry_problem['context']['company']}\")\n",
    "print(f\"Product: {market_entry_problem['context']['product']}\")\n",
    "print(f\"Target: {market_entry_problem['context']['target_market']}\")\n",
    "print(f\"Budget: {market_entry_problem['context']['budget']}\")\n",
    "print(f\"Timeline: {market_entry_problem['context']['timeline']}\")\n",
    "print()\n",
    "print(\"📋 Problem Statement:\")\n",
    "print(market_entry_problem['problem_statement'])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. Implementing ReAct Problem Solving"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class ReActSolver:\n",
    "    \"\"\"ReAct pattern implementation for business problem solving\"\"\"\n",
    "    \n",
    "    def __init__(self, api_base: str, api_key: str):\n",
    "        self.api_base = api_base\n",
    "        self.headers = {\"Authorization\": f\"Bearer {api_key}\", \"Content-Type\": \"application/json\"}\n",
    "        self.reasoning_trace = []\n",
    "        self.action_history = []\n",
    "        self.observation_log = []\n",
    "        \n",
    "    def think(self, problem: Dict[str, Any], context: Dict[str, Any]) -> str:\n",
    "        \"\"\"Generate reasoning trace for current state\"\"\"\n",
    "        reasoning_request = {\n",
    "            \"task_type\": \"strategic_reasoning\",\n",
    "            \"description\": \"Generate reasoning trace for problem solving step\",\n",
    "            \"input_data\": {\n",
    "                \"problem\": problem,\n",
    "                \"context\": context,\n",
    "                \"previous_actions\": self.action_history[-3:],  # Last 3 actions\n",
    "                \"reasoning_goal\": \"determine_next_action\"\n",
    "            },\n",
    "            \"reasoning_strategy\": \"chain_of_thought\",\n",
    "            \"required_capabilities\": [\"reasoning\", \"analysis\"]\n",
    "        }\n",
    "        \n",
    "        response = requests.post(\n",
    "            f\"{self.api_base}/tasks\",\n",
    "            headers=self.headers,\n",
    "            json=reasoning_request\n",
    "        )\n",
    "        \n",
    "        if response.status_code == 200:\n",
    "            result = response.json()\n",
    "            reasoning = result['result'].get('reasoning_trace', 'Continue analysis')\n",
    "            self.reasoning_trace.append({\n",
    "                \"step\": len(self.reasoning_trace) + 1,\n",
    "                \"reasoning\": reasoning,\n",
    "                \"timestamp\": datetime.now().isoformat()\n",
    "            })\n",
    "            return reasoning\n",
    "        else:\n",
    "            return \"Unable to generate reasoning - continuing with analysis\"\n",
    "    \n",
    "    def act(self, action: str, parameters: Dict[str, Any]) -> Dict[str, Any]:\n",
    "        \"\"\"Execute an action and return results\"\"\"\n",
    "        action_request = {\n",
    "            \"task_type\": f\"react_action_{action}\",\n",
    "            \"description\": f\"Execute {action} action in ReAct sequence\",\n",
    "            \"input_data\": {\n",
    "                \"action\": action,\n",
    "                \"parameters\": parameters,\n",
    "                \"context\": \"market_entry_analysis\"\n",
    "            },\n",
    "            \"required_capabilities\": [\"analysis\", \"research\"]\n",
    "        }\n",
    "        \n",
    "        response = requests.post(\n