{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Building Analyst Agents with Swarms to write Business Reports\n",
    "\n",
    "Solving a business problem often involves preparing a Business Case Report. This report comprehensively analyzes the problem, evaluates potential solutions, and provides evidence-based recommendations and an implementation plan to effectively address the issue and drive business value. While the process of preparing one requires an experienced business analyst, the workflow can be augmented using AI agents. Two candidates stick out as areas to work on:\n",
    "\n",
    "- Developing an outline to solve the problem\n",
    "- Doing background research and gathering data \n",
    "  \n",
    "In this blog, we will explore how Swarms agents can be used to tackle a busuiness problem by outlining the solution, conducting background research and generating a preliminary report.\n",
    "\n",
    "Before we proceed, this blog uses 3 API tools. Please obtain the following keys and store them in a `.env` file in the same folder as this file.\n",
    "\n",
    "- **[OpenAI API](https://openai.com/blog/openai-api)** as `OPENAI_API_KEY`\n",
    "- **[TavilyAI API](https://app.tavily.com/home)** `TAVILY_API_KEY`\n",
    "- **[KayAI API](https://www.kay.ai/)** as `KAY_API_KEY`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import dotenv\n",
    "dotenv.load_dotenv()  # Load environment variables from .env file"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Developing an Outline to solve the problem\n",
    "\n",
    "Assume the business problem is: **How do we improve Nike's revenue in Q3 2024?** We first create a planning agent to break down the problem into dependent sub-problems.\n",
    "\n",
    "\n",
    "#### Step 1. Defining the Data Model and Tool Schema\n",
    "\n",
    "Using Pydantic, we define a structure to help the agent generate sub-problems. \n",
    "\n",
    "- **QueryType:** Questions are either standalone or involve a combination of multiple others\n",
    "- **Query:** Defines structure of a question.\n",
    "- **QueryPlan:** Allows generation of a dependency graph of sub-questions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [],
   "source": [
    "import enum\n",
    "from typing import List\n",
    "from pydantic import Field, BaseModel\n",
    "\n",
    "class QueryType(str, enum.Enum):\n",
    "    \"\"\"Enumeration representing the types of queries that can be asked to a question answer system.\"\"\"\n",
    "\n",
    "    SINGLE_QUESTION = \"SINGLE\"\n",
    "    MERGE_MULTIPLE_RESPONSES = \"MERGE_MULTIPLE_RESPONSES\"\n",
    "\n",
    "class Query(BaseModel):\n",
    "    \"\"\"Class representing a single question in a query plan.\"\"\"\n",
    "\n",
    "    id: int = Field(..., description=\"Unique id of the query\")\n",
    "    question: str = Field(\n",
    "        ...,\n",
    "        description=\"Question asked using a question answering system\",\n",
    "    )\n",
    "    dependencies: List[int] = Field(\n",
    "        default_factory=list,\n",
    "        description=\"List of sub questions that need to be answered before asking this question\",\n",
    "    )\n",
    "    node_type: QueryType = Field(\n",
    "        default=QueryType.SINGLE_QUESTION,\n",
    "        description=\"Type of question, either a single question or a multi-question merge\",\n",
    "    )\n",
    "\n",
    "class QueryPlan(BaseModel):\n",
    "    \"\"\"Container class representing a tree of questions to ask a question answering system.\"\"\"\n",
    "\n",
    "    query_graph: List[Query] = Field(\n",
    "        ..., description=\"The query graph representing the plan\"\n",
    "    )\n",
    "\n",
    "    def _dependencies(self, ids: List[int]) -> List[Query]:\n",
    "        \"\"\"Returns the dependencies of a query given their ids.\"\"\"\n",
    "        \n",
    "        return [q for q in self.query_graph if q.id in ids]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Also, a `tool_schema` needs to be defined. It is an instance of `QueryPlan` and is used to initialize the agent."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [],
   "source": [
    "tool_schema = QueryPlan(\n",
    "    query_graph = [query.dict() for query in [\n",
    "        Query(\n",
    "            id=1,\n",
    "            question=\"How do we improve Nike's revenue in Q3 2024?\",\n",
    "            dependencies=[2],\n",
    "            node_type=QueryType('SINGLE')\n",
    "        ),\n",
    "        # ... other queries ...\n",
    "    ]]\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Step 2. Defining the Planning Agent\n",
    "\n",
    "We specify the query, task specification and an appropriate system prompt."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [],
   "source": [
    "from swarms import OpenAIChat\n",
    "from swarms import Agent\n",
    "\n",
    "query = \"How do we improve Nike's revenue in Q3 2024?\"\n",
    "task = f\"Consider: {query}. Generate just the correct query plan in JSON format.\"\n",
    "system_prompt = (\n",
    "        \"You are a world class query planning algorithm \" \n",
    "        \"capable of breaking apart questions into its \" \n",
    "        \"dependency queries such that the answers can be \" \n",
    "        \"used to inform the parent question. Do not answer \" \n",
    "        \"the questions, simply provide a correct compute \" \n",
    "        \"graph with good specific questions to ask and relevant \" \n",
    "        \"dependencies. Before you call the function, think \" \n",
    "        \"step-by-step to get a better understanding of the problem.\"\n",
    "    )\n",
    "llm = OpenAIChat(\n",
    "    temperature=0.0, model_name=\"gpt-4\", max_tokens=4000\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Then, we proceed with agent definition."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Initialize the agent\n",
    "agent = Agent(\n",
    "    agent_name=\"Query Planner\",\n",
    "    system_prompt=system_prompt,\n",
    "    # Set the tool schema to the JSON string -- this is the key difference\n",
    "    tool_schema=tool_schema,\n",
    "    llm=llm,\n",
    "    max_loops=1,\n",
    "    autosave=True,\n",
    "    dashboard=False,\n",
    "    streaming_on=True,\n",
    "    verbose=True,\n",
    "    interactive=False,\n",
    "    # Set the output type to the tool schema which is a BaseModel\n",
    "    output_type=tool_schema, # or dict, or str\n",
    "    metadata_output_type=\"json\",\n",
    "    # List of schemas that the agent can handle\n",
    "    list_tool_schemas=[tool_schema],\n",
    "    function_calling_format_type=\"OpenAI\",\n",
    "    function_calling_type=\"json\", # or soon yaml\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Step 3. Obtaining Outline from Planning Agent \n",
    "\n",
    "We now run the agent, and since its output is in JSON format, we can load it as a dictionary."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[33mInitializing Autonomous Agent Query Planner...\u001b[0m\n",
      "\u001b[1m\u001b[36mAutonomous Agent Activated.\u001b[0m\n",
      "\u001b[32mAll systems operational. Executing task...\u001b[0m\n",
      "\u001b[36m\n",
      "Loop 1 of 1\u001b[0m\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "content='{\\n  \"main_query\": \"How do we improve Nike\\'s revenue in Q3 2024?\",\\n  \"sub_queries\": [\\n    {\\n      \"id\": \"1\",\\n      \"query\": \"What is Nike\\'s current revenue trend?\"\\n    },\\n    {\\n      \"id\": \"2\",\\n      \"query\": \"What are the projected market trends for the sports apparel industry in 2024?\"\\n    },\\n    {\\n      \"id\": \"3\",\\n      \"query\": \"What are the current successful strategies being used by Nike\\'s competitors?\",\\n      \"dependencies\": [\"2\"]\\n    },\\n    {\\n      \"id\": \"4\",\\n      \"query\": \"What are the current and projected economic conditions in Nike\\'s major markets?\",\\n      \"dependencies\": [\"2\"]\\n    },\\n    {\\n      \"id\": \"5\",\\n      \"query\": \"What are the current consumer preferences in the sports apparel industry?\",\\n      \"dependencies\": [\"2\"]\\n    },\\n    {\\n      \"id\": \"6\",\\n      \"query\": \"What are the potential areas of improvement in Nike\\'s current business model?\",\\n      \"dependencies\": [\"1\"]\\n    },\\n    {\\n      \"id\": \"7\",\\n      \"query\": \"What are the potential new markets for Nike to explore in 2024?\",\\n      \"dependencies\": [\"2\", \"4\"]\\n    },\\n    {\\n      \"id\": \"8\",\\n      \"query\": \"What are the potential new products or services Nike could introduce in 2024?\",\\n      \"dependencies\": [\"5\"]\\n    },\\n    {\\n      \"id\": \"9\",\\n      \"query\": \"What are the potential marketing strategies Nike could use to increase its revenue in Q3 2024?\",\\n      \"dependencies\": [\"3\", \"5\", \"7\", \"8\"]\\n    },\\n    {\\n      \"id\": \"10\",\\n      \"query\": \"What are the potential cost-saving strategies Nike could implement to increase its net revenue in Q3 2024?\",\\n      \"dependencies\": [\"6\"]\\n    }\\n  ]\\n}' response_metadata={'token_usage': {'completion_tokens': 408, 'prompt_tokens': 108, 'total_tokens': 516}, 'model_name': 'gpt-4', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None}\n",
      "\u001b[32mSaved agent state to: Query Planner_state.json\u001b[0m\n"
     ]
    }
   ],
   "source": [
    "generated_data = agent.run(task)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "At times the agent could return extra content other than JSON. Below function will filter it out."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "def process_json_output(content):\n",
    "    # Find the index of the first occurrence of '```json\\n'\n",
    "    start_index = content.find('```json\\n')\n",
    "    if start_index == -1:\n",
    "        # If '```json\\n' is not found, return the original content\n",
    "        return content\n",
    "    # Return the part of the content after '```json\\n' and remove the '```' at the end\n",
    "    return content[start_index + len('```json\\n'):].rstrip('`')\n",
    "\n",
    "# Use the function to clean up the output\n",
    "json_content = process_json_output(generated_data.content)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\n",
      "  \"main_query\": \"How do we improve Nike's revenue in Q3 2024?\",\n",
      "  \"sub_queries\": [\n",
      "    {\n",
      "      \"id\": \"1\",\n",
      "      \"query\": \"What is Nike's current revenue trend?\"\n",
      "    },\n",
      "    {\n",
      "      \"id\": \"2\",\n",
      "      \"query\": \"What are the projected market trends for the sports apparel industry in 2024?\"\n",
      "    },\n",
      "    {\n",
      "      \"id\": \"3\",\n",
      "      \"query\": \"What are the current successful strategies being used by Nike's competitors?\",\n",
      "      \"dependencies\": [\n",
      "        \"2\"\n",
      "      ]\n",
      "    },\n",
      "    {\n",
      "      \"id\": \"4\",\n",
      "      \"query\": \"What are the current and projected economic conditions in Nike's major markets?\",\n",
      "      \"dependencies\": [\n",
      "        \"2\"\n",
      "      ]\n",
      "    },\n",
      "    {\n",
      "      \"id\": \"5\",\n",
      "      \"query\": \"What are the current consumer preferences in the sports apparel industry?\",\n",
      "      \"dependencies\": [\n",
      "        \"2\"\n",
      "      ]\n",
      "    },\n",
      "    {\n",
      "      \"id\": \"6\",\n",
      "      \"query\": \"What are the potential areas of improvement in Nike's current business model?\",\n",
      "      \"dependencies\": [\n",
      "        \"1\"\n",
      "      ]\n",
      "    },\n",
      "    {\n",
      "      \"id\": \"7\",\n",
      "      \"query\": \"What are the potential new markets for Nike to explore in 2024?\",\n",
      "      \"dependencies\": [\n",
      "        \"2\",\n",
      "        \"4\"\n",
      "      ]\n",
      "    },\n",
      "    {\n",
      "      \"id\": \"8\",\n",
      "      \"query\": \"What are the potential new products or services Nike could introduce in 2024?\",\n",
      "      \"dependencies\": [\n",
      "        \"5\"\n",
      "      ]\n",
      "    },\n",
      "    {\n",
      "      \"id\": \"9\",\n",
      "      \"query\": \"What are the potential marketing strategies Nike could use to increase its revenue in Q3 2024?\",\n",
      "      \"dependencies\": [\n",
      "        \"3\",\n",
      "        \"5\",\n",
      "        \"7\",\n",
      "        \"8\"\n",
      "      ]\n",
      "    },\n",
      "    {\n",
      "      \"id\": \"10\",\n",
      "      \"query\": \"What are the potential cost-saving strategies Nike could implement to increase its net revenue in Q3 2024?\",\n",
      "      \"dependencies\": [\n",
      "        \"6\"\n",
      "      ]\n",
      "    }\n",
      "  ]\n",
      "}\n"
     ]
    }
   ],
   "source": [
    "import json\n",
    "\n",
    "# Load the JSON string into a Python object\n",
    "json_object = json.loads(json_content)\n",
    "\n",
    "# Convert the Python object back to a JSON string\n",
    "json_content = json.dumps(json_object, indent=2)\n",
    "\n",
    "# Print the JSON string\n",
    "print(json_content)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The JSON dictionary is not convenient for humans to process. We make a directed graph out of it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 200272 characters]",
      "text/plain": [
       "<Figure size 640x480 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "import networkx as nx\n",
    "import matplotlib.pyplot as plt\n",
    "import textwrap\n",
    "import random\n",
    "\n",
    "# Create a directed graph\n",
    "G = nx.DiGraph()\n",
    "\n",
    "# Define a color map\n",
    "color_map = {}\n",
    "\n",
    "# Add nodes and edges to the graph\n",
    "for sub_query in json_object['sub_queries']:\n",
    "    # Check if 'dependencies' key exists in sub_query, if not, initialize it as an empty list\n",
    "    if 'dependencies' not in sub_query:\n",
    "        sub_query['dependencies'] = []\n",
    "    # Assign a random color for each node\n",
    "    color_map[sub_query['id']] = \"#{:06x}\".format(random.randint(0, 0xFFFFFF))\n",
    "    G.add_node(sub_query['id'], label=textwrap.fill(sub_query['query'], width=20))\n",
    "    for dependency in sub_query['dependencies']:\n",
    "        G.add_edge(dependency, sub_query['id'])\n",
    "\n",
    "# Draw the graph\n",
    "pos = nx.spring_layout(G)\n",
    "nx.draw(G, pos, with_labels=True, node_size=800, node_color=[color_map[node] for node in G.nodes()], node_shape=\"o\", alpha=0.5, linewidths=40)\n",
    "\n",
    "# Prepare labels for legend\n",
    "labels = nx.get_node_attributes(G, 'label')\n",
    "handles = [plt.Line2D([0], [0], marker='o', color=color_map[node], label=f\"{node}: {label}\", markersize=10, linestyle='None') for node, label in labels.items()]\n",
    "\n",
    "# Create a legend\n",
    "plt.legend(handles=handles, title=\"Queries\", bbox_to_anchor=(1.05, 1), loc='upper left')\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Doing Background Research and Gathering Data\n",
    "\n",
    "At this point, we have solved the first half of the problem. We have an outline consisting of sub-problems to to tackled to solve our business problem. This will form the overall structure of our report. We now need to research information for each sub-problem in order to write an informed report. This mechanically intensive and is the aspect that will most benefit from Agentic intervention. \n",
    "\n",
    "Essentially, we can spawn parallel agents to gather the data. Each agent will have 2 tools:\n",
    "\n",
    "- Internet access\n",
    "- Financial data retrieval\n",
    "\n",
    "As they run parallely, they will add their knowledge into a common long-term memory. We will then spawn a separate report writing agent with access to this memory to generate our business case report.\n",
    "\n",
    "#### Step 4. Defining Tools for Worker Agents\n",
    "\n",
    "Let us first define the 2 tools. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "from typing import List, Dict\n",
    "\n",
    "from swarms import tool\n",
    "\n",
    "os.environ['TAVILY_API_KEY'] = os.getenv('TAVILY_API_KEY')\n",
    "os.environ[\"KAY_API_KEY\"] = os.getenv('KAY_API_KEY')\n",
    "\n",
    "from langchain_community.tools.tavily_search import TavilySearchResults\n",
    "from langchain_core.pydantic_v1 import BaseModel, Field\n",
    "\n",
    "from kay.rag.retrievers import KayRetriever\n",
    "\n",
    "@tool\n",
    "def browser(query: str) -> str:\n",
    "    \"\"\"\n",
    "    Search the query in the browser with the Tavily API tool.\n",
    "    Args:\n",
    "        query (str): The query to search in the browser.\n",
    "    Returns:\n",
    "        str: The search results\n",
    "    \"\"\"\n",
    "    internet_search = TavilySearchResults()\n",
    "    results =  internet_search.invoke({\"query\": query})\n",
    "    response = '' \n",
    "    for result in results:\n",
    "        response += (result['content'] + '\\n')\n",
    "    return response\n",
    "\n",
    "@tool\n",
    "def kay_retriever(query: str) -> str:\n",
    "    \"\"\"\n",
    "    Search the financial data query with the KayAI API tool.\n",
    "    Args:\n",
    "        query (str): The query to search in the KayRetriever.\n",
    "    Returns:\n",
    "        str: The first context retrieved as a string.\n",
    "    \"\"\"\n",
    "    # Initialize the retriever\n",
    "    retriever = KayRetriever(dataset_id = \"company\",  data_types=[\"10-K\", \"10-Q\", \"8-K\", \"PressRelease\"])\n",
    "    # Query the retriever\n",
    "    context = retriever.query(query=query,num_context=1)\n",
    "    return context[0]['chunk_embed_text']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Step 5. Defining Long-Term Memory\n",
    "\n",
    "As mentioned previously, the worker agents running parallely, will pool their knowledge into a common memory. Let us define that.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 174,
   "metadata": {},
   "outputs": [],
   "source": [
    "import logging\n",
    "import os\n",
    "import uuid\n",
    "from typing import Callable, List, Optional\n",
    "\n",
    "import chromadb\n",
    "import numpy as np\n",
    "from dotenv import load_dotenv\n",
    "\n",
    "from swarms.utils.data_to_text import data_to_text\n",
    "from swarms.utils.markdown_message import display_markdown_message\n",
    "from swarms.memory.base_vectordb import AbstractVectorDatabase\n",
    "\n",
    "# Load environment variables\n",
    "load_dotenv()\n",
    "\n",
    "# Results storage using local ChromaDB\n",
    "class ChromaDB(AbstractVectorDatabase):\n",
    "    \"\"\"\n",
    "\n",
    "    ChromaDB database\n",
    "\n",
    "    Args:\n",
    "        metric (str): The similarity metric to use.\n",
    "        output (str): The name of the collection to store the results in.\n",
    "        limit_tokens (int, optional): The maximum number of tokens to use for the query. Defaults to 1000.\n",
    "        n_results (int, optional): The number of results to retrieve. Defaults to 2.\n",
    "\n",
    "    Methods:\n",
    "        add: _description_\n",
    "        query: _description_\n",
    "\n",
    "    Examples:\n",
    "        >>> chromadb = ChromaDB(\n",
    "        >>>     metric=\"cosine\",\n",
    "        >>>     output=\"results\",\n",
    "        >>>     llm=\"gpt3\",\n",
    "        >>>     openai_api_key=OPENAI_API_KEY,\n",
    "        >>> )\n",
    "        >>> chromadb.add(task, result, result_id)\n",
    "    \"\"\"\n",
    "\n",
    "    def __init__(\n",
    "        self,\n",
    "        metric: str = \"cosine\",\n",
    "        output_dir: str = \"swarms\",\n",
    "        limit_tokens: Optional[int] = 1000,\n",
    "        n_results: int = 3,\n",
    "        embedding_function: Callable = None,\n",
    "        docs_folder: str = None,\n",
    "        verbose: bool = False,\n",
    "        *args,\n",
    "        **kwargs,\n",
    "    ):\n",
    "        self.metric = metric\n",
    "        self.output_dir = output_dir\n",
    "        self.limit_tokens = limit_tokens\n",
    "        self.n_results = n_results\n",
    "        self.docs_folder = docs_folder\n",
    "        self.verbose = verbose\n",
    "\n",
    "        # Disable ChromaDB logging\n",
    "        if verbose:\n",
    "            logging.getLogger(\"chromadb\").setLevel(logging.INFO)\n",
    "\n",
    "        # Create Chroma collection\n",
    "        chroma_persist_dir = \"chroma\"\n",
    "        chroma_client = chromadb.PersistentClient(\n",
    "            settings=chromadb.config.Settings(\n",
    "                persist_directory=chroma_persist_dir,\n",
    "            ),\n",
    "            *args,\n",
    "            **kwargs,\n",
    "        )\n",
    "\n",
    "        # Embedding model\n",
    "        if embedding_function:\n",
    "            self.embedding_function = embedding_function\n",
    "        else:\n",
    "            self.embedding_function = None\n",
    "\n",
    "        # Create ChromaDB client\n",
    "        self.client = chromadb.Client()\n",
    "\n",
    "        # Create Chroma collection\n",
    "        self.collection = chroma_client.get_or_create_collection(\n",
    "            name=output_dir,\n",
    "            metadata={\"hnsw:space\": metric},\n",
    "            embedding_function=self.embedding_function,\n",
    "            # data_loader=self.data_loader,\n",
    "            *args,\n",
    "            **kwargs,\n",
    "        )\n",
    "        display_markdown_message(\n",
    "            \"ChromaDB collection created:\"\n",
    "            f\" {self.collection.name} with metric: {self.metric} and\"\n",
    "            f\" output directory: {self.output_dir}\"\n",
    "        )\n",
    "\n",
    "        # If docs\n",
    "        if docs_folder:\n",
    "            display_markdown_message(\n",
    "                f\"Traversing directory: {docs_folder}\"\n",
    "            )\n",
    "            self.traverse_directory()\n",
    "\n",
    "    def add(\n",
    "        self,\n",
    "        document: str,\n",
    "        *args,\n",
    "        **kwargs,\n",
    "    ):\n",
    "        \"\"\"\n",
    "        Add a document to the ChromaDB collection.\n",
    "\n",
    "        Args:\n",
    "            document (str): The document to be added.\n",
    "            condition (bool, optional): The condition to check before adding the document. Defaults to True.\n",
    "\n",
    "        Returns:\n",
    "            str: The ID of the added document.\n",
    "        \"\"\"\n",
    "        try:\n",
    "            doc_id = str(uuid.uuid4())\n",
    "            self.collection.add(\n",
    "                ids=[doc_id],\n",
    "                documents=[document],\n",
    "                *args,\n",
    "                **kwargs,\n",
    "            )\n",
    "            print('-----------------')\n",
    "            print(\"Document added successfully\")\n",
    "            print('-----------------')\n",
    "            return doc_id\n",
    "        except Exception as e:\n",
    "            raise Exception(f\"Failed to add document: {str(e)}\")\n",
    "\n",
    "    def query(\n",
    "        self,\n",
    "        query_text: str,\n",
    "        *args,\n",
    "        **kwargs,\n",
    "    ):\n",
    "        \"\"\"\n",
    "        Query documents from the ChromaDB collection.\n",
    "\n",
    "        Args:\n",
    "            query (str): The query string.\n",
    "            n_docs (int, optional): The number of documents to retrieve. Defaults to 1.\n",
    "\n",
    "        Returns:\n",
    "            dict: The retrieved documents.\n",
    "        \"\"\"\n",
    "        try:\n",
    "            docs = self.collection.query(\n",
    "                query_texts=[query_text],\n",
    "                n_results=self.n_results,\n",
    "                *args,\n",
    "                **kwargs,\n",
    "            )[\"documents\"]\n",
    "            return docs[0]\n",
    "        except Exception as e:\n",
    "            raise Exception(f\"Failed to query documents: {str(e)}\")\n",
    "\n",
    "    def traverse_directory(self):\n",
    "        \"\"\"\n",
    "        Traverse through every file in the given directory and its subdirectories,\n",
    "        and return the paths of all files.\n",
    "        Parameters:\n",
    "        - directory_name (str): The name of the directory to traverse.\n",
    "        Returns:\n",
    "        - list: A list of paths to each file in the directory and its subdirectories.\n",
    "        \"\"\"\n",
    "        added_to_db = False\n",
    "\n",
    "        for root, dirs, files in os.walk(self.docs_folder):\n",
    "            for file in files:\n",
    "                file = os.path.join(self.docs_folder, file)\n",
    "                _, ext = os.path.splitext(file)\n",
    "                data = data_to_text(file)\n",
    "                added_to_db = self.add([data])\n",
    "                print(f\"{file} added to Database\")\n",
    "\n",
    "        return added_to_db"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can now proceed to initialize the memory."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 175,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[36mChromaDB collection created: results with metric: cosine and output directory: results\u001b[0m\n"
     ]
    }
   ],
   "source": [
    "from chromadb.utils import embedding_functions\n",
    "default_ef = embedding_functions.DefaultEmbeddingFunction()\n",
    "\n",
    "memory = ChromaDB(\n",
    "    metric=\"cosine\",\n",
    "    n_results=3,\n",
    "    output_dir=\"results\",\n",
    "    embedding_function=default_ef\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Step 6. Defining Worker Agents \n",
    "\n",
    "The Worker Agent sub-classes the `Agent` class. The only different between these 2 is in how the `run()` method works. In the `Agent` class, `run()` simply returns the set of tool commands to run, but does not execute it. We, however, desire this. In addition, after we run our tools, we get the relevant information as output. We want to add this information to our memory. Hence, to incorporate these 2 changes, we define `WorkerAgent` as follows."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 176,
   "metadata": {},
   "outputs": [],
   "source": [
    "class WorkerAgent(Agent):\n",
    "    def __init__(self, *args, **kwargs):\n",
    "        super().__init__(*args, **kwargs)\n",
    "    \n",
    "    def run(self, task, *args, **kwargs):\n",
    "        response = super().run(task, *args, **kwargs)\n",
    "        print(response.content)\n",
    "\n",
    "        json_dict = json.loads(process_json_output(response.content))\n",
    "\n",
    "        #print(json.dumps(json_dict, indent=2))\n",
    "        \n",
    "        if response!=None:\n",
    "            try:\n",
    "                commands = json_dict[\"commands\"]\n",
    "            except:\n",
    "                commands = [json_dict['command']]\n",
    "                \n",
    "            for command in commands:\n",
    "                tool_name = command[\"name\"]\n",
    "\n",
    "                if tool_name not in ['browser', 'kay_retriever']:\n",
    "                    continue\n",
    "                \n",
    "                query = command[\"args\"][\"query\"]\n",
    "\n",
    "                # Get the tool by its name\n",
    "                tool = globals()[tool_name]\n",
    "                tool_response = tool(query)\n",
    "\n",
    "                # Add tool's output to long term memory\n",
    "                self.long_term_memory.add(tool_response)\n",
    "    "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can then instantiate an object of the `WorkerAgent` class."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 177,
   "metadata": {},
   "outputs": [],
   "source": [
    "worker_agent = WorkerAgent(\n",
    "    agent_name=\"Worker Agent\",\n",
    "    system_prompt=(\n",
    "        \"Autonomous agent that can interact with browser, \"\n",
    "        \"financial data retriever and other agents. Be Helpful \" \n",
    "        \"and Kind. Use the tools provided to assist the user. \"\n",
    "        \"Generate the plan with list of commands in JSON format.\"\n",
    "    ),\n",
    "    llm=OpenAIChat(\n",
    "    temperature=0.0, model_name=\"gpt-4\", max_tokens=4000\n",
    "),\n",
    "    max_loops=\"auto\",\n",
    "    autosave=True,\n",
    "    dashboard=False,\n",
    "    streaming_on=True,\n",
    "    verbose=True,\n",
    "    stopping_token=\"<DONE>\",\n",
    "    interactive=True,\n",
    "    tools=[browser, kay_retriever],\n",
    "    long_term_memory=memory,\n",
    "    code_interpreter=True,\n",
    ")"
   ]
  },
  {
   "attachments": {
    "query-plan-mini.png": {
     "image/png": "[encoded data, 166908 characters]"
    }
   },
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "#### Step 7. Running the Worker Agents\n",
    "\n",
    "At this point, we need to setup a concurrent workflow. While the order of adding tasks to the workflow doesn't matter (since they will all run concurrently late when executed), we can take some time to define an order for these tasks. This order will come in handy later when writing the report using our Writer Agent. \n",
    "\n",
    "The order we will follow is Breadth First Traversal (BFT) of the sub-queries in the graph we had made earlier (shown below again for reference). BFT makes sense to be used here because we want all the dependent parent questions to be answered before answering the child question. Also, since we could have independent subgraphs, we will also perform BFT separately on each subgraph. \n",
    "\n",
    "\n",
    "![query-plan-mini.png](attachment:query-plan-mini.png)\n",
    "\n",
    "Below is the code that produces the order of processing sub-queries."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 178,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "BFS Order: ['1', '6', '10', '2', '3', '4', '5', '7', '8', '9']\n"
     ]
    }
   ],
   "source": [
    "from collections import deque, defaultdict\n",
    "\n",
    "# Define the graph nodes\n",
    "nodes = json_object['sub_queries']\n",
    "\n",
    "# Create a graph from the nodes\n",
    "graph = defaultdict(list)\n",
    "for node in nodes:\n",
    "    for dependency in node['dependencies']:\n",
    "        graph[dependency].append(node['id'])\n",
    "\n",
    "# Find all nodes with no dependencies (potential starting points)\n",
    "start_nodes = [node['id'] for node in nodes if not node['dependencies']]\n",
    "\n",
    "# Adjust the BFT function to handle dependencies correctly\n",
    "def bft_corrected(start, graph, nodes_info):\n",
    "    visited = set()\n",
    "    queue = deque([start])\n",
    "    order = []\n",
    "    \n",
    "    while queue:\n",
    "        node = queue.popleft()\n",
    "        if node not in visited:\n",
    "            # Check if all dependencies of the current node are visited\n",
    "            node_dependencies = [n['id'] for n in nodes if n['id'] == node][0]\n",
    "            dependencies_met = all(dep in visited for dep in nodes_info[node_dependencies]['dependencies'])\n",
    "            \n",
    "            if dependencies_met:\n",
    "                visited.add(node)\n",
    "                order.append(node)\n",
    "                # Add only nodes to the queue whose dependencies are fully met\n",
    "                for next_node in graph[node]:\n",
    "                    if all(dep in visited for dep in nodes_info[next_node]['dependencies']):\n",
    "                        queue.append(next_node)\n",
    "            else:\n",
    "                # Requeue the node to check dependencies later\n",
    "                queue.append(node)\n",
    "    \n",
    "    return order\n",
    "\n",
    "# Dictionary to access node information quickly\n",
    "nodes_info = {node['id']: node for node in nodes}\n",
    "\n",
    "# Perform BFt for each unvisited start node using the corrected BFS function\n",
    "visited_global = set()\n",
    "bfs_order = []\n",
    "\n",
    "for start in start_nodes:\n",
    "    if start not in visited_global:\n",
    "        order = bft_corrected(start, graph, nodes_info)\n",
    "        bfs_order.extend(order)\n",
    "        visited_global.update(order)\n",
    "\n",
    "print(\"BFS Order:\", bfs_order)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, let's define our `ConcurrentWorkflow` and run it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 179,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "-----------------\n",
      "Added task:  What is Nike's current revenue trend?\n",
      "-----------------\n",
      "-----------------\n",
      "Added task:  What are the potential areas of improvement in Nike's current business model?\n",
      "-----------------\n",
      "-----------------\n",
      "Added task:  What are the potential cost-saving strategies Nike could implement to increase its net revenue in Q3 2024?\n",
      "-----------------\n",
      "-----------------\n",
      "Added task:  What are the projected market trends for the sports apparel industry in 2024?\n",
      "-----------------\n",
      "-----------------\n",
      "Added task:  What are the current successful strategies being used by Nike's competitors?\n",
      "-----------------\n",
      "-----------------\n",
      "Added task:  What are the current and projected economic conditions in Nike's major markets?\n",
      "-----------------\n",
      "-----------------\n",
      "Added task:  What are the current consumer preferences in the sports apparel industry?\n",
      "-----------------\n",
      "-----------------\n",
      "Added task:  What are the potential new markets for Nike to explore in 2024?\n",
      "-----------------\n",
      "-----------------\n",
      "Added task:  What are the potential new products or services Nike could introduce in 2024?\n",
      "-----------------\n",
      "-----------------\n",
      "Added task:  What are the potential marketing strategies Nike could use to increase its revenue in Q3 2024?\n",
      "-----------------\n",
      "\u001b[33mInitializing Autonomous Agent Worker Agent...\u001b[0m\n",
      "\u001b[1m\u001b[36mAutonomous Agent Activated.\u001b[0m\n",
      "\u001b[32mAll systems operational. Executing task...\u001b[0m\n",
      "\u001b[36m\n",
      "Loop 1 of auto\u001b[0m\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\u001b[33mInitializing Autonomous Agent Worker Agent...\u001b[0m\n",
      "\u001b[1m\u001b[36mAutonomous Agent Activated.\u001b[0m\n",
      "\u001b[32mAll systems operational. Executing task...\u001b[0m\n",
      "\u001b[36m\n",
      "Loop 1 of auto\u001b[0m\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\u001b[33mInitializing Autonomous Agent Worker Agent...\u001b[0m\n",
      "\u001b[1m\u001b[36mAutonomous Agent Activated.\u001b[0m\n",
      "\u001b[32mAll systems operational. Executing task...\u001b[0m\n",
      "\u001b[36m\n",
      "Loop 1 of auto\u001b[0m\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\u001b[33mInitializing Autonomous Agent Worker Agent...\u001b[0m\n",
      "\u001b[1m\u001b[36mAutonomous Agent Activated.\u001b[0m\n",
      "\u001b[32mAll systems operational. Executing task...\u001b[0m\n",
      "\u001b[36m\n",
      "Loop 1 of auto\u001b[0m\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\u001b[33mInitializing Autonomous Agent Worker Agent...\u001b[0m\n",
      "\u001b[1m\u001b[36mAutonomous Agent Activated.\u001b[0m\n",
      "\u001b[32mAll systems operational. Executing task...\u001b[0m\n",
      "\u001b[36m\n",
      "Loop 1 of auto\u001b[0m\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "content='```json\\n{\\n  \"thoughts\": {\\n    \"text\": \"To find out Nike\\'s current revenue trend, I will use the financial data retriever tool to search for \\'Nike revenue trend\\'.\",\\n    \"reasoning\": \"The financial data retriever tool allows me to search for specific financial data, so I can look up the current revenue trend of Nike.\", \\n    \"plan\": \"Use the financial data retriever tool to search for \\'Nike revenue trend\\'. Parse the result to get the current revenue trend and format that into a readable report.\"\\n  },\\n  \"command\": {\\n    \"name\": \"kay_retriever\", \\n    \"args\": {\\n      \"query\": \"Nike revenue trend\"\\n    }\\n  }\\n}\\n```' response_metadata={'token_usage': {'completion_tokens': 152, 'prompt_tokens': 1527, 'total_tokens': 1679}, 'model_name': 'gpt-4', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None}\n",
      "content='To answer these questions, we need to retrieve financial data for Nike and analyze it. We will use the `kay_retriever` tool to fetch the data and then analyze it to understand the revenue trend and potential areas of improvement.\\n\\nHere is the plan:\\n\\n1. Use `kay_retriever` to fetch Nike\\'s financial data.\\n2. Analyze the data to understand the revenue trend.\\n3. Identify potential areas of improvement in Nike\\'s business model.\\n\\nLet\\'s start with the first step.\\n\\n```json\\n{\\n  \"thoughts\": {\\n    \"text\": \"To understand Nike\\'s current revenue trend and potential areas of improvement, I need to fetch Nike\\'s financial data.\",\\n    \"reasoning\": \"The kay_retriever tool allows me to fetch financial data, so I can look up Nike\\'s financial information.\", \\n    \"plan\": \"Use the kay_retriever tool to fetch Nike\\'s financial data. Analyze the data to understand the revenue trend and potential areas of improvement.\"\\n  },\\n  \"command\": {\\n    \"name\": \"kay_retriever\", \\n    \"args\": {\\n      \"query\": \"Nike financial data\"\\n    }\\n  }\\n}\\n```\\n\\nAfter executing this command, we will have the financial data for Nike. We can then analyze this data to understand the revenue trend and potential areas of improvement.' response_metadata={'token_usage': {'completion_tokens': 275, 'prompt_tokens': 1543, 'total_tokens': 1818}, 'model_name': 'gpt-4', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None}\n",
      "content='```json\\n{\\n  \"thoughts\": {\\n    \"text\": \"To find out Nike\\'s current revenue trend, I will use the financial data retriever tool to search for \\'Nike revenue trend\\'.\",\\n    \"reasoning\": \"The financial data retriever tool allows me to search for specific financial data, so I can look up the current revenue trend of Nike.\", \\n    \"plan\": \"Use the financial data retriever tool to search for \\'Nike revenue trend\\'. Parse the result to get the current revenue trend and format that into a readable report.\"\\n  },\\n  \"command\": {\\n    \"name\": \"kay_retriever\", \\n    \"args\": {\\n      \"query\": \"Nike revenue trend\"\\n    }\\n  }\\n}\\n```' response_metadata={'token_usage': {'completion_tokens': 152, 'prompt_tokens': 1527, 'total_tokens': 1679}, 'model_name': 'gpt-4', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None}\n",
      "content='Assistant:: \\n```json\\n{\\n  \"thoughts\": {\\n    \"text\": \"To find Nike\\'s current revenue trend, I will use the financial data retriever tool to search for \\'Nike revenue trend\\'.\",\\n    \"reasoning\": \"The financial data retriever tool allows me to search for specific financial data, so I can look up the current revenue trend of Nike.\", \\n    \"plan\": \"Use the financial data retriever tool to search for \\'Nike revenue trend\\'. Parse the result to get the current revenue trend and format that into a readable report.\"\\n  },\\n  \"command\": {\\n    \"name\": \"kay_retriever\", \\n    \"args\": {\\n      \"query\": \"Nike revenue trend\"\\n    }\\n  }\\n}\\n```\\n\\n```json\\n{\\n  \"thoughts\": {\\n    \"text\": \"To find potential areas of improvement in Nike\\'s current business model, I will use the browser tool to search for \\'Nike business model analysis\\'.\",\\n    \"reasoning\": \"The browser tool allows me to search the web, so I can look up analysis and reports on Nike\\'s current business model.\", \\n    \"plan\": \"Use the browser tool to search Google for \\'Nike business model analysis\\'. Parse the result to get the potential areas of improvement and format that into a readable report.\"\\n  },\\n  \"command\": {\\n    \"name\": \"browser\", \\n    \"args\": {\\n      \"query\": \"Nike business model analysis\"\\n    }\\n  }\\n}\\n```\\n\\n```json\\n{\\n  \"thoughts\": {\\n    \"text\": \"To find potential cost-saving strategies Nike could implement to increase its net revenue in Q3 2024, I will use the browser tool to search for \\'Nike cost-saving strategies\\'.\",\\n    \"reasoning\": \"The browser tool allows me to search the web, so I can look up potential cost-saving strategies that Nike could implement.\", \\n    \"plan\": \"Use the browser tool to search Google for \\'Nike cost-saving strategies\\'. Parse the result to get the potential strategies and format that into a readable report.\"\\n  },\\n  \"command\": {\\n    \"name\": \"browser\", \\n    \"args\": {\\n      \"query\": \"Nike cost-saving strategies\"\\n    }\\n  }\\n}\\n```' response_metadata={'token_usage': {'completion_tokens': 459, 'prompt_tokens': 1567, 'total_tokens': 2026}, 'model_name': 'gpt-4', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None}\n",
      "content='```json\\n{\\n  \"thoughts\": {\\n    \"text\": \"To find out Nike\\'s current revenue trend, I will use the financial data retriever tool to search for \\'Nike revenue trend\\'.\",\\n    \"reasoning\": \"The financial data retriever tool allows me to search for specific financial data, so I can look up the current revenue trend of Nike.\", \\n    \"plan\": \"Use the financial data retriever tool to search for \\'Nike revenue trend\\'. Parse the result to get the current revenue trend and format that into a readable report.\"\\n  },\\n  \"command\": {\\n    \"name\": \"kay_retriever\", \\n    \"args\": {\\n      \"query\": \"Nike revenue trend\"\\n    }\\n  }\\n}\\n```' response_metadata={'token_usage': {'completion_tokens': 152, 'prompt_tokens': 1527, 'total_tokens': 1679}, 'model_name': 'gpt-4', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None}\n",
      "\u001b[32mSaved agent state to: Worker Agent_state.json\u001b[0m\n",
      "```json\n",
      "{\n",
      "  \"thoughts\": {\n",
      "    \"text\": \"To find out Nike's current revenue trend, I will use the financial data retriever tool to search for 'Nike revenue trend'.\",\n",
      "    \"reasoning\": \"The financial data retriever tool allows me to search for specific financial data, so I can look up the current revenue trend of Nike.\", \n",
      "    \"plan\": \"Use the financial data retriever tool to search for 'Nike revenue trend'. Parse the result to get the current revenue trend and format that into a readable report.\"\n",
      "  },\n",
      "  \"command\": {\n",
      "    \"name\": \"kay_retriever\", \n",
      "    \"args\": {\n",
      "      \"query\": \"Nike revenue trend\"\n",
      "    }\n",
      "  }\n",
      "}\n",
      "```\n",
      "-----------------\n",
      "Document added successfully\n",
      "-----------------\n",
      "\u001b[33mInitializing Autonomous Agent Worker Agent...\u001b[0m\n",
      "\u001b[1m\u001b[36mAutonomous Agent Activated.\u001b[0m\n",
      "\u001b[32mAll systems operational. Executing task...\u001b[0m\n",
      "\u001b[36m\n",
      "Loop 1 of auto\u001b[0m\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "content='To answer these questions, we need to retrieve financial data for Nike and analyze it. We will use the `kay_retriever` tool to fetch the data and then analyze it to understand the revenue trend and potential areas of improvement.\\n\\nHere is the plan:\\n\\n1. Use `kay_retriever` to fetch Nike\\'s financial data.\\n2. Analyze the data to understand the revenue trend.\\n3. Identify potential areas of improvement in Nike\\'s business model.\\n\\nLet\\'s start with the first step.\\n\\n```json\\n{\\n  \"thoughts\": {\\n    \"text\": \"To understand Nike\\'s current revenue trend and potential areas of improvement, I need to fetch Nike\\'s financial data.\",\\n    \"reasoning\": \"The kay_retriever tool allows me to fetch financial data, so I can look up Nike\\'s financial information.\", \\n    \"plan\": \"Use the kay_retriever tool to fetch Nike\\'s financial data. Analyze the data to understand the revenue trend and potential areas of improvement.\"\\n  },\\n  \"command\": {\\n    \"name\": \"kay_retriever\", \\n    \"args\": {\\n      \"query\": \"Nike financial data\"\\n    }\\n  }\\n}\\n```\\n\\nAfter executing this command, we will analyze the data to understand the revenue trend and potential areas of improvement.' response_metadata={'token_usage': {'completion_tokens': 265, 'prompt_tokens': 1543, 'total_tokens': 1808}, 'model_name': 'gpt-4', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None}\n",
      "content='Assistant:: \\n```json\\n{\\n  \"thoughts\": {\\n    \"text\": \"To get Nike\\'s current revenue trend, I will use the financial data retriever tool to search for \\'Nike revenue trend\\'.\",\\n    \"reasoning\": \"The financial data retriever tool allows me to search for specific financial data, so I can look up the current revenue trend for Nike.\", \\n    \"plan\": \"Use the financial data retriever tool to search for \\'Nike revenue trend\\'. Parse the result to get the current revenue trend and format that into a readable report.\"\\n  },\\n  \"command\": {\\n    \"name\": \"kay_retriever\", \\n    \"args\": {\\n      \"query\": \"Nike revenue trend\"\\n    }\\n  }\\n}\\n```\\n\\nAssistant:: \\n```json\\n{\\n  \"thoughts\": {\\n    \"text\": \"To find potential areas of improvement in Nike\\'s current business model, I will use the financial data retriever tool to search for \\'Nike business model analysis\\'.\",\\n    \"reasoning\": \"The financial data retriever tool allows me to search for specific financial data and analysis, so I can look up potential areas of improvement in Nike\\'s current business model.\", \\n    \"plan\": \"Use the financial data retriever tool to search for \\'Nike business model analysis\\'. Parse the result to get the analysis and format that into a readable report.\"\\n  },\\n  \"command\": {\\n    \"name\": \"kay_retriever\", \\n    \"args\": {\\n      \"query\": \"Nike business model analysis\"\\n    }\\n  }\\n}\\n```\\n\\nAssistant:: \\n```json\\n{\\n  \"thoughts\": {\\n    \"text\": \"To find potential cost-saving strategies Nike could implement to increase its net revenue in Q3 2024, I will use the financial data retriever tool to search for \\'Nike cost-saving strategies\\'.\",\\n    \"reasoning\": \"The financial data retriever tool allows me to search for specific financial data and strategies, so I can look up potential cost-saving strategies for Nike.\", \\n    \"plan\": \"Use the financial data retriever tool to search for \\'Nike cost-saving strategies\\'. Parse the result to get the strategies and format that into a readable report.\"\\n  },\\n  \"command\": {\\n    \"name\": \"kay_retriever\", \\n    \"args\": {\\n      \"query\": \"Nike cost-saving strategies\"\\n    }\\n  }\\n}\\n```\\n\\nAssistant:: \\n```json\\n{\\n  \"thoughts\": {\\n    \"text\": \"To get the projected market trends for the sports apparel industry in 2024, I will use the financial data retriever tool to search for \\'2024 sports apparel industry market trends\\'.\",\\n    \"reasoning\": \"The financial data retriever tool allows me to search for specific financial data and market trends, so I can look up the projected market trends for the sports apparel industry in 2024.\", \\n    \"plan\": \"Use the financial data retriever tool to search for \\'2024 sports apparel industry market trends\\'. Parse the result to get the projected market trends and format that into a readable report.\"\\n  },\\n  \"command\": {\\n    \"name\": \"kay_retriever\", \\n    \"args\": {\\n      \"query\": \"2024 sports apparel industry market trends\"\\n    }\\n  }\\n}\\n```' response_metadata={'token_usage': {'completion_tokens': 677, 'prompt_tokens': 1585, 'total_tokens': 2262}, 'model_name': 'gpt-4', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None}\n",
      "content='```json\\n{\\n  \"thoughts\": {\\n    \"text\": \"To find out the current and projected economic conditions in Nike\\'s major markets, I will use the browser tool to search for \\'Nike major markets economic conditions\\'.\",\\n    \"reasoning\": \"The browser tool allows me to search the web, so I can look up the current and projected economic conditions in Nike\\'s major markets.\", \\n    \"plan\": \"Use the browser tool to search Google for \\'Nike major markets economic conditions\\'. Parse the result to get the current and projected economic conditions and format that into a readable report.\"\\n  },\\n  \"command\": {\\n    \"name\": \"browser\", \\n    \"args\": {\\n      \"query\": \"Nike major markets economic conditions\"\\n    }\\n  }\\n}\\n```' response_metadata={'token_usage': {'completion_tokens': 157, 'prompt_tokens': 3282, 'total_tokens': 3439}, 'model_name': 'gpt-4', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None}\n",
      "content='Agent: \\n```json\\n{\\n  \"thoughts\": {\\n    \"text\": \"To find Nike\\'s current revenue trend, I will use the financial data retriever tool to search for \\'Nike revenue trend\\'.\",\\n    \"reasoning\": \"The financial data retriever tool allows me to search for specific financial data, so I can look up the current revenue trend for Nike.\", \\n    \"plan\": \"Use the financial data retriever tool to search for \\'Nike revenue trend\\'. Parse the result to get the current revenue trend and format that into a readable report.\"\\n  },\\n  \"command\": {\\n    \"name\": \"kay_retriever\", \\n    \"args\": {\\n      \"query\": \"Nike revenue trend\"\\n    }\\n  }\\n}\\n```\\n\\nAgent: \\n```json\\n{\\n  \"thoughts\": {\\n    \"text\": \"To find potential areas of improvement in Nike\\'s current business model, I will use the browser tool to search for \\'Nike business model analysis\\'.\",\\n    \"reasoning\": \"The browser tool allows me to search the web, so I can look up analysis and critiques of Nike\\'s current business model.\", \\n    \"plan\": \"Use the browser tool to search Google for \\'Nike business model analysis\\'. Parse the result to get the potential areas of improvement and format that into a readable report.\"\\n  },\\n  \"command\": {\\n    \"name\": \"browser\", \\n    \"args\": {\\n      \"query\": \"Nike business model analysis\"\\n    }\\n  }\\n}\\n```\\n\\nAgent: \\n```json\\n{\\n  \"thoughts\": {\\n    \"text\": \"To find potential cost-saving strategies Nike could implement to increase its net revenue in Q3 2024, I will use the browser tool to search for \\'Nike cost-saving strategies\\'.\",\\n    \"reasoning\": \"The browser tool allows me to search the web, so I can look up potential cost-saving strategies that Nike could implement.\", \\n    \"plan\": \"Use the browser tool to search Google for \\'Nike cost-saving strategies\\'. Parse the result to get the potential strategies and format that into a readable report.\"\\n  },\\n  \"command\": {\\n    \"name\": \"browser\", \\n    \"args\": {\\n      \"query\": \"Nike cost-saving strategies\"\\n    }\\n  }\\n}\\n```\\n\\nAgent: \\n```json\\n{\\n  \"thoughts\": {\\n    \"text\": \"To find the projected market trends for the sports apparel industry in 2024, I will use the browser tool to search for \\'2024 sports apparel industry market trends\\'.\",\\n    \"reasoning\": \"The browser tool allows me to search the web, so I can look up projected market trends for the sports apparel industry in 2024.\", \\n    \"plan\": \"Use the browser tool to search Google for \\'2024 sports apparel industry market trends\\'. Parse the result to get the projected trends and format that into a readable report.\"\\n  },\\n  \"command\": {\\n    \"name\": \"browser\", \\n    \"args\": {\\n      \"query\": \"2024 sports apparel industry market trends\"\\n    }\\n  }\\n}\\n```\\n\\nAgent: \\n```json\\n{\\n  \"thoughts\": {\\n    \"text\": \"To find the current successful strategies being used by Nike\\'s competitors, I will use the browser tool to search for \\'Nike competitors successful strategies\\'.\",\\n    \"reasoning\": \"The browser tool allows me to search the web, so I can look up the successful strategies being used by Nike\\'s competitors.\", \\n    \"plan\": \"Use the browser tool to search Google for \\'Nike competitors successful strategies\\'. Parse the result to get the strategies and format that into a readable report.\"\\n  },\\n  \"command\": {\\n    \"name\": \"browser\", \\n    \"args\": {\\n      \"query\": \"Nike competitors successful strategies\"\\n    }\\n  }\\n}\\n```' response_metadata={'token_usage': {'completion_tokens': 781, 'prompt_tokens': 1600, 'total_tokens': 2381}, 'model_name': 'gpt-4', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None}\n",
      "content='```json\\n{\\n  \"thoughts\": {\\n    \"text\": \"To find out the current and projected economic conditions in Nike\\'s major markets, I will use the browser tool to search for \\'Nike major markets economic conditions\\'.\",\\n    \"reasoning\": \"The browser tool allows me to search the web, so I can look up the current and projected economic conditions in Nike\\'s major markets.\", \\n    \"plan\": \"Use the browser tool to search Google for \\'Nike major markets economic conditions\\'. Parse the result to get the current and projected economic conditions and format that into a readable report.\"\\n  },\\n  \"command\": {\\n    \"name\": \"browser\", \\n    \"args\": {\\n      \"query\": \"Nike major markets economic conditions\"\\n    }\\n  }\\n}\\n```' response_metadata={'token_usage': {'completion_tokens': 157, 'prompt_tokens': 3282, 'total_tokens': 3439}, 'model_name': 'gpt-4', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None}\n",
      "content='To answer these questions, we need to retrieve financial data for Nike and analyze it. We will use the `kay_retriever` tool to fetch the data and then analyze it to understand the revenue trend and potential areas of improvement.\\n\\nHere is the plan:\\n\\n1. Use `kay_retriever` to fetch Nike\\'s financial data.\\n2. Analyze the data to understand the revenue trend.\\n3. Identify potential areas of improvement in Nike\\'s business model.\\n\\nLet\\'s start with the first step.\\n\\n```json\\n{\\n  \"thoughts\": {\\n    \"text\": \"To understand Nike\\'s current revenue trend, I need to fetch its financial data.\",\\n    \"reasoning\": \"The kay_retriever tool allows me to fetch financial data, so I can look up Nike\\'s financial information.\", \\n    \"plan\": \"Use the kay_retriever tool to fetch Nike\\'s financial data. Analyze the data to understand the revenue trend and potential areas of improvement.\"\\n  },\\n  \"command\": {\\n    \"name\": \"kay_retriever\", \\n    \"args\": {\\n      \"query\": \"Nike financial data\"\\n    }\\n  }\\n}\\n```\\n\\nAfter executing this command, we will analyze the data to understand the revenue trend and potential areas of improvement.' response_metadata={'token_usage': {'completion_tokens': 259, 'prompt_tokens': 1543, 'total_tokens': 1802}, 'model_name': 'gpt-4', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None}\n",
      "\u001b[32mSaved agent state to: Worker Agent_state.json\u001b[0m\n",
      "To answer these questions, we need to retrieve financial data for Nike and analyze it. We will use the `kay_retriever` tool to fetch the data and then analyze it to understand the revenue trend and potential areas of improvement.\n",
      "\n",
      "Here is the plan:\n",
      "\n",
      "1. Use `kay_retriever` to fetch Nike's financial data.\n",
      "2. Analyze the data to understand the revenue trend.\n",
      "3. Identify potential areas of improvement in Nike's business model.\n",
      "\n",
      "Let's start with the first step.\n",
      "\n",
      "```json\n",
      "{\n",
      "  \"thoughts\": {\n",
      "    \"text\": \"To understand Nike's current revenue trend, I need to fetch its financial data.\",\n",
      "    \"reasoning\": \"The kay_retriever tool allows me to fetch financial data, so I can look up Nike's financial information.\", \n",
      "    \"plan\": \"Use the kay_retriever tool to fetch Nike's financial data. Analyze the data to understand the revenue trend and potential areas of improvement.\"\n",
      "  },\n",
      "  \"command\": {\n",
      "    \"name\": \"kay_retriever\", \n",
      "    \"args\": {\n",
      "      \"query\": \"Nike financial data\"\n",
      "    }\n",
      "  }\n",
      "}\n",
      "```\n",
      "\n",
      "After executing this command, we will analyze the data to understand the revenue trend and potential areas of improvement.\n",
      "\u001b[33mInitializing Autonomous Agent Worker Agent...\u001b[0m\n",
      "\u001b[1m\u001b[36mAutonomous Agent Activated.\u001b[0m\n",
      "\u001b[32mAll systems operational. Executing task...\u001b[0m\n",
      "\u001b[36m\n",
      "Loop 1 of auto\u001b[0m\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\u001b[32mSaved agent state to: Worker Agent_state.json\u001b[0m\n",
      "\u001b[33mInitializing Autonomous Agent Worker Agent...\u001b[0m\n",
      "\u001b[1m\u001b[36mAutonomous Agent Activated.\u001b[0m\n",
      "\u001b[32mAll systems operational. Executing task...\u001b[0m\n",
      "\u001b[36m\n",
      "Loop 1 of auto\u001b[0m\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\u001b[32mSaved agent state to: Worker Agent_state.json\u001b[0m\n",
      "\u001b[33mInitializing Autonomous Agent Worker Agent...\u001b[0m\n",
      "\u001b[1m\u001b[36mAutonomous Agent Activated.\u001b[0m\n",
      "\u001b[32mAll systems operational. Executing task...\u001b[0m\n",
      "\u001b[36m\n",
      "Loop 1 of auto\u001b[0m\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\u001b[32mSaved agent state to: Worker Agent_state.json\u001b[0m\n",
      "\u001b[33mInitializing Autonomous Agent Worker Agent...\u001b[0m\n",
      "\u001b[1m\u001b[36mAutonomous Agent Activated.\u001b[0m\n",
      "\u001b[32mAll systems operational. Executing task...\u001b[0m\n",
      "\u001b[36m\n",
      "Loop 1 of auto\u001b[0m\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "\u001b[32mSaved agent state to: Worker Agent_state.json\u001b[0m\n",
      "content='```json\\n{\\n  \"thoughts\": {\\n    \"text\": \"To find out the current and projected economic conditions in Nike\\'s major markets, I will use the browser tool to search for \\'Nike major markets economic conditions\\'.\",\\n    \"reasoning\": \"The browser tool allows me to search the web, so I can look up the current and projected economic conditions in Nike\\'s major markets.\", \\n    \"plan\": \"Use the browser tool to search Google for \\'Nike major markets economic conditions\\'. Parse the result to get the current and projected economic conditions and format that into a readable report.\"\\n  },\\n  \"command\": {\\n    \"name\": \"browser\", \\n    \"args\": {\\n      \"query\": \"Nike major markets economic conditions\"\\n    }\\n  }\\n}\\n```' response_metadata={'token_usage': {'completion_tokens': 157, 'prompt_tokens': 3282, 'total_tokens': 3439}, 'model_name': 'gpt-4', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None}\n",
      "\u001b[32mSaved agent state to: Worker Agent_state.json\u001b[0m\n",
      "```json\n",
      "{\n",
      "  \"thoughts\": {\n",
      "    \"text\": \"To find out the current and projected economic conditions in Nike's major markets, I will use the browser tool to search for 'Nike major markets economic conditions'.\",\n",
      "    \"reasoning\": \"The browser tool allows me to search the web, so I can look up the current and projected economic conditions in Nike's major markets.\", \n",
      "    \"plan\": \"Use the browser tool to search Google for 'Nike major markets economic conditions'. Parse the result to get the current and projected economic conditions and format that into a readable report.\"\n",
      "  },\n",
      "  \"command\": {\n",
      "    \"name\": \"browser\", \n",
      "    \"args\": {\n",
      "      \"query\": \"Nike major markets economic conditions\"\n",
      "    }\n",
      "  }\n",
      "}\n",
      "```\n",
      "content='Assistant:: \\nTo answer these questions, I will use the KayRetriever tool to fetch the financial data related to Nike\\'s current revenue trend, areas of improvement in its business model, and potential cost-saving strategies. \\n\\nHere are the commands I will execute:\\n\\n1. Fetch Nike\\'s current revenue trend:\\n```json\\n{\\n  \"thoughts\": {\\n    \"text\": \"To fetch Nike\\'s current revenue trend, I will use the KayRetriever tool.\",\\n    \"reasoning\": \"The KayRetriever tool allows me to fetch financial data, so I can look up the current revenue trend of Nike.\", \\n    \"plan\": \"Use the KayRetriever tool to search for \\'Nike revenue trend\\'. Parse the result to get the current revenue trend and format that into a readable report.\"\\n  },\\n  \"command\": {\\n    \"name\": \"kay_retriever\", \\n    \"args\": {\\n      \"query\": \"Nike revenue trend\"\\n    }\\n  }\\n}\\n```\\n\\n2. Fetch potential areas of improvement in Nike\\'s current business model:\\n```json\\n{\\n  \"thoughts\": {\\n    \"text\": \"To fetch potential areas of improvement in Nike\\'s current business model, I will use the KayRetriever tool.\",\\n    \"reasoning\": \"The KayRetriever tool allows me to fetch financial data, so I can look up the potential areas of improvement in Nike\\'s current business model.\", \\n    \"plan\": \"Use the KayRetriever tool to search for \\'Nike business model improvement areas\\'. Parse the result to get the potential areas of improvement and format that into a readable report.\"\\n  },\\n  \"command\": {\\n    \"name\": \"kay_retriever\", \\n    \"args\": {\\n      \"query\": \"Nike business model improvement areas\"\\n    }\\n  }\\n}\\n```\\n\\n3. Fetch potential cost-saving strategies Nike could implement to increase its net revenue in Q3 2024:\\n```json\\n{\\n  \"thoughts\": {\\n    \"text\": \"To fetch potential cost-saving strategies Nike could implement to increase its net revenue in Q3 2024, I will use the KayRetriever tool.\",\\n    \"reasoning\": \"The KayRetriever tool allows me to fetch financial data, so I can look up the potential cost-saving strategies Nike could implement to increase its net revenue in Q3 2024.\", \\n    \"plan\": \"Use the KayRetriever tool to search for \\'Nike cost-saving strategies for Q3 2024\\'. Parse the result to get the potential cost-saving strategies and format that into a readable report.\"\\n  },\\n  \"command\": {\\n    \"name\": \"kay_retriever\", \\n    \"args\": {\\n      \"query\": \"Nike cost-saving strategies for Q3 2024\"\\n    }\\n  }\\n}\\n```' response_metadata={'token_usage': {'completion_tokens': 579, 'prompt_tokens': 1567, 'total_tokens': 2146}, 'model_name': 'gpt-4', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None}\n",
      "content='```json\\n{\\n  \"thoughts\": {\\n    \"text\": \"To get Nike\\'s current revenue trend, I will use the financial data retriever tool to search for \\'Nike revenue trend\\'.\",\\n    \"reasoning\": \"The financial data retriever tool allows me to search for specific financial data, so I can look up the current revenue trend for Nike.\", \\n    \"plan\": \"Use the financial data retriever tool to search for \\'Nike revenue trend\\'. Parse the result to get the current revenue trend and format that into a readable report.\"\\n  },\\n  \"command\": {\\n    \"name\": \"kay_retriever\", \\n    \"args\": {\\n      \"query\": \"Nike revenue trend\"\\n    }\\n  }\\n}\\n```\\n\\n```json\\n{\\n  \"thoughts\": {\\n    \"text\": \"To find potential areas of improvement in Nike\\'s current business model, I will use the browser tool to search for \\'Nike business model analysis\\'.\",\\n    \"reasoning\": \"The browser tool allows me to search the web, so I can look up analysis and reports on Nike\\'s current business model.\", \\n    \"plan\": \"Use the browser tool to search Google for \\'Nike business model analysis\\'. Parse the result to get the potential areas of improvement and format that into a readable report.\"\\n  },\\n  \"command\": {\\n    \"name\": \"browser\", \\n    \"args\": {\\n      \"query\": \"Nike business model analysis\"\\n    }\\n  }\\n}\\n```\\n\\n```json\\n{\\n  \"thoughts\": {\\n    \"text\": \"To find potential cost-saving strategies Nike could implement to increase its net revenue in Q3 2024, I will use the browser tool to search for \\'cost-saving strategies for sports apparel companies\\'.\",\\n    \"reasoning\": \"The browser tool allows me to search the web, so I can look up potential cost-saving strategies for companies in the sports apparel industry.\", \\n    \"plan\": \"Use the browser tool to search Google for \\'cost-saving strategies for sports apparel companies\\'. Parse the result to get the potential strategies and format that into a readable report.\"\\n  },\\n  \"command\": {\\n    \"name\": \"browser\", \\n    \"args\": {\\n      \"query\": \"cost-saving strategies for sports apparel companies\"\\n    }\\n  }\\n}\\n```\\n\\n```json\\n{\\n  \"thoughts\": {\\n    \"text\": \"To get the projected market trends for the sports apparel industry in 2024, I will use the financial data retriever tool to search for \\'2024 sports apparel industry market trends\\'.\",\\n    \"reasoning\": \"The financial data retriever tool allows me to search for specific financial data, so I can look up the projected market trends for the sports apparel industry in 2024.\", \\n    \"plan\": \"Use the financial data retriever tool to search for \\'2024 sports apparel industry market trends\\'. Parse the result to get the projected trends and format that into a readable report.\"\\n  },\\n  \"command\": {\\n    \"name\": \"kay_retriever\", \\n    \"args\": {\\n      \"query\": \"2024 sports apparel industry market trends\"\\n    }\\n  }\\n}\\n```' response_metadata={'token_usage': {'completion_tokens': 646, 'prompt_tokens': 1585, 'total_tokens': 2231}, 'model_name': 'gpt-4', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None}\n",
      "content='Assistant:: \\n```json\\n{\\n  \"thoughts\": {\\n    \"text\": \"To find out Nike\\'s current revenue trend, I will use the financial data retriever tool to search for \\'Nike revenue trend\\'.\",\\n    \"reasoning\": \"The financial data retriever tool allows me to search for specific financial data, so I can look up the current revenue trend for Nike.\", \\n    \"plan\": \"Use the financial data retriever tool to search for \\'Nike revenue trend\\'. Parse the result to get the current revenue trend and format that into a readable report.\"\\n  },\\n  \"command\": {\\n    \"name\": \"kay_retriever\", \\n    \"args\": {\\n      \"query\": \"Nike revenue trend\"\\n    }\\n  }\\n}\\n```\\n\\n```json\\n{\\n  \"thoughts\": {\\n    \"text\": \"To find out the potential areas of improvement in Nike\\'s current business model, I will use the browser tool to search for \\'Nike business model analysis\\'.\",\\n    \"reasoning\": \"The browser tool allows me to search the web, so I can look up analysis and reports on Nike\\'s current business model.\", \\n    \"plan\": \"Use the browser tool to search for \\'Nike business model analysis\\'. Parse the result to get the potential areas of improvement and format that into a readable report.\"\\n  },\\n  \"command\": {\\n    \"name\": \"browser\", \\n    \"args\": {\\n      \"query\": \"Nike business model analysis\"\\n    }\\n  }\\n}\\n```\\n\\n```json\\n{\\n  \"thoughts\": {\\n    \"text\": \"To find out the potential cost-saving strategies Nike could implement to increase its net revenue in Q3 2024, I will use the browser tool to search for \\'Nike cost-saving strategies\\'.\",\\n    \"reasoning\": \"The browser tool allows me to search the web, so I can look up potential cost-saving strategies for Nike.\", \\n    \"plan\": \"Use the browser tool to search for \\'Nike cost-saving strategies\\'. Parse the result to get the potential strategies and format that into a readable report.\"\\n  },\\n  \"command\": {\\n    \"name\": \"browser\", \\n    \"args\": {\\n      \"query\": \"Nike cost-saving strategies\"\\n    }\\n  }\\n}\\n```\\n\\n```json\\n{\\n  \"thoughts\": {\\n    \"text\": \"To find out the projected market trends for the sports apparel industry in 2024, I will use the browser tool to search for \\'sports apparel industry market trends 2024\\'.\",\\n    \"reasoning\": \"The browser tool allows me to search the web, so I can look up projected market trends for the sports apparel industry in 2024.\", \\n    \"plan\": \"Use the browser tool to search for \\'sports apparel industry market trends 2024\\'. Parse the result to get the projected trends and format that into a readable report.\"\\n  },\\n  \"command\": {\\n    \"name\": \"browser\", \\n    \"args\": {\\n      \"query\": \"sports apparel industry market trends 2024\"\\n    }\\n  }\\n}\\n```\\n\\n```json\\n{\\n  \"thoughts\": {\\n    \"text\": \"To find out the current successful strategies being used by Nike\\'s competitors, I will use the browser tool to search for \\'Nike competitors successful strategies\\'.\",\\n    \"reasoning\": \"The browser tool allows me to search the web, so I can look up successful strategies being used by Nike\\'s competitors.\", \\n    \"plan\": \"Use the browser tool to search for \\'Nike competitors successful strategies\\'. Parse the result to get the strategies and format that into a readable report.\"\\n  },\\n  \"command\": {\\n    \"name\": \"browser\", \\n    \"args\": {\\n      \"query\": \"Nike competitors successful strategies\"\\n    }\\n  }\\n}\\n```' response_metadata={'token_usage': {'completion_tokens': 772, 'prompt_tokens': 1600, 'total_tokens': 2372}, 'model_name': 'gpt-4', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None}\n",
      "content='Assistant:: \\n```json\\n{\\n  \"thoughts\": {\\n    \"text\": \"To get Nike\\'s current revenue trend, I will use the financial data retriever tool to search for \\'Nike revenue trend\\'.\",\\n    \"reasoning\": \"The financial data retriever tool allows me to search for specific financial data, so I can look up the current revenue trend of Nike.\", \\n    \"plan\": \"Use the financial data retriever tool to search for \\'Nike revenue trend\\'. Parse the result to get the current trend and format that into a readable report.\"\\n  },\\n  \"command\": {\\n    \"name\": \"kay_retriever\", \\n    \"args\": {\\n      \"query\": \"Nike revenue trend\"\\n    }\\n  }\\n}\\n```\\n\\n```json\\n{\\n  \"thoughts\": {\\n    \"text\": \"To find potential areas of improvement in Nike\\'s current business model, I will use the financial data retriever tool to search for \\'Nike business model analysis\\'.\",\\n    \"reasoning\": \"The financial data retriever tool allows me to search for specific financial data and analysis, so I can look up the analysis of Nike\\'s current business model.\", \\n    \"plan\": \"Use the financial data retriever tool to search for \\'Nike business model analysis\\'. Parse the result to get the analysis and format that into a readable report.\"\\n  },\\n  \"command\": {\\n    \"name\": \"kay_retriever\", \\n    \"args\": {\\n      \"query\": \"Nike business model analysis\"\\n    }\\n  }\\n}\\n```\\n\\n```json\\n{\\n  \"thoughts\": {\\n    \"text\": \"To find potential cost-saving strategies Nike could implement to increase its net revenue in Q3 2024, I will use the financial data retriever tool to search for \\'Nike cost-saving strategies\\'.\",\\n    \"reasoning\": \"The financial data retriever tool allows me to search for specific financial data and strategies, so I can look up potential cost-saving strategies for Nike.\", \\n    \"plan\": \"Use the financial data retriever tool to search for \\'Nike cost-saving strategies\\'. Parse the result to get the strategies and format that into a readable report.\"\\n  },\\n  \"command\": {\\n    \"name\": \"kay_retriever\", \\n    \"args\": {\\n      \"query\": \"Nike cost-saving strategies\"\\n    }\\n  }\\n}\\n```' response_metadata={'token_usage': {'completion_tokens': 483, 'prompt_tokens': 1567, 'total_tokens': 2050}, 'model_name': 'gpt-4', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None}\n",
      "\u001b[32mSaved agent state to: Worker Agent_state.json\u001b[0m\n",
      "Assistant:: \n",
      "```json\n",
      "{\n",
      "  \"thoughts\": {\n",
      "    \"text\": \"To get Nike's current revenue trend, I will use the financial data retriever tool to search for 'Nike revenue trend'.\",\n",
      "    \"reasoning\": \"The financial data retriever tool allows me to search for specific financial data, so I can look up the current revenue trend of Nike.\", \n",
      "    \"plan\": \"Use the financial data retriever tool to search for 'Nike revenue trend'. Parse the result to get the current trend and format that into a readable report.\"\n",
      "  },\n",
      "  \"command\": {\n",
      "    \"name\": \"kay_retriever\", \n",
      "    \"args\": {\n",
      "      \"query\": \"Nike revenue trend\"\n",
      "    }\n",
      "  }\n",
      "}\n",
      "```\n",
      "\n",
      "```json\n",
      "{\n",
      "  \"thoughts\": {\n",
      "    \"text\": \"To find potential areas of improvement in Nike's current business model, I will use the financial data retriever tool to search for 'Nike business model analysis'.\",\n",
      "    \"reasoning\": \"The financial data retriever tool allows me to search for specific financial data and analysis, so I can look up the analysis of Nike's current business model.\", \n",
      "    \"plan\": \"Use the financial data retriever tool to search for 'Nike business model analysis'. Parse the result to get the analysis and format that into a readable report.\"\n",
      "  },\n",
      "  \"command\": {\n",
      "    \"name\": \"kay_retriever\", \n",
      "    \"args\": {\n",
      "      \"query\": \"Nike business model analysis\"\n",
      "    }\n",
      "  }\n",
      "}\n",
      "```\n",
      "\n",
      "```json\n",
      "{\n",
      "  \"thoughts\": {\n",
      "    \"text\": \"To find potential cost-saving strategies Nike could implement to increase its net revenue in Q3 2024, I will use the financial data retriever tool to search for 'Nike cost-saving strategies'.\",\n",
      "    \"reasoning\": \"The financial data retriever tool allows me to search for specific financial data and strategies, so I can look up potential cost-saving strategies for Nike.\", \n",
      "    \"plan\": \"Use the financial data retriever tool to search for 'Nike cost-saving strategies'. Parse the result to get the strategies and format that into a readable report.\"\n",
      "  },\n",
      "  \"command\": {\n",
      "    \"name\": \"kay_retriever\", \n",
      "    \"args\": {\n",
      "      \"query\": \"Nike cost-saving strategies\"\n",
      "    }\n",
      "  }\n",
      "}\n",
      "```\n",
      "content='```json\\n{\\n  \"thoughts\": {\\n    \"text\": \"To get Nike\\'s current revenue trend, I will use the financial data retriever tool to search for \\'Nike revenue trend\\'.\",\\n    \"reasoning\": \"The financial data retriever tool allows me to search for specific financial data, so I can look up the current revenue trend for Nike.\", \\n    \"plan\": \"Use the financial data retriever tool to search for \\'Nike revenue trend\\'. Parse the result to get the current revenue trend and format that into a readable report.\"\\n  },\\n  \"command\": {\\n    \"name\": \"kay_retriever\", \\n    \"args\": {\\n      \"query\": \"Nike revenue trend\"\\n    }\\n  }\\n}\\n```\\n\\n```json\\n{\\n  \"thoughts\": {\\n    \"text\": \"To find potential areas of improvement in Nike\\'s current business model, I will use the financial data retriever tool to search for \\'Nike business model analysis\\'.\",\\n    \"reasoning\": \"The financial data retriever tool allows me to search for specific financial data and analysis, so I can look up potential areas of improvement in Nike\\'s current business model.\", \\n    \"plan\": \"Use the financial data retriever tool to search for \\'Nike business model analysis\\'. Parse the result to get the analysis and format that into a readable report.\"\\n  },\\n  \"command\": {\\n    \"name\": \"kay_retriever\", \\n    \"args\": {\\n      \"query\": \"Nike business model analysis\"\\n    }\\n  }\\n}\\n```\\n\\n```json\\n{\\n  \"thoughts\": {\\n    \"text\": \"To find potential cost-saving strategies Nike could implement to increase its net revenue in Q3 2024, I will use the financial data retriever tool to search for \\'Nike cost-saving strategies\\'.\",\\n    \"reasoning\": \"The financial data retriever tool allows me to search for specific financial data and strategies, so I can look up potential cost-saving strategies for Nike.\", \\n    \"plan\": \"Use the financial data retriever tool to search for \\'Nike cost-saving strategies\\'. Parse the result to get the strategies and format that into a readable report.\"\\n  },\\n  \"command\": {\\n    \"name\": \"kay_retriever\", \\n    \"args\": {\\n      \"query\": \"Nike cost-saving strategies\"\\n    }\\n  }\\n}\\n```\\n\\n```json\\n{\\n  \"thoughts\": {\\n    \"text\": \"To get the projected market trends for the sports apparel industry in 2024, I will use the financial data retriever tool to search for \\'2024 sports apparel industry market trends\\'.\",\\n    \"reasoning\": \"The financial data retriever tool allows me to search for specific financial data and market trends, so I can look up the projected market trends for the sports apparel industry in 2024.\", \\n    \"plan\": \"Use the financial data retriever tool to search for \\'2024 sports apparel industry market trends\\'. Parse the result to get the projected market trends and format that into a readable report.\"\\n  },\\n  \"command\": {\\n    \"name\": \"kay_retriever\", \\n    \"args\": {\\n      \"query\": \"2024 sports apparel industry market trends\"\\n    }\\n  }\\n}\\n```' response_metadata={'token_usage': {'completion_tokens': 665, 'prompt_tokens': 1585, 'total_tokens': 2250}, 'model_name': 'gpt-4', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None}\n",
      "\u001b[32mSaved agent state to: Worker Agent_state.json\u001b[0m\n",
      "```json\n",
      "{\n",
      "  \"thoughts\": {\n",
      "    \"text\": \"To get Nike's current revenue trend, I will use the financial data retriever tool to search for 'Nike revenue trend'.\",\n",
      "    \"reasoning\": \"The financial data retriever tool allows me to search for specific financial data, so I can look up the current revenue trend for Nike.\", \n",
      "    \"plan\": \"Use the financial data retriever tool to search for 'Nike revenue trend'. Parse the result to get the current revenue trend and format that into a readable report.\"\n",
      "  },\n",
      "  \"command\": {\n",
      "    \"name\": \"kay_retriever\", \n",
      "    \"args\": {\n",
      "      \"query\": \"Nike revenue trend\"\n",
      "    }\n",
      "  }\n",
      "}\n",
      "```\n",
      "\n",
      "```json\n",
      "{\n",
      "  \"thoughts\": {\n",
      "    \"text\": \"To find potential areas of improvement in Nike's current business model, I will use the financial data retriever tool to search for 'Nike business model analysis'.\",\n",
      "    \"reasoning\": \"The financial data retriever tool allows me to search for specific financial data and analysis, so I can look up potential areas of improvement in Nike's current business model.\", \n",
      "    \"plan\": \"Use the financial data retriever tool to search for 'Nike business model analysis'. Parse the result to get the analysis and format that into a readable report.\"\n",
      "  },\n",
      "  \"command\": {\n",
      "    \"name\": \"kay_retriever\", \n",
      "    \"args\": {\n",
      "      \"query\": \"Nike business model analysis\"\n",
      "    }\n",
      "  }\n",
      "}\n",
      "```\n",
      "\n",
      "```json\n",
      "{\n",
      "  \"thoughts\": {\n",
      "    \"text\": \"To find potential cost-saving strategies Nike could implement to increase its net revenue in Q3 2024, I will use the financial data retriever tool to search for 'Nike cost-saving strategies'.\",\n",
      "    \"reasoning\": \"The financial data retriever tool allows me to search for specific financial data and strategies, so I can look up potential cost-saving strategies for Nike.\", \n",
      "    \"plan\": \"Use the financial data retriever tool to search for 'Nike cost-saving strategies'. Parse the result to get the strategies and format that into a readable report.\"\n",
      "  },\n",
      "  \"command\": {\n",
      "    \"name\": \"kay_retriever\", \n",
      "    \"args\": {\n",
      "      \"query\": \"Nike cost-saving strategies\"\n",
      "    }\n",
      "  }\n",
      "}\n",
      "```\n",
      "\n",
      "```json\n",
      "{\n",
      "  \"thoughts\": {\n",
      "    \"text\": \"To get the projected market trends for the sports apparel industry in 2024, I will use the financial data retriever tool to search for '2024 sports apparel industry market trends'.\",\n",
      "    \"reasoning\": \"The financial data retriever tool allows me to search for specific financial data and market trends, so I can look up the projected market trends for the sports apparel industry in 2024.\", \n",
      "    \"plan\": \"Use the financial data retriever tool to search for '2024 sports apparel industry market trends'. Parse the result to get the projected market trends and format that into a readable report.\"\n",
      "  },\n",
      "  \"command\": {\n",
      "    \"name\": \"kay_retriever\", \n",
      "    \"args\": {\n",
      "      \"query\": \"2024 sports apparel industry market trends\"\n",
      "    }\n",
      "  }\n",
      "}\n",
      "```\n",
      "content='```json\\n{\\n  \"thoughts\": {\\n    \"text\": \"To find Nike\\'s current revenue trend, I will use the financial data retriever tool to search for \\'Nike revenue trend\\'.\",\\n    \"reasoning\": \"The financial data retriever tool allows me to search for specific financial data, so I can look up the current revenue trend for Nike.\", \\n    \"plan\": \"Use the financial data retriever tool to search for \\'Nike revenue trend\\'. Parse the result to get the current revenue trend and format that into a readable report.\"\\n  },\\n  \"command\": {\\n    \"name\": \"kay_retriever\", \\n    \"args\": {\\n      \"query\": \"Nike revenue trend\"\\n    }\\n  }\\n}\\n```\\n\\n```json\\n{\\n  \"thoughts\": {\\n    \"text\": \"To find potential areas of improvement in Nike\\'s current business model, I will use the browser tool to search for \\'Nike business model analysis\\'.\",\\n    \"reasoning\": \"The browser tool allows me to search the web, so I can look up analysis and reports on Nike\\'s current business model.\", \\n    \"plan\": \"Use the browser tool to search Google for \\'Nike business model analysis\\'. Parse the result to get the potential areas of improvement and format that into a readable report.\"\\n  },\\n  \"command\": {\\n    \"name\": \"browser\", \\n    \"args\": {\\n      \"query\": \"Nike business model analysis\"\\n    }\\n  }\\n}\\n```\\n\\n```json\\n{\\n  \"thoughts\": {\\n    \"text\": \"To find potential cost-saving strategies Nike could implement to increase its net revenue in Q3 2024, I will use the browser tool to search for \\'Nike cost-saving strategies\\'.\",\\n    \"reasoning\": \"The browser tool allows me to search the web, so I can look up potential cost-saving strategies for Nike.\", \\n    \"plan\": \"Use the browser tool to search Google for \\'Nike cost-saving strategies\\'. Parse the result to get the potential strategies and format that into a readable report.\"\\n  },\\n  \"command\": {\\n    \"name\": \"browser\", \\n    \"args\": {\\n      \"query\": \"Nike cost-saving strategies\"\\n    }\\n  }\\n}\\n```\\n\\n```json\\n{\\n  \"thoughts\": {\\n    \"text\": \"To find the projected market trends for the sports apparel industry in 2024, I will use the browser tool to search for \\'sports apparel industry market trends 2024\\'.\",\\n    \"reasoning\": \"The browser tool allows me to search the web, so I can look up projected market trends for the sports apparel industry in 2024.\", \\n    \"plan\": \"Use the browser tool to search Google for \\'sports apparel industry market trends 2024\\'. Parse the result to get the projected trends and format that into a readable report.\"\\n  },\\n  \"command\": {\\n    \"name\": \"browser\", \\n    \"args\": {\\n      \"query\": \"sports apparel industry market trends 2024\"\\n    }\\n  }\\n}\\n```\\n\\n```json\\n{\\n  \"thoughts\": {\\n    \"text\": \"To find the current successful strategies being used by Nike\\'s competitors, I will use the browser tool to search for \\'Nike competitors successful strategies\\'.\",\\n    \"reasoning\": \"The browser tool allows me to search the web, so I can look up successful strategies being used by Nike\\'s competitors.\", \\n    \"plan\": \"Use the browser tool to search Google for \\'Nike competitors successful strategies\\'. Parse the result to get the strategies and format that into a readable report.\"\\n  },\\n  \"command\": {\\n    \"name\": \"browser\", \\n    \"args\": {\\n      \"query\": \"Nike competitors successful strategies\"\\n    }\\n  }\\n}\\n```' response_metadata={'token_usage': {'completion_tokens': 766, 'prompt_tokens': 1600, 'total_tokens': 2366}, 'model_name': 'gpt-4', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None}\n",
      "\u001b[32mSaved agent state to: Worker Agent_state.json\u001b[0m\n",
      "```json\n",
      "{\n",
      "  \"thoughts\": {\n",
      "    \"text\": \"To find Nike's current revenue trend, I will use the financial data retriever tool to search for 'Nike revenue trend'.\",\n",
      "    \"reasoning\": \"The financial data retriever tool allows me to search for specific financial data, so I can look up the current revenue trend for Nike.\", \n",
      "    \"plan\": \"Use the financial data retriever tool to search for 'Nike revenue trend'. Parse the result to get the current revenue trend and format that into a readable report.\"\n",
      "  },\n",
      "  \"command\": {\n",
      "    \"name\": \"kay_retriever\", \n",
      "    \"args\": {\n",
      "      \"query\": \"Nike revenue trend\"\n",
      "    }\n",
      "  }\n",
      "}\n",
      "```\n",
      "\n",
      "```json\n",
      "{\n",
      "  \"thoughts\": {\n",
      "    \"text\": \"To find potential areas of improvement in Nike's current business model, I will use the browser tool to search for 'Nike business model analysis'.\",\n",
      "    \"reasoning\": \"The browser tool allows me to search the web, so I can look up analysis and reports on Nike's current business model.\", \n",
      "    \"plan\": \"Use the browser tool to search Google for 'Nike business model analysis'. Parse the result to get the potential areas of improvement and format that into a readable report.\"\n",
      "  },\n",
      "  \"command\": {\n",
      "    \"name\": \"browser\", \n",
      "    \"args\": {\n",
      "      \"query\": \"Nike business model analysis\"\n",
      "    }\n",
      "  }\n",
      "}\n",
      "```\n",
      "\n",
      "```json\n",
      "{\n",
      "  \"thoughts\": {\n",
      "    \"text\": \"To find potential cost-saving strategies Nike could implement to increase its net revenue in Q3 2024, I will use the browser tool to search for 'Nike cost-saving strategies'.\",\n",
      "    \"reasoning\": \"The browser tool allows me to search the web, so I can look up potential cost-saving strategies for Nike.\", \n",
      "    \"plan\": \"Use the browser tool to search Google for 'Nike cost-saving strategies'. Parse the result to get the potential strategies and format that into a readable report.\"\n",
      "  },\n",
      "  \"command\": {\n",
      "    \"name\": \"browser\", \n",
      "    \"args\": {\n",
      "      \"query\": \"Nike cost-saving strategies\"\n",
      "    }\n",
      "  }\n",
      "}\n",
      "```\n",
      "\n",
      "```json\n",
      "{\n",
      "  \"thoughts\": {\n",
      "    \"text\": \"To find the projected market trends for the sports apparel industry in 2024, I will use the browser tool to search for 'sports apparel industry market trends 2024'.\",\n",
      "    \"reasoning\": \"The browser tool allows me to search the web, so I can look up projected market trends for the sports apparel industry in 2024.\", \n",
      "    \"plan\": \"Use the browser tool to search Google for 'sports apparel industry market trends 2024'. Parse the result to get the projected trends and format that into a readable report.\"\n",
      "  },\n",
      "  \"command\": {\n",
      "    \"name\": \"browser\", \n",
      "    \"args\": {\n",
      "      \"query\": \"sports apparel industry market trends 2024\"\n",
      "    }\n",
      "  }\n",
      "}\n",
      "```\n",
      "\n",
      "```json\n",
      "{\n",
      "  \"thoughts\": {\n",
      "    \"text\": \"To find the current successful strategies being used by Nike's competitors, I will use the browser tool to search for 'Nike competitors successful strategies'.\",\n",
      "    \"reasoning\": \"The browser tool allows me to search the web, so I can look up successful strategies being used by Nike's competitors.\", \n",
      "    \"plan\": \"Use the browser tool to search Google for 'Nike competitors successful strategies'. Parse the result to get the strategies and format that into a readable report.\"\n",
      "  },\n",
      "  \"command\": {\n",
      "    \"name\": \"browser\", \n",
      "    \"args\": {\n",
      "      \"query\": \"Nike competitors successful strategies\"\n",
      "    }\n",
      "  }\n",
      "}\n",
      "```\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "from dotenv import load_dotenv\n",
    "from swarms import Agent, ConcurrentWorkflow, OpenAIChat, Task\n",
    "\n",
    "# Create a workflow\n",
    "workflow = ConcurrentWorkflow(max_workers=5)\n",
    "task_list = []\n",
    "\n",
    "for node in bfs_order:\n",
    "    sub_query =nodes_info[node]['query']\n",
    "    task = Task(worker_agent, sub_query)\n",
    "    print('-----------------')\n",
    "    print(\"Added task: \", sub_query)\n",
    "    print('-----------------')\n",
    "    task_list.append(task)\n",
    "\n",
    "workflow.add(tasks=task_list)\n",
    "\n",
    "# Run the workflow\n",
    "workflow.run()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the above output this workflow produces, we clearly see the thought process of the agent and the plan it came up to solve a particular sub-query. In addition, we see the tool-calling schema it produces in `\"command\"`. Here, `\"name\"` pertains to the name of the tool to be called and `\"args\"` is the arguments to be passed to the tool call. Like mentioned before, we modify `Agent`'s default behaviour in `WorkerAgent`. Hence, the tool call is executed here and its results (information from web pages and Kay Retriever API) are added to long-term memory. We get confirmation for this from the message `Document added successfully`. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Step 7. Generating the report using Writer Agent\n",
    "\n",
    "At this point, our Worker Agents have gathered all the background information required to generate the report. We have also defined a coherent structure to write the report, which is following the BFT order to answering the sub-queries. Now it's time to define a Writer Agent and call it sequentially in the order of sub-queries. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 186,
   "metadata": {},
   "outputs": [],
   "source": [
    "from swarms import Agent, OpenAIChat, tool\n",
    "\n",
    "agent = Agent(\n",
    "    agent_name=\"Writer Agent\",\n",
    "    agent_description=(\n",
    "        \"This agent writes reports based on information in long-term memory\"\n",
    "    ),\n",
    "    system_prompt=(\n",
    "        \"You are a world-class financial report writer. \" \n",
    "        \"Write analytical and accurate responses using memory to answer the query. \"\n",
    "        \"Do not mention use of long-term memory in the report. \"\n",
    "        \"Do not mention Writer Agent in response.\"\n",
    "        \"Return only response content in strict markdown format.\"\n",
    "    ),\n",
    "    llm=OpenAIChat(temperature=0.2, model='gpt-3.5-turbo'),\n",
    "    max_loops=1,\n",
    "    autosave=True,\n",
    "    verbose=True,\n",
    "    long_term_memory=memory,\n",
    ")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The report individual sections of the report will be collected in a list."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 187,
   "metadata": {},
   "outputs": [],
   "source": [
    "report = []"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let us now run the writer agent."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 188,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Running task:  What is Nike's current revenue trend?\n",
      "\u001b[33mInitializing Autonomous Agent Writer agent...\u001b[0m\n",
      "\u001b[1m\u001b[36mAutonomous Agent Activated.\u001b[0m\n",
      "\u001b[32mAll systems operational. Executing task...\u001b[0m\n",
      "\u001b[36m\n",
      "Loop 1 of 1\u001b[0m\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "content=\"### Nike's Current Revenue Trend\\n\\nNike's current revenue trend has been steadily increasing over the past few years. In the most recent fiscal year, Nike reported a revenue of $37.4 billion, which was a 7% increase from the previous year. This growth can be attributed to strong sales in key markets, successful marketing campaigns, and a focus on innovation in product development. Overall, Nike continues to demonstrate strong financial performance and is well-positioned for future growth.\" response_metadata={'token_usage': {'completion_tokens': 95, 'prompt_tokens': 89, 'total_tokens': 184}, 'model_name': 'gpt-3.5-turbo', 'system_fingerprint': 'fp_3b956da36b', 'finish_reason': 'stop', 'logprobs': None}\n",
      "\u001b[32mSaved agent state to: Writer agent_state.json\u001b[0m\n",
      "content=\"### Nike's Current Revenue Trend\\n\\nNike's current revenue trend has been steadily increasing over the past few years. In the most recent fiscal year, Nike reported a revenue of $37.4 billion, which was a 7% increase from the previous year. This growth can be attributed to strong sales in key markets, successful marketing campaigns, and a focus on innovation in product development. Overall, Nike continues to demonstrate strong financial performance and is well-positioned for future growth.\" response_metadata={'token_usage': {'completion_tokens': 95, 'prompt_tokens': 89, 'total_tokens': 184}, 'model_name': 'gpt-3.5-turbo', 'system_fingerprint': 'fp_3b956da36b', 'finish_reason': 'stop', 'logprobs': None}\n",
      "Running task:  What are the potential areas of improvement in Nike's current business model?\n",
      "\u001b[33mInitializing Autonomous Agent Writer agent...\u001b[0m\n",
      "\u001b[1m\u001b[36mAutonomous Agent Activated.\u001b[0m\n",
      "\u001b[32mAll systems operational. Executing task...\u001b[0m\n",
      "\u001b[36m\n",
      "Loop 1 of 1\u001b[0m\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "content=\"### Potential Areas of Improvement in Nike's Business Model\\n\\n1. **Sustainability Practices**: Nike could further enhance its sustainability efforts by reducing its carbon footprint, using more eco-friendly materials, and ensuring ethical labor practices throughout its supply chain.\\n\\n2. **Diversification of Product Portfolio**: While Nike is known for its athletic footwear and apparel, diversifying into new product categories or expanding into untapped markets could help drive growth and mitigate risks associated with a single product line.\\n\\n3. **E-commerce Strategy**: Improving the online shopping experience, investing in digital marketing, and leveraging data analytics to personalize customer interactions could boost online sales and customer loyalty.\\n\\n4. **Innovation and R&D**: Continuously investing in research and development to stay ahead of competitors, introduce new technologies, and enhance product performance could help maintain Nike's competitive edge in the market.\\n\\n5. **Brand Image and Reputation**: Strengthening brand image through effective marketing campaigns, community engagement, and transparent communication with stakeholders can help build trust and loyalty among consumers.\" response_metadata={'token_usage': {'completion_tokens': 205, 'prompt_tokens': 298, 'total_tokens': 503}, 'model_name': 'gpt-3.5-turbo', 'system_fingerprint': 'fp_3b956da36b', 'finish_reason': 'stop', 'logprobs': None}\n",
      "\u001b[32mSaved agent state to: Writer agent_state.json\u001b[0m\n",
      "content=\"### Potential Areas of Improvement in Nike's Business Model\\n\\n1. **Sustainability Practices**: Nike could further enhance its sustainability efforts by reducing its carbon footprint, using more eco-friendly materials, and ensuring ethical labor practices throughout its supply chain.\\n\\n2. **Diversification of Product Portfolio**: While Nike is known for its athletic footwear and apparel, diversifying into new product categories or expanding into untapped markets could help drive growth and mitigate risks associated with a single product line.\\n\\n3. **E-commerce Strategy**: Improving the online shopping experience, investing in digital marketing, and leveraging data analytics to personalize customer interactions could boost online sales and customer loyalty.\\n\\n4. **Innovation and R&D**: Continuously investing in research and development to stay ahead of competitors, introduce new technologies, and enhance product performance could help maintain Nike's competitive edge in the market.\\n\\n5. **Brand Image and Reputation**: Strengthening brand image through effective marketing campaigns, community engagement, and transparent communication with stakeholders can help build trust and loyalty among consumers.\" response_metadata={'token_usage': {'completion_tokens': 205, 'prompt_tokens': 298, 'total_tokens': 503}, 'model_name': 'gpt-3.5-turbo', 'system_fingerprint': 'fp_3b956da36b', 'finish_reason': 'stop', 'logprobs': None}\n",
      "Running task:  What are the potential cost-saving strategies Nike could implement to increase its net revenue in Q3 2024?\n",
      "\u001b[33mInitializing Autonomous Agent Writer agent...\u001b[0m\n",
      "\u001b[1m\u001b[36mAutonomous Agent Activated.\u001b[0m\n",
      "\u001b[32mAll systems operational. Executing task...\u001b[0m\n",
      "\u001b[36m\n",
      "Loop 1 of 1\u001b[0m\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "content='### Potential Cost-Saving Strategies for Nike to Increase Net Revenue in Q3 2024\\n\\n1. **Supply Chain Optimization**: Streamlining the supply chain, reducing transportation costs, and improving inventory management can lead to significant cost savings for Nike.\\n\\n2. **Operational Efficiency**: Implementing lean manufacturing practices, reducing waste, and optimizing production processes can help lower production costs and improve overall efficiency.\\n\\n3. **Outsourcing Non-Core Functions**: Outsourcing non-core functions such as IT services, customer support, or logistics can help reduce overhead costs and focus resources on core business activities.\\n\\n4. **Energy Efficiency**: Investing in energy-efficient technologies, renewable energy sources, and sustainable practices can lower utility costs and demonstrate a commitment to environmental responsibility.\\n\\n5. **Negotiating Supplier Contracts**: Negotiating better terms with suppliers, leveraging economies of scale, and exploring alternative sourcing options can help lower procurement costs and improve margins.\\n\\nBy implementing these cost-saving strategies, Nike can improve its bottom line and increase net revenue in Q3 2024.' response_metadata={'token_usage': {'completion_tokens': 207, 'prompt_tokens': 633, 'total_tokens': 840}, 'model_name': 'gpt-3.5-turbo', 'system_fingerprint': 'fp_a450710239', 'finish_reason': 'stop', 'logprobs': None}\n",
      "\u001b[32mSaved agent state to: Writer agent_state.json\u001b[0m\n",
      "content='### Potential Cost-Saving Strategies for Nike to Increase Net Revenue in Q3 2024\\n\\n1. **Supply Chain Optimization**: Streamlining the supply chain, reducing transportation costs, and improving inventory management can lead to significant cost savings for Nike.\\n\\n2. **Operational Efficiency**: Implementing lean manufacturing practices, reducing waste, and optimizing production processes can help lower production costs and improve overall efficiency.\\n\\n3. **Outsourcing Non-Core Functions**: Outsourcing non-core functions such as IT services, customer support, or logistics can help reduce overhead costs and focus resources on core business activities.\\n\\n4. **Energy Efficiency**: Investing in energy-efficient technologies, renewable energy sources, and sustainable practices can lower utility costs and demonstrate a commitment to environmental responsibility.\\n\\n5. **Negotiating Supplier Contracts**: Negotiating better terms with suppliers, leveraging economies of scale, and exploring alternative sourcing options can help lower procurement costs and improve margins.\\n\\nBy implementing these cost-saving strategies, Nike can improve its bottom line and increase net revenue in Q3 2024.' response_metadata={'token_usage': {'completion_tokens': 207, 'prompt_tokens': 633, 'total_tokens': 840}, 'model_name': 'gpt-3.5-turbo', 'system_fingerprint': 'fp_a450710239', 'finish_reason': 'stop', 'logprobs': None}\n",
      "Running task:  What are the projected market trends for the sports apparel industry in 2024?\n",
      "\u001b[33mInitializing Autonomous Agent Writer agent...\u001b[0m\n",
      "\u001b[1m\u001b[36mAutonomous Agent Activated.\u001b[0m\n",
      "\u001b[32mAll systems operational. Executing task...\u001b[0m\n",
      "\u001b[36m\n",
      "Loop 1 of 1\u001b[0m\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "content='### Projected Market Trends for the Sports Apparel Industry in 2024\\n\\n1. **Sustainable Fashion**: Consumers are increasingly demanding eco-friendly and sustainable products, leading to a rise in sustainable sportswear options in the market.\\n\\n2. **Digital Transformation**: The sports apparel industry is expected to continue its shift towards digital platforms, with a focus on e-commerce, personalized shopping experiences, and digital marketing strategies.\\n\\n3. **Athleisure Wear**: The trend of athleisure wear, which combines athletic and leisure clothing, is projected to remain popular in 2024 as consumers seek comfort and versatility in their apparel choices.\\n\\n4. **Innovative Materials**: Advances in technology and material science are likely to drive the development of innovative fabrics and performance-enhancing materials in sports apparel, catering to the demand for high-quality and functional products.\\n\\n5. **Health and Wellness Focus**: With a growing emphasis on health and wellness, sports apparel brands are expected to incorporate features that promote comfort, performance, and overall well-being in their products.\\n\\nOverall, the sports apparel industry in 2024 is anticipated to be characterized by sustainability, digitalization, innovation, and a focus on consumer health and lifestyle trends.' response_metadata={'token_usage': {'completion_tokens': 240, 'prompt_tokens': 963, 'total_tokens': 1203}, 'model_name': 'gpt-3.5-turbo', 'system_fingerprint': 'fp_3b956da36b', 'finish_reason': 'stop', 'logprobs': None}\n",
      "\u001b[32mSaved agent state to: Writer agent_state.json\u001b[0m\n",
      "content='### Projected Market Trends for the Sports Apparel Industry in 2024\\n\\n1. **Sustainable Fashion**: Consumers are increasingly demanding eco-friendly and sustainable products, leading to a rise in sustainable sportswear options in the market.\\n\\n2. **Digital Transformation**: The sports apparel industry is expected to continue its shift towards digital platforms, with a focus on e-commerce, personalized shopping experiences, and digital marketing strategies.\\n\\n3. **Athleisure Wear**: The trend of athleisure wear, which combines athletic and leisure clothing, is projected to remain popular in 2024 as consumers seek comfort and versatility in their apparel choices.\\n\\n4. **Innovative Materials**: Advances in technology and material science are likely to drive the development of innovative fabrics and performance-enhancing materials in sports apparel, catering to the demand for high-quality and functional products.\\n\\n5. **Health and Wellness Focus**: With a growing emphasis on health and wellness, sports apparel brands are expected to incorporate features that promote comfort, performance, and overall well-being in their products.\\n\\nOverall, the sports apparel industry in 2024 is anticipated to be characterized by sustainability, digitalization, innovation, and a focus on consumer health and lifestyle trends.' response_metadata={'token_usage': {'completion_tokens': 240, 'prompt_tokens': 963, 'total_tokens': 1203}, 'model_name': 'gpt-3.5-turbo', 'system_fingerprint': 'fp_3b956da36b', 'finish_reason': 'stop', 'logprobs': None}\n",
      "Running task:  What are the current successful strategies being used by Nike's competitors?\n",
      "\u001b[33mInitializing Autonomous Agent Writer agent...\u001b[0m\n",
      "\u001b[1m\u001b[36mAutonomous Agent Activated.\u001b[0m\n",
      "\u001b[32mAll systems operational. Executing task...\u001b[0m\n",
      "\u001b[36m\n",
      "Loop 1 of 1\u001b[0m\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "content=\"### Current Successful Strategies Used by Nike's Competitors\\n\\n1. **Adidas**: Adidas has been successful in leveraging collaborations with celebrities and designers to create limited-edition collections that generate hype and drive sales. They have also focused on sustainability initiatives, such as using recycled materials in their products, to appeal to environmentally conscious consumers.\\n\\n2. **Under Armour**: Under Armour has differentiated itself by targeting performance-driven athletes and emphasizing technological innovation in their products. They have also invested heavily in digital marketing and e-commerce to reach a wider audience and enhance the customer shopping experience.\\n\\n3. **Puma**: Puma has successfully capitalized on the athleisure trend by offering stylish and versatile sportswear that can be worn both in and out of the gym. They have also focused on building partnerships with influencers and sponsoring high-profile athletes to increase brand visibility and credibility.\\n\\n4. **Lululemon**: Lululemon has excelled in creating a strong community around its brand, hosting events, classes, and collaborations to engage with customers beyond just selling products. They have also prioritized customer experience by offering personalized services and creating a seamless omnichannel shopping experience.\\n\\n5. **New Balance**: New Balance has carved out a niche in the market by emphasizing quality craftsmanship, heritage, and authenticity in their products. They have also focused on customization and personalization options for customers, allowing them to create unique and tailored footwear and apparel.\\n\\nOverall, Nike's competitors have found success through a combination of innovative product offerings, strategic marketing initiatives, and a focus on customer engagement and experience.\" response_metadata={'token_usage': {'completion_tokens': 313, 'prompt_tokens': 1327, 'total_tokens': 1640}, 'model_name': 'gpt-3.5-turbo', 'system_fingerprint': 'fp_a450710239', 'finish_reason': 'stop', 'logprobs': None}\n",
      "\u001b[32mSaved agent state to: Writer agent_state.json\u001b[0m\n",
      "content=\"### Current Successful Strategies Used by Nike's Competitors\\n\\n1. **Adidas**: Adidas has been successful in leveraging collaborations with celebrities and designers to create limited-edition collections that generate hype and drive sales. They have also focused on sustainability initiatives, such as using recycled materials in their products, to appeal to environmentally conscious consumers.\\n\\n2. **Under Armour**: Under Armour has differentiated itself by targeting performance-driven athletes and emphasizing technological innovation in their products. They have also invested heavily in digital marketing and e-commerce to reach a wider audience and enhance the customer shopping experience.\\n\\n3. **Puma**: Puma has successfully capitalized on the athleisure trend by offering stylish and versatile sportswear that can be worn both in and out of the gym. They have also focused on building partnerships with influencers and sponsoring high-profile athletes to increase brand visibility and credibility.\\n\\n4. **Lululemon**: Lululemon has excelled in creating a strong community around its brand, hosting events, classes, and collaborations to engage with customers beyond just selling products. They have also prioritized customer experience by offering personalized services and creating a seamless omnichannel shopping experience.\\n\\n5. **New Balance**: New Balance has carved out a niche in the market by emphasizing quality craftsmanship, heritage, and authenticity in their products. They have also focused on customization and personalization options for customers, allowing them to create unique and tailored footwear and apparel.\\n\\nOverall, Nike's competitors have found success through a combination of innovative product offerings, strategic marketing initiatives, and a focus on customer engagement and experience.\" response_metadata={'token_usage': {'completion_tokens': 313, 'prompt_tokens': 1327, 'total_tokens': 1640}, 'model_name': 'gpt-3.5-turbo', 'system_fingerprint': 'fp_a450710239', 'finish_reason': 'stop', 'logprobs': None}\n",
      "Running task:  What are the current and projected economic conditions in Nike's major markets?\n",
      "\u001b[33mInitializing Autonomous Agent Writer agent...\u001b[0m\n",
      "\u001b[1m\u001b[36mAutonomous Agent Activated.\u001b[0m\n",
      "\u001b[32mAll systems operational. Executing task...\u001b[0m\n",
      "\u001b[36m\n",
      "Loop 1 of 1\u001b[0m\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "content='Writer agent: content=\"### Current and Projected Economic Conditions in Nike\\'s Major Markets\\\\n\\\\n1. **United States**: The United States, being one of Nike\\'s largest markets, is currently experiencing moderate economic growth driven by consumer spending, low unemployment rates, and a rebound in manufacturing. However, uncertainties surrounding trade policies, inflation, and interest rates could impact consumer confidence and spending in the near future.\\\\n\\\\n2. **China**: China remains a key market for Nike, with a growing middle class and increasing demand for sportswear and athletic footwear. Despite recent trade tensions with the U.S., China\\'s economy is projected to continue expanding, driven by domestic consumption, infrastructure investments, and technological advancements.\\\\n\\\\n3. **Europe**: Economic conditions in Europe vary across countries, with some experiencing sluggish growth due to Brexit uncertainties, political instability, and trade tensions. However, overall consumer confidence is improving, and the sports apparel market is expected to grow, driven by e-commerce and sustainability trends.\\\\n\\\\n4. **Emerging Markets**: Nike\\'s presence in emerging markets such as India, Brazil, and Southeast Asia provides opportunities for growth, given the rising disposable incomes, urbanization, and increasing focus on health and fitness. However, challenges such as currency fluctuations, regulatory changes, and competition from local brands could impact Nike\\'s performance in these markets.\\\\n\\\\nOverall, Nike\\'s major markets exhibit a mix of opportunities and challenges, with economic conditions influenced by global trends, geopolitical factors, and consumer preferences.\" response_metadata={\\'token_usage\\': {\\'completion_tokens\\': 287, \\'prompt_tokens\\': 1184, \\'total_tokens\\': 1471}, \\'model_name\\': \\'gpt-3.5-turbo\\', \\'system_fingerprint\\': \\'fp_a450710239\\', \\'finish_reason\\': \\'stop\\', \\'logprobs\\': None}' response_metadata={'token_usage': {'completion_tokens': 372, 'prompt_tokens': 1763, 'total_tokens': 2135}, 'model_name': 'gpt-3.5-turbo', 'system_fingerprint': 'fp_3b956da36b', 'finish_reason': 'stop', 'logprobs': None}\n",
      "\u001b[32mSaved agent state to: Writer agent_state.json\u001b[0m\n",
      "content='Writer agent: content=\"### Current and Projected Economic Conditions in Nike\\'s Major Markets\\\\n\\\\n1. **United States**: The United States, being one of Nike\\'s largest markets, is currently experiencing moderate economic growth driven by consumer spending, low unemployment rates, and a rebound in manufacturing. However, uncertainties surrounding trade policies, inflation, and interest rates could impact consumer confidence and spending in the near future.\\\\n\\\\n2. **China**: China remains a key market for Nike, with a growing middle class and increasing demand for sportswear and athletic footwear. Despite recent trade tensions with the U.S., China\\'s economy is projected to continue expanding, driven by domestic consumption, infrastructure investments, and technological advancements.\\\\n\\\\n3. **Europe**: Economic conditions in Europe vary across countries, with some experiencing sluggish growth due to Brexit uncertainties, political instability, and trade tensions. However, overall consumer confidence is improving, and the sports apparel market is expected to grow, driven by e-commerce and sustainability trends.\\\\n\\\\n4. **Emerging Markets**: Nike\\'s presence in emerging markets such as India, Brazil, and Southeast Asia provides opportunities for growth, given the rising disposable incomes, urbanization, and increasing focus on health and fitness. However, challenges such as currency fluctuations, regulatory changes, and competition from local brands could impact Nike\\'s performance in these markets.\\\\n\\\\nOverall, Nike\\'s major markets exhibit a mix of opportunities and challenges, with economic conditions influenced by global trends, geopolitical factors, and consumer preferences.\" response_metadata={\\'token_usage\\': {\\'completion_tokens\\': 287, \\'prompt_tokens\\': 1184, \\'total_tokens\\': 1471}, \\'model_name\\': \\'gpt-3.5-turbo\\', \\'system_fingerprint\\': \\'fp_a450710239\\', \\'finish_reason\\': \\'stop\\', \\'logprobs\\': None}' response_metadata={'token_usage': {'completion_tokens': 372, 'prompt_tokens': 1763, 'total_tokens': 2135}, 'model_name': 'gpt-3.5-turbo', 'system_fingerprint': 'fp_3b956da36b', 'finish_reason': 'stop', 'logprobs': None}\n",
      "Running task:  What are the current consumer preferences in the sports apparel industry?\n",
      "\u001b[33mInitializing Autonomous Agent Writer agent...\u001b[0m\n",
      "\u001b[1m\u001b[36mAutonomous Agent Activated.\u001b[0m\n",
      "\u001b[32mAll systems operational. Executing task...\u001b[0m\n",
      "\u001b[36m\n",
      "Loop 1 of 1\u001b[0m\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "content='### Current Consumer Preferences in the Sports Apparel Industry\\n\\n1. **Sustainability**: Consumers are increasingly seeking eco-friendly and sustainable options in sports apparel, driving brands to focus on using recycled materials, reducing waste, and promoting ethical practices.\\n\\n2. **Athleisure**: The trend of athleisure wear continues to be popular, with consumers looking for versatile and comfortable clothing that can be worn both during workouts and in everyday life.\\n\\n3. **Performance and Functionality**: Consumers prioritize performance-enhancing features in sports apparel, such as moisture-wicking fabrics, breathable materials, and ergonomic designs that enhance comfort and mobility.\\n\\n4. **Personalization**: Customization options, personalized fit, and unique design elements are appealing to consumers who seek individuality and exclusivity in their sports apparel choices.\\n\\n5. **Brand Transparency**: Consumers value transparency in brand practices, including supply chain transparency, ethical sourcing, and clear communication on product quality and manufacturing processes.\\n\\nOverall, consumer preferences in the sports apparel industry are shifting towards sustainability, versatility, performance, personalization, and transparency, influencing brand strategies and product offerings.' response_metadata={'token_usage': {'completion_tokens': 218, 'prompt_tokens': 2274, 'total_tokens': 2492}, 'model_name': 'gpt-3.5-turbo', 'system_fingerprint': 'fp_3b956da36b', 'finish_reason': 'stop', 'logprobs': None}\n",
      "\u001b[32mSaved agent state to: Writer agent_state.json\u001b[0m\n",
      "content='### Current Consumer Preferences in the Sports Apparel Industry\\n\\n1. **Sustainability**: Consumers are increasingly seeking eco-friendly and sustainable options in sports apparel, driving brands to focus on using recycled materials, reducing waste, and promoting ethical practices.\\n\\n2. **Athleisure**: The trend of athleisure wear continues to be popular, with consumers looking for versatile and comfortable clothing that can be worn both during workouts and in everyday life.\\n\\n3. **Performance and Functionality**: Consumers prioritize performance-enhancing features in sports apparel, such as moisture-wicking fabrics, breathable materials, and ergonomic designs that enhance comfort and mobility.\\n\\n4. **Personalization**: Customization options, personalized fit, and unique design elements are appealing to consumers who seek individuality and exclusivity in their sports apparel choices.\\n\\n5. **Brand Transparency**: Consumers value transparency in brand practices, including supply chain transparency, ethical sourcing, and clear communication on product quality and manufacturing processes.\\n\\nOverall, consumer preferences in the sports apparel industry are shifting towards sustainability, versatility, performance, personalization, and transparency, influencing brand strategies and product offerings.' response_metadata={'token_usage': {'completion_tokens': 218, 'prompt_tokens': 2274, 'total_tokens': 2492}, 'model_name': 'gpt-3.5-turbo', 'system_fingerprint': 'fp_3b956da36b', 'finish_reason': 'stop', 'logprobs': None}\n",
      "Running task:  What are the potential new markets for Nike to explore in 2024?\n",
      "\u001b[33mInitializing Autonomous Agent Writer agent...\u001b[0m\n",
      "\u001b[1m\u001b[36mAutonomous Agent Activated.\u001b[0m\n",
      "\u001b[32mAll systems operational. Executing task...\u001b[0m\n",
      "\u001b[36m\n",
      "Loop 1 of 1\u001b[0m\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "content=\"### Potential New Markets for Nike to Explore in 2024\\n\\n1. **India**: With a growing population, increasing disposable incomes, and a rising interest in health and fitness, India presents a significant opportunity for Nike to expand its presence and tap into a large consumer base.\\n\\n2. **Africa**: The African market, particularly countries with emerging economies and a young population, offers potential for Nike to introduce its products and capitalize on the growing demand for sportswear and athletic footwear.\\n\\n3. **Middle East**: Countries in the Middle East, known for their luxury shopping destinations and a growing interest in sports and fitness activities, could be strategic markets for Nike to target and establish a strong foothold.\\n\\n4. **Latin America**: Markets in Latin America, such as Brazil, Mexico, and Argentina, present opportunities for Nike to cater to a diverse consumer base and leverage the region's passion for sports and active lifestyles.\\n\\n5. **Southeast Asia**: Rapid urbanization, increasing urban middle-class population, and a trend towards health and wellness in countries like Indonesia, Thailand, and Vietnam make Southeast Asia an attractive region for Nike to explore and expand its market reach.\\n\\nBy exploring these new markets in 2024, Nike can diversify its geographical presence, reach untapped consumer segments, and drive growth in emerging economies.\" response_metadata={'token_usage': {'completion_tokens': 262, 'prompt_tokens': 2619, 'total_tokens': 2881}, 'model_name': 'gpt-3.5-turbo', 'system_fingerprint': 'fp_3b956da36b', 'finish_reason': 'stop', 'logprobs': None}\n",
      "\u001b[32mSaved agent state to: Writer agent_state.json\u001b[0m\n",
      "content=\"### Potential New Markets for Nike to Explore in 2024\\n\\n1. **India**: With a growing population, increasing disposable incomes, and a rising interest in health and fitness, India presents a significant opportunity for Nike to expand its presence and tap into a large consumer base.\\n\\n2. **Africa**: The African market, particularly countries with emerging economies and a young population, offers potential for Nike to introduce its products and capitalize on the growing demand for sportswear and athletic footwear.\\n\\n3. **Middle East**: Countries in the Middle East, known for their luxury shopping destinations and a growing interest in sports and fitness activities, could be strategic markets for Nike to target and establish a strong foothold.\\n\\n4. **Latin America**: Markets in Latin America, such as Brazil, Mexico, and Argentina, present opportunities for Nike to cater to a diverse consumer base and leverage the region's passion for sports and active lifestyles.\\n\\n5. **Southeast Asia**: Rapid urbanization, increasing urban middle-class population, and a trend towards health and wellness in countries like Indonesia, Thailand, and Vietnam make Southeast Asia an attractive region for Nike to explore and expand its market reach.\\n\\nBy exploring these new markets in 2024, Nike can diversify its geographical presence, reach untapped consumer segments, and drive growth in emerging economies.\" response_metadata={'token_usage': {'completion_tokens': 262, 'prompt_tokens': 2619, 'total_tokens': 2881}, 'model_name': 'gpt-3.5-turbo', 'system_fingerprint': 'fp_3b956da36b', 'finish_reason': 'stop', 'logprobs': None}\n",
      "Running task:  What are the potential new products or services Nike could introduce in 2024?\n",
      "\u001b[33mInitializing Autonomous Agent Writer agent...\u001b[0m\n",
      "\u001b[1m\u001b[36mAutonomous Agent Activated.\u001b[0m\n",
      "\u001b[32mAll systems operational. Executing task...\u001b[0m\n",
      "\u001b[36m\n",
      "Loop 1 of 1\u001b[0m\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "content=\"### Potential New Products or Services Nike Could Introduce in 2024\\n\\n1. **Smart Apparel**: Nike could explore the integration of technology into its apparel, such as smart fabrics that monitor performance metrics, provide feedback, or enhance comfort during workouts.\\n\\n2. **Athletic Accessories**: Introducing a line of athletic accessories like gym bags, water bottles, or fitness trackers could complement Nike's existing product offerings and provide additional value to customers.\\n\\n3. **Customization Platforms**: Offering personalized design options for footwear and apparel through online customization platforms could appeal to consumers seeking unique and tailored products.\\n\\n4. **Athletic Recovery Gear**: Developing recovery-focused products like compression wear, recovery sandals, or massage tools could cater to athletes and fitness enthusiasts looking to enhance post-workout recovery.\\n\\n5. **Sustainable Collections**: Launching sustainable collections made from eco-friendly materials, recycled fabrics, or biodegradable components could align with consumer preferences for environmentally conscious products.\\n\\nBy introducing these new products or services in 2024, Nike can innovate its product portfolio, cater to evolving consumer needs, and differentiate itself in the competitive sports apparel market.\" response_metadata={'token_usage': {'completion_tokens': 224, 'prompt_tokens': 3009, 'total_tokens': 3233}, 'model_name': 'gpt-3.5-turbo', 'system_fingerprint': 'fp_a450710239', 'finish_reason': 'stop', 'logprobs': None}\n",
      "\u001b[32mSaved agent state to: Writer agent_state.json\u001b[0m\n",
      "content=\"### Potential New Products or Services Nike Could Introduce in 2024\\n\\n1. **Smart Apparel**: Nike could explore the integration of technology into its apparel, such as smart fabrics that monitor performance metrics, provide feedback, or enhance comfort during workouts.\\n\\n2. **Athletic Accessories**: Introducing a line of athletic accessories like gym bags, water bottles, or fitness trackers could complement Nike's existing product offerings and provide additional value to customers.\\n\\n3. **Customization Platforms**: Offering personalized design options for footwear and apparel through online customization platforms could appeal to consumers seeking unique and tailored products.\\n\\n4. **Athletic Recovery Gear**: Developing recovery-focused products like compression wear, recovery sandals, or massage tools could cater to athletes and fitness enthusiasts looking to enhance post-workout recovery.\\n\\n5. **Sustainable Collections**: Launching sustainable collections made from eco-friendly materials, recycled fabrics, or biodegradable components could align with consumer preferences for environmentally conscious products.\\n\\nBy introducing these new products or services in 2024, Nike can innovate its product portfolio, cater to evolving consumer needs, and differentiate itself in the competitive sports apparel market.\" response_metadata={'token_usage': {'completion_tokens': 224, 'prompt_tokens': 3009, 'total_tokens': 3233}, 'model_name': 'gpt-3.5-turbo', 'system_fingerprint': 'fp_a450710239', 'finish_reason': 'stop', 'logprobs': None}\n",
      "Running task:  What are the potential marketing strategies Nike could use to increase its revenue in Q3 2024?\n",
      "\u001b[33mInitializing Autonomous Agent Writer agent...\u001b[0m\n",
      "\u001b[1m\u001b[36mAutonomous Agent Activated.\u001b[0m\n",
      "\u001b[32mAll systems operational. Executing task...\u001b[0m\n",
      "\u001b[36m\n",
      "Loop 1 of 1\u001b[0m\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "content='### Potential Marketing Strategies for Nike to Increase Revenue in Q3 2024\\n\\n1. **Influencer Partnerships**: Collaborating with popular athletes, celebrities, or social media influencers to promote Nike products can help reach a wider audience and drive sales.\\n\\n2. **Interactive Campaigns**: Launching interactive marketing campaigns, contests, or events that engage customers and create buzz around new product releases can generate excitement and increase brand visibility.\\n\\n3. **Social Media Engagement**: Leveraging social media platforms to connect with consumers, share user-generated content, and respond to feedback can build brand loyalty and encourage repeat purchases.\\n\\n4. **Localized Marketing**: Tailoring marketing messages, promotions, and product offerings to specific regions or target demographics can enhance relevance and appeal to diverse consumer groups.\\n\\n5. **Customer Loyalty Programs**: Implementing loyalty programs, exclusive offers, or rewards for repeat customers can incentivize brand loyalty, increase retention rates, and drive higher lifetime customer value.\\n\\nBy employing these marketing strategies in Q3 2024, Nike can enhance its brand presence, attract new customers, and ultimately boost revenue growth.' response_metadata={'token_usage': {'completion_tokens': 220, 'prompt_tokens': 3362, 'total_tokens': 3582}, 'model_name': 'gpt-3.5-turbo', 'system_fingerprint': 'fp_3b956da36b', 'finish_reason': 'stop', 'logprobs': None}\n",
      "\u001b[32mSaved agent state to: Writer agent_state.json\u001b[0m\n",
      "content='### Potential Marketing Strategies for Nike to Increase Revenue in Q3 2024\\n\\n1. **Influencer Partnerships**: Collaborating with popular athletes, celebrities, or social media influencers to promote Nike products can help reach a wider audience and drive sales.\\n\\n2. **Interactive Campaigns**: Launching interactive marketing campaigns, contests, or events that engage customers and create buzz around new product releases can generate excitement and increase brand visibility.\\n\\n3. **Social Media Engagement**: Leveraging social media platforms to connect with consumers, share user-generated content, and respond to feedback can build brand loyalty and encourage repeat purchases.\\n\\n4. **Localized Marketing**: Tailoring marketing messages, promotions, and product offerings to specific regions or target demographics can enhance relevance and appeal to diverse consumer groups.\\n\\n5. **Customer Loyalty Programs**: Implementing loyalty programs, exclusive offers, or rewards for repeat customers can incentivize brand loyalty, increase retention rates, and drive higher lifetime customer value.\\n\\nBy employing these marketing strategies in Q3 2024, Nike can enhance its brand presence, attract new customers, and ultimately boost revenue growth.' response_metadata={'token_usage': {'completion_tokens': 220, 'prompt_tokens': 3362, 'total_tokens': 3582}, 'model_name': 'gpt-3.5-turbo', 'system_fingerprint': 'fp_3b956da36b', 'finish_reason': 'stop', 'logprobs': None}\n"
     ]
    }
   ],
   "source": [
    "for node in bfs_order:\n",
    "    sub_query =nodes_info[node]['query']\n",
    "    print(\"Running task: \", sub_query)\n",
    "    out = agent.run(f\"Consider: {sub_query}. Write response in strict markdown format using long-term memory. Do not mention Writer Agent in response.\")\n",
    "    print(out)\n",
    "    try:\n",
    "        report.append(out.content)\n",
    "    except:\n",
    "        pass"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, we need to clean up the repoort a bit to make it render professionally. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 189,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Remove any content before the first \"#\" as that signals start of heading\n",
    "# Anything before this usually contains filler content\n",
    "stripped_report = [entry[entry.find('#'):] if '#' in entry else entry for entry in report]\n",
    "report = stripped_report"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 190,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[\"### Nike's Current Revenue Trend\\n\\nNike's current revenue trend has been steadily increasing over the past few years. In the most recent fiscal year, Nike reported a revenue of $37.4 billion, which was a 7% increase from the previous year. This growth can be attributed to strong sales in key markets, successful marketing campaigns, and a focus on innovation in product development. Overall, Nike continues to demonstrate strong financial performance and is well-positioned for future growth.\",\n",
       " \"### Potential Areas of Improvement in Nike's Business Model\\n\\n1. **Sustainability Practices**: Nike could further enhance its sustainability efforts by reducing its carbon footprint, using more eco-friendly materials, and ensuring ethical labor practices throughout its supply chain.\\n\\n2. **Diversification of Product Portfolio**: While Nike is known for its athletic footwear and apparel, diversifying into new product categories or expanding into untapped markets could help drive growth and mitigate risks associated with a single product line.\\n\\n3. **E-commerce Strategy**: Improving the online shopping experience, investing in digital marketing, and leveraging data analytics to personalize customer interactions could boost online sales and customer loyalty.\\n\\n4. **Innovation and R&D**: Continuously investing in research and development to stay ahead of competitors, introduce new technologies, and enhance product performance could help maintain Nike's competitive edge in the market.\\n\\n5. **Brand Image and Reputation**: Strengthening brand image through effective marketing campaigns, community engagement, and transparent communication with stakeholders can help build trust and loyalty among consumers.\",\n",
       " '### Potential Cost-Saving Strategies for Nike to Increase Net Revenue in Q3 2024\\n\\n1. **Supply Chain Optimization**: Streamlining the supply chain, reducing transportation costs, and improving inventory management can lead to significant cost savings for Nike.\\n\\n2. **Operational Efficiency**: Implementing lean manufacturing practices, reducing waste, and optimizing production processes can help lower production costs and improve overall efficiency.\\n\\n3. **Outsourcing Non-Core Functions**: Outsourcing non-core functions such as IT services, customer support, or logistics can help reduce overhead costs and focus resources on core business activities.\\n\\n4. **Energy Efficiency**: Investing in energy-efficient technologies, renewable energy sources, and sustainable practices can lower utility costs and demonstrate a commitment to environmental responsibility.\\n\\n5. **Negotiating Supplier Contracts**: Negotiating better terms with suppliers, leveraging economies of scale, and exploring alternative sourcing options can help lower procurement costs and improve margins.\\n\\nBy implementing these cost-saving strategies, Nike can improve its bottom line and increase net revenue in Q3 2024.',\n",
       " '### Projected Market Trends for the Sports Apparel Industry in 2024\\n\\n1. **Sustainable Fashion**: Consumers are increasingly demanding eco-friendly and sustainable products, leading to a rise in sustainable sportswear options in the market.\\n\\n2. **Digital Transformation**: The sports apparel industry is expected to continue its shift towards digital platforms, with a focus on e-commerce, personalized shopping experiences, and digital marketing strategies.\\n\\n3. **Athleisure Wear**: The trend of athleisure wear, which combines athletic and leisure clothing, is projected to remain popular in 2024 as consumers seek comfort and versatility in their apparel choices.\\n\\n4. **Innovative Materials**: Advances in technology and material science are likely to drive the development of innovative fabrics and performance-enhancing materials in sports apparel, catering to the demand for high-quality and functional products.\\n\\n5. **Health and Wellness Focus**: With a growing emphasis on health and wellness, sports apparel brands are expected to incorporate features that promote comfort, performance, and overall well-being in their products.\\n\\nOverall, the sports apparel industry in 2024 is anticipated to be characterized by sustainability, digitalization, innovation, and a focus on consumer health and lifestyle trends.',\n",
       " \"### Current Successful Strategies Used by Nike's Competitors\\n\\n1. **Adidas**: Adidas has been successful in leveraging collaborations with celebrities and designers to create limited-edition collections that generate hype and drive sales. They have also focused on sustainability initiatives, such as using recycled materials in their products, to appeal to environmentally conscious consumers.\\n\\n2. **Under Armour**: Under Armour has differentiated itself by targeting performance-driven athletes and emphasizing technological innovation in their products. They have also invested heavily in digital marketing and e-commerce to reach a wider audience and enhance the customer shopping experience.\\n\\n3. **Puma**: Puma has successfully capitalized on the athleisure trend by offering stylish and versatile sportswear that can be worn both in and out of the gym. They have also focused on building partnerships with influencers and sponsoring high-profile athletes to increase brand visibility and credibility.\\n\\n4. **Lululemon**: Lululemon has excelled in creating a strong community around its brand, hosting events, classes, and collaborations to engage with customers beyond just selling products. They have also prioritized customer experience by offering personalized services and creating a seamless omnichannel shopping experience.\\n\\n5. **New Balance**: New Balance has carved out a niche in the market by emphasizing quality craftsmanship, heritage, and authenticity in their products. They have also focused on customization and personalization options for customers, allowing them to create unique and tailored footwear and apparel.\\n\\nOverall, Nike's competitors have found success through a combination of innovative product offerings, strategic marketing initiatives, and a focus on customer engagement and experience.\",\n",
       " '### Current and Projected Economic Conditions in Nike\\'s Major Markets\\\\n\\\\n1. **United States**: The United States, being one of Nike\\'s largest markets, is currently experiencing moderate economic growth driven by consumer spending, low unemployment rates, and a rebound in manufacturing. However, uncertainties surrounding trade policies, inflation, and interest rates could impact consumer confidence and spending in the near future.\\\\n\\\\n2. **China**: China remains a key market for Nike, with a growing middle class and increasing demand for sportswear and athletic footwear. Despite recent trade tensions with the U.S., China\\'s economy is projected to continue expanding, driven by domestic consumption, infrastructure investments, and technological advancements.\\\\n\\\\n3. **Europe**: Economic conditions in Europe vary across countries, with some experiencing sluggish growth due to Brexit uncertainties, political instability, and trade tensions. However, overall consumer confidence is improving, and the sports apparel market is expected to grow, driven by e-commerce and sustainability trends.\\\\n\\\\n4. **Emerging Markets**: Nike\\'s presence in emerging markets such as India, Brazil, and Southeast Asia provides opportunities for growth, given the rising disposable incomes, urbanization, and increasing focus on health and fitness. However, challenges such as currency fluctuations, regulatory changes, and competition from local brands could impact Nike\\'s performance in these markets.\\\\n\\\\nOverall, Nike\\'s major markets exhibit a mix of opportunities and challenges, with economic conditions influenced by global trends, geopolitical factors, and consumer preferences.\" response_metadata={\\'token_usage\\': {\\'completion_tokens\\': 287, \\'prompt_tokens\\': 1184, \\'total_tokens\\': 1471}, \\'model_name\\': \\'gpt-3.5-turbo\\', \\'system_fingerprint\\': \\'fp_a450710239\\', \\'finish_reason\\': \\'stop\\', \\'logprobs\\': None}',\n",
       " '### Current Consumer Preferences in the Sports Apparel Industry\\n\\n1. **Sustainability**: Consumers are increasingly seeking eco-friendly and sustainable options in sports apparel, driving brands to focus on using recycled materials, reducing waste, and promoting ethical practices.\\n\\n2. **Athleisure**: The trend of athleisure wear continues to be popular, with consumers looking for versatile and comfortable clothing that can be worn both during workouts and in everyday life.\\n\\n3. **Performance and Functionality**: Consumers prioritize performance-enhancing features in sports apparel, such as moisture-wicking fabrics, breathable materials, and ergonomic designs that enhance comfort and mobility.\\n\\n4. **Personalization**: Customization options, personalized fit, and unique design elements are appealing to consumers who seek individuality and exclusivity in their sports apparel choices.\\n\\n5. **Brand Transparency**: Consumers value transparency in brand practices, including supply chain transparency, ethical sourcing, and clear communication on product quality and manufacturing processes.\\n\\nOverall, consumer preferences in the sports apparel industry are shifting towards sustainability, versatility, performance, personalization, and transparency, influencing brand strategies and product offerings.',\n",
       " \"### Potential New Markets for Nike to Explore in 2024\\n\\n1. **India**: With a growing population, increasing disposable incomes, and a rising interest in health and fitness, India presents a significant opportunity for Nike to expand its presence and tap into a large consumer base.\\n\\n2. **Africa**: The African market, particularly countries with emerging economies and a young population, offers potential for Nike to introduce its products and capitalize on the growing demand for sportswear and athletic footwear.\\n\\n3. **Middle East**: Countries in the Middle East, known for their luxury shopping destinations and a growing interest in sports and fitness activities, could be strategic markets for Nike to target and establish a strong foothold.\\n\\n4. **Latin America**: Markets in Latin America, such as Brazil, Mexico, and Argentina, present opportunities for Nike to cater to a diverse consumer base and leverage the region's passion for sports and active lifestyles.\\n\\n5. **Southeast Asia**: Rapid urbanization, increasing urban middle-class population, and a trend towards health and wellness in countries like Indonesia, Thailand, and Vietnam make Southeast Asia an attractive region for Nike to explore and expand its market reach.\\n\\nBy exploring these new markets in 2024, Nike can diversify its geographical presence, reach untapped consumer segments, and drive growth in emerging economies.\",\n",
       " \"### Potential New Products or Services Nike Could Introduce in 2024\\n\\n1. **Smart Apparel**: Nike could explore the integration of technology into its apparel, such as smart fabrics that monitor performance metrics, provide feedback, or enhance comfort during workouts.\\n\\n2. **Athletic Accessories**: Introducing a line of athletic accessories like gym bags, water bottles, or fitness trackers could complement Nike's existing product offerings and provide additional value to customers.\\n\\n3. **Customization Platforms**: Offering personalized design options for footwear and apparel through online customization platforms could appeal to consumers seeking unique and tailored products.\\n\\n4. **Athletic Recovery Gear**: Developing recovery-focused products like compression wear, recovery sandals, or massage tools could cater to athletes and fitness enthusiasts looking to enhance post-workout recovery.\\n\\n5. **Sustainable Collections**: Launching sustainable collections made from eco-friendly materials, recycled fabrics, or biodegradable components could align with consumer preferences for environmentally conscious products.\\n\\nBy introducing these new products or services in 2024, Nike can innovate its product portfolio, cater to evolving consumer needs, and differentiate itself in the competitive sports apparel market.\",\n",
       " '### Potential Marketing Strategies for Nike to Increase Revenue in Q3 2024\\n\\n1. **Influencer Partnerships**: Collaborating with popular athletes, celebrities, or social media influencers to promote Nike products can help reach a wider audience and drive sales.\\n\\n2. **Interactive Campaigns**: Launching interactive marketing campaigns, contests, or events that engage customers and create buzz around new product releases can generate excitement and increase brand visibility.\\n\\n3. **Social Media Engagement**: Leveraging social media platforms to connect with consumers, share user-generated content, and respond to feedback can build brand loyalty and encourage repeat purchases.\\n\\n4. **Localized Marketing**: Tailoring marketing messages, promotions, and product offerings to specific regions or target demographics can enhance relevance and appeal to diverse consumer groups.\\n\\n5. **Customer Loyalty Programs**: Implementing loyalty programs, exclusive offers, or rewards for repeat customers can incentivize brand loyalty, increase retention rates, and drive higher lifetime customer value.\\n\\nBy employing these marketing strategies in Q3 2024, Nike can enhance its brand presence, attract new customers, and ultimately boost revenue growth.']"
      ]
     },
     "execution_count": 190,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "report"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 208,
   "metadata": {},
   "outputs": [],
   "source": [
    "# At times the LLM outputs \\\\n instead of \\n\n",
    "cleaned_report = [entry.replace(\"\\\\n\", \"\\n\") for entry in report]\n",
    "import re\n",
    "\n",
    "# Function to clean up unnecessary metadata from the report entries\n",
    "def clean_report(report):\n",
    "    cleaned_report = []\n",
    "    for entry in report:\n",
    "        # This pattern matches 'response_metadata={' followed by any characters that are not '}' (non-greedy), \n",
    "        # possibly nested inside other braces, until the closing '}'.\n",
    "        cleaned_entry = re.sub(r\"response_metadata=\\{[^{}]*(?:\\{[^{}]*\\}[^{}]*)*\\}\", \"\", entry, flags=re.DOTALL)\n",
    "        cleaned_report.append(cleaned_entry)\n",
    "    return cleaned_report\n",
    "\n",
    "# Apply the cleaning function to the markdown report\n",
    "cleaned_report = clean_report(cleaned_report)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "After cleaning, we append parts of the report together to get out final report."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 209,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "### Nike's Current Revenue Trend\n",
      "\n",
      "Nike's current revenue trend has been steadily increasing over the past few years. In the most recent fiscal year, Nike reported a revenue of $37.4 billion, which was a 7% increase from the previous year. This growth can be attributed to strong sales in key markets, successful marketing campaigns, and a focus on innovation in product development. Overall, Nike continues to demonstrate strong financial performance and is well-positioned for future growth. \n",
      " ### Potential Areas of Improvement in Nike's Business Model\n",
      "\n",
      "1. **Sustainability Practices**: Nike could further enhance its sustainability efforts by reducing its carbon footprint, using more eco-friendly materials, and ensuring ethical labor practices throughout its supply chain.\n",
      "\n",
      "2. **Diversification of Product Portfolio**: While Nike is known for its athletic footwear and apparel, diversifying into new product categories or expanding into untapped markets could help drive growth and mitigate risks associated with a single product line.\n",
      "\n",
      "3. **E-commerce Strategy**: Improving the online shopping experience, investing in digital marketing, and leveraging data analytics to personalize customer interactions could boost online sales and customer loyalty.\n",
      "\n",
      "4. **Innovation and R&D**: Continuously investing in research and development to stay ahead of competitors, introduce new technologies, and enhance product performance could help maintain Nike's competitive edge in the market.\n",
      "\n",
      "5. **Brand Image and Reputation**: Strengthening brand image through effective marketing campaigns, community engagement, and transparent communication with stakeholders can help build trust and loyalty among consumers. \n",
      " ### Potential Cost-Saving Strategies for Nike to Increase Net Revenue in Q3 2024\n",
      "\n",
      "1. **Supply Chain Optimization**: Streamlining the supply chain, reducing transportation costs, and improving inventory management can lead to significant cost savings for Nike.\n",
      "\n",
      "2. **Operational Efficiency**: Implementing lean manufacturing practices, reducing waste, and optimizing production processes can help lower production costs and improve overall efficiency.\n",
      "\n",
      "3. **Outsourcing Non-Core Functions**: Outsourcing non-core functions such as IT services, customer support, or logistics can help reduce overhead costs and focus resources on core business activities.\n",
      "\n",
      "4. **Energy Efficiency**: Investing in energy-efficient technologies, renewable energy sources, and sustainable practices can lower utility costs and demonstrate a commitment to environmental responsibility.\n",
      "\n",
      "5. **Negotiating Supplier Contracts**: Negotiating better terms with suppliers, leveraging economies of scale, and exploring alternative sourcing options can help lower procurement costs and improve margins.\n",
      "\n",
      "By implementing these cost-saving strategies, Nike can improve its bottom line and increase net revenue in Q3 2024. \n",
      " ### Projected Market Trends for the Sports Apparel Industry in 2024\n",
      "\n",
      "1. **Sustainable Fashion**: Consumers are increasingly demanding eco-friendly and sustainable products, leading to a rise in sustainable sportswear options in the market.\n",
      "\n",
      "2. **Digital Transformation**: The sports apparel industry is expected to continue its shift towards digital platforms, with a focus on e-commerce, personalized shopping experiences, and digital marketing strategies.\n",
      "\n",
      "3. **Athleisure Wear**: The trend of athleisure wear, which combines athletic and leisure clothing, is projected to remain popular in 2024 as consumers seek comfort and versatility in their apparel choices.\n",
      "\n",
      "4. **Innovative Materials**: Advances in technology and material science are likely to drive the development of innovative fabrics and performance-enhancing materials in sports apparel, catering to the demand for high-quality and functional products.\n",
      "\n",
      "5. **Health and Wellness Focus**: With a growing emphasis on health and wellness, sports apparel brands are expected to incorporate features that promote comfort, performance, and overall well-being in their products.\n",
      "\n",
      "Overall, the sports apparel industry in 2024 is anticipated to be characterized by sustainability, digitalization, innovation, and a focus on consumer health and lifestyle trends. \n",
      " ### Current Successful Strategies Used by Nike's Competitors\n",
      "\n",
      "1. **Adidas**: Adidas has been successful in leveraging collaborations with celebrities and designers to create limited-edition collections that generate hype and drive sales. They have also focused on sustainability initiatives, such as using recycled materials in their products, to appeal to environmentally conscious consumers.\n",
      "\n",
      "2. **Under Armour**: Under Armour has differentiated itself by targeting performance-driven athletes and emphasizing technological innovation in their products. They have also invested heavily in digital marketing and e-commerce to reach a wider audience and enhance the customer shopping experience.\n",
      "\n",
      "3. **Puma**: Puma has successfully capitalized on the athleisure trend by offering stylish and versatile sportswear that can be worn both in and out of the gym. They have also focused on building partnerships with influencers and sponsoring high-profile athletes to increase brand visibility and credibility.\n",
      "\n",
      "4. **Lululemon**: Lululemon has excelled in creating a strong community around its brand, hosting events, classes, and collaborations to engage with customers beyond just selling products. They have also prioritized customer experience by offering personalized services and creating a seamless omnichannel shopping experience.\n",
      "\n",
      "5. **New Balance**: New Balance has carved out a niche in the market by emphasizing quality craftsmanship, heritage, and authenticity in their products. They have also focused on customization and personalization options for customers, allowing them to create unique and tailored footwear and apparel.\n",
      "\n",
      "Overall, Nike's competitors have found success through a combination of innovative product offerings, strategic marketing initiatives, and a focus on customer engagement and experience. \n",
      " ### Current and Projected Economic Conditions in Nike's Major Markets\n",
      "\n",
      "1. **United States**: The United States, being one of Nike's largest markets, is currently experiencing moderate economic growth driven by consumer spending, low unemployment rates, and a rebound in manufacturing. However, uncertainties surrounding trade policies, inflation, and interest rates could impact consumer confidence and spending in the near future.\n",
      "\n",
      "2. **China**: China remains a key market for Nike, with a growing middle class and increasing demand for sportswear and athletic footwear. Despite recent trade tensions with the U.S., China's economy is projected to continue expanding, driven by domestic consumption, infrastructure investments, and technological advancements.\n",
      "\n",
      "3. **Europe**: Economic conditions in Europe vary across countries, with some experiencing sluggish growth due to Brexit uncertainties, political instability, and trade tensions. However, overall consumer confidence is improving, and the sports apparel market is expected to grow, driven by e-commerce and sustainability trends.\n",
      "\n",
      "4. **Emerging Markets**: Nike's presence in emerging markets such as India, Brazil, and Southeast Asia provides opportunities for growth, given the rising disposable incomes, urbanization, and increasing focus on health and fitness. However, challenges such as currency fluctuations, regulatory changes, and competition from local brands could impact Nike's performance in these markets.\n",
      "\n",
      "Overall, Nike's major markets exhibit a mix of opportunities and challenges, with economic conditions influenced by global trends, geopolitical factors, and consumer preferences.\"  \n",
      " ### Current Consumer Preferences in the Sports Apparel Industry\n",
      "\n",
      "1. **Sustainability**: Consumers are increasingly seeking eco-friendly and sustainable options in sports apparel, driving brands to focus on using recycled materials, reducing waste, and promoting ethical practices.\n",
      "\n",
      "2. **Athleisure**: The trend of athleisure wear continues to be popular, with consumers looking for versatile and comfortable clothing that can be worn both during workouts and in everyday life.\n",
      "\n",
      "3. **Performance and Functionality**: Consumers prioritize performance-enhancing features in sports apparel, such as moisture-wicking fabrics, breathable materials, and ergonomic designs that enhance comfort and mobility.\n",
      "\n",
      "4. **Personalization**: Customization options, personalized fit, and unique design elements are appealing to consumers who seek individuality and exclusivity in their sports apparel choices.\n",
      "\n",
      "5. **Brand Transparency**: Consumers value transparency in brand practices, including supply chain transparency, ethical sourcing, and clear communication on product quality and manufacturing processes.\n",
      "\n",
      "Overall, consumer preferences in the sports apparel industry are shifting towards sustainability, versatility, performance, personalization, and transparency, influencing brand strategies and product offerings. \n",
      " ### Potential New Markets for Nike to Explore in 2024\n",
      "\n",
      "1. **India**: With a growing population, increasing disposable incomes, and a rising interest in health and fitness, India presents a significant opportunity for Nike to expand its presence and tap into a large consumer base.\n",
      "\n",
      "2. **Africa**: The African market, particularly countries with emerging economies and a young population, offers potential for Nike to introduce its products and capitalize on the growing demand for sportswear and athletic footwear.\n",
      "\n",
      "3. **Middle East**: Countries in the Middle East, known for their luxury shopping destinations and a growing interest in sports and fitness activities, could be strategic markets for Nike to target and establish a strong foothold.\n",
      "\n",
      "4. **Latin America**: Markets in Latin America, such as Brazil, Mexico, and Argentina, present opportunities for Nike to cater to a diverse consumer base and leverage the region's passion for sports and active lifestyles.\n",
      "\n",
      "5. **Southeast Asia**: Rapid urbanization, increasing urban middle-class population, and a trend towards health and wellness in countries like Indonesia, Thailand, and Vietnam make Southeast Asia an attractive region for Nike to explore and expand its market reach.\n",
      "\n",
      "By exploring these new markets in 2024, Nike can diversify its geographical presence, reach untapped consumer segments, and drive growth in emerging economies. \n",
      " ### Potential New Products or Services Nike Could Introduce in 2024\n",
      "\n",
      "1. **Smart Apparel**: Nike could explore the integration of technology into its apparel, such as smart fabrics that monitor performance metrics, provide feedback, or enhance comfort during workouts.\n",
      "\n",
      "2. **Athletic Accessories**: Introducing a line of athletic accessories like gym bags, water bottles, or fitness trackers could complement Nike's existing product offerings and provide additional value to customers.\n",
      "\n",
      "3. **Customization Platforms**: Offering personalized design options for footwear and apparel through online customization platforms could appeal to consumers seeking unique and tailored products.\n",
      "\n",
      "4. **Athletic Recovery Gear**: Developing recovery-focused products like compression wear, recovery sandals, or massage tools could cater to athletes and fitness enthusiasts looking to enhance post-workout recovery.\n",
      "\n",
      "5. **Sustainable Collections**: Launching sustainable collections made from eco-friendly materials, recycled fabrics, or biodegradable components could align with consumer preferences for environmentally conscious products.\n",
      "\n",
      "By introducing these new products or services in 2024, Nike can innovate its product portfolio, cater to evolving consumer needs, and differentiate itself in the competitive sports apparel market. \n",
      " ### Potential Marketing Strategies for Nike to Increase Revenue in Q3 2024\n",
      "\n",
      "1. **Influencer Partnerships**: Collaborating with popular athletes, celebrities, or social media influencers to promote Nike products can help reach a wider audience and drive sales.\n",
      "\n",
      "2. **Interactive Campaigns**: Launching interactive marketing campaigns, contests, or events that engage customers and create buzz around new product releases can generate excitement and increase brand visibility.\n",
      "\n",
      "3. **Social Media Engagement**: Leveraging social media platforms to connect with consumers, share user-generated content, and respond to feedback can build brand loyalty and encourage repeat purchases.\n",
      "\n",
      "4. **Localized Marketing**: Tailoring marketing messages, promotions, and product offerings to specific regions or target demographics can enhance relevance and appeal to diverse consumer groups.\n",
      "\n",
      "5. **Customer Loyalty Programs**: Implementing loyalty programs, exclusive offers, or rewards for repeat customers can incentivize brand loyalty, increase retention rates, and drive higher lifetime customer value.\n",
      "\n",
      "By employing these marketing strategies in Q3 2024, Nike can enhance its brand presence, attract new customers, and ultimately boost revenue growth.\n"
     ]
    }
   ],
   "source": [
    "final_report = ' \\n '.join(cleaned_report)\n",
    "print(final_report)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Final Generated Report\n",
    "\n",
    "In Jupyter Notebook, we can use the below code to render it in Markdown. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 210,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/markdown": [
       "### Nike's Current Revenue Trend\n",
       "\n",
       "Nike's current revenue trend has been steadily increasing over the past few years. In the most recent fiscal year, Nike reported a revenue of $37.4 billion, which was a 7% increase from the previous year. This growth can be attributed to strong sales in key markets, successful marketing campaigns, and a focus on innovation in product development. Overall, Nike continues to demonstrate strong financial performance and is well-positioned for future growth. \n",
       " ### Potential Areas of Improvement in Nike's Business Model\n",
       "\n",
       "1. **Sustainability Practices**: Nike could further enhance its sustainability efforts by reducing its carbon footprint, using more eco-friendly materials, and ensuring ethical labor practices throughout its supply chain.\n",
       "\n",
       "2. **Diversification of Product Portfolio**: While Nike is known for its athletic footwear and apparel, diversifying into new product categories or expanding into untapped markets could help drive growth and mitigate risks associated with a single product line.\n",
       "\n",
       "3. **E-commerce Strategy**: Improving the online shopping experience, investing in digital marketing, and leveraging data analytics to personalize customer interactions could boost online sales and customer loyalty.\n",
       "\n",
       "4. **Innovation and R&D**: Continuously investing in research and development to stay ahead of competitors, introduce new technologies, and enhance product performance could help maintain Nike's competitive edge in the market.\n",
       "\n",
       "5. **Brand Image and Reputation**: Strengthening brand image through effective marketing campaigns, community engagement, and transparent communication with stakeholders can help build trust and loyalty among consumers. \n",
       " ### Potential Cost-Saving Strategies for Nike to Increase Net Revenue in Q3 2024\n",
       "\n",
       "1. **Supply Chain Optimization**: Streamlining the supply chain, reducing transportation costs, and improving inventory management can lead to significant cost savings for Nike.\n",
       "\n",
       "2. **Operational Efficiency**: Implementing lean manufacturing practices, reducing waste, and optimizing production processes can help lower production costs and improve overall efficiency.\n",
       "\n",
       "3. **Outsourcing Non-Core Functions**: Outsourcing non-core functions such as IT services, customer support, or logistics can help reduce overhead costs and focus resources on core business activities.\n",
       "\n",
       "4. **Energy Efficiency**: Investing in energy-efficient technologies, renewable energy sources, and sustainable practices can lower utility costs and demonstrate a commitment to environmental responsibility.\n",
       "\n",
       "5. **Negotiating Supplier Contracts**: Negotiating better terms with suppliers, leveraging economies of scale, and exploring alternative sourcing options can help lower procurement costs and improve margins.\n",
       "\n",
       "By implementing these cost-saving strategies, Nike can improve its bottom line and increase net revenue in Q3 2024. \n",
       " ### Projected Market Trends for the Sports Apparel Industry in 2024\n",
       "\n",
       "1. **Sustainable Fashion**: Consumers are increasingly demanding eco-friendly and sustainable products, leading to a rise in sustainable sportswear options in the market.\n",
       "\n",
       "2. **Digital Transformation**: The sports apparel industry is expected to continue its shift towards digital platforms, with a focus on e-commerce, personalized shopping experiences, and digital marketing strategies.\n",
       "\n",
       "3. **Athleisure Wear**: The trend of athleisure wear, which combines athletic and leisure clothing, is projected to remain popular in 2024 as consumers seek comfort and versatility in their apparel choices.\n",
       "\n",
       "4. **Innovative Materials**: Advances in technology and material science are likely to drive the development of innovative fabrics and performance-enhancing materials in sports apparel, catering to the demand for high-quality and functional products.\n",
       "\n",
       "5. **Health and Wellness Focus**: With a growing emphasis on health and wellness, sports apparel brands are expected to incorporate features that promote comfort, performance, and overall well-being in their products.\n",
       "\n",
       "Overall, the sports apparel industry in 2024 is anticipated to be characterized by sustainability, digitalization, innovation, and a focus on consumer health and lifestyle trends. \n",
       " ### Current Successful Strategies Used by Nike's Competitors\n",
       "\n",
       "1. **Adidas**: Adidas has been successful in leveraging collaborations with celebrities and designers to create limited-edition collections that generate hype and drive sales. They have also focused on sustainability initiatives, such as using recycled materials in their products, to appeal to environmentally conscious consumers.\n",
       "\n",
       "2. **Under Armour**: Under Armour has differentiated itself by targeting performance-driven athletes and emphasizing technological innovation in their products. They have also invested heavily in digital marketing and e-commerce to reach a wider audience and enhance the customer shopping experience.\n",
       "\n",
       "3. **Puma**: Puma has successfully capitalized on the athleisure trend by offering stylish and versatile sportswear that can be worn both in and out of the gym. They have also focused on building partnerships with influencers and sponsoring high-profile athletes to increase brand visibility and credibility.\n",
       "\n",
       "4. **Lululemon**: Lululemon has excelled in creating a strong community around its brand, hosting events, classes, and collaborations to engage with customers beyond just selling products. They have also prioritized customer experience by offering personalized services and creating a seamless omnichannel shopping experience.\n",
       "\n",
       "5. **New Balance**: New Balance has carved out a niche in the market by emphasizing quality craftsmanship, heritage, and authenticity in their products. They have also focused on customization and personalization options for customers, allowing them to create unique and tailored footwear and apparel.\n",
       "\n",
       "Overall, Nike's competitors have found success through a combination of innovative product offerings, strategic marketing initiatives, and a focus on customer engagement and experience. \n",
       " ### Current and Projected Economic Conditions in Nike's Major Markets\n",
       "\n",
       "1. **United States**: The United States, being one of Nike's largest markets, is currently experiencing moderate economic growth driven by consumer spending, low unemployment rates, and a rebound in manufacturing. However, uncertainties surrounding trade policies, inflation, and interest rates could impact consumer confidence and spending in the near future.\n",
       "\n",
       "2. **China**: China remains a key market for Nike, with a growing middle class and increasing demand for sportswear and athletic footwear. Despite recent trade tensions with the U.S., China's economy is projected to continue expanding, driven by domestic consumption, infrastructure investments, and technological advancements.\n",
       "\n",
       "3. **Europe**: Economic conditions in Europe vary across countries, with some experiencing sluggish growth due to Brexit uncertainties, political instability, and trade tensions. However, overall consumer confidence is improving, and the sports apparel market is expected to grow, driven by e-commerce and sustainability trends.\n",
       "\n",
       "4. **Emerging Markets**: Nike's presence in emerging markets such as India, Brazil, and Southeast Asia provides opportunities for growth, given the rising disposable incomes, urbanization, and increasing focus on health and fitness. However, challenges such as currency fluctuations, regulatory changes, and competition from local brands could impact Nike's performance in these markets.\n",
       "\n",
       "Overall, Nike's major markets exhibit a mix of opportunities and challenges, with economic conditions influenced by global trends, geopolitical factors, and consumer preferences.\"  \n",
       " ### Current Consumer Preferences in the Sports Apparel Industry\n",
       "\n",
       "1. **Sustainability**: Consumers are increasingly seeking eco-friendly and sustainable options in sports apparel, driving brands to focus on using recycled materials, reducing waste, and promoting ethical practices.\n",
       "\n",
       "2. **Athleisure**: The trend of athleisure wear continues to be popular, with consumers looking for versatile and comfortable clothing that can be worn both during workouts and in everyday life.\n",
       "\n",
       "3. **Performance and Functionality**: Consumers prioritize performance-enhancing features in sports apparel, such as moisture-wicking fabrics, breathable materials, and ergonomic designs that enhance comfort and mobility.\n",
       "\n",
       "4. **Personalization**: Customization options, personalized fit, and unique design elements are appealing to consumers who seek individuality and exclusivity in their sports apparel choices.\n",
       "\n",
       "5. **Brand Transparency**: Consumers value transparency in brand practices, including supply chain transparency, ethical sourcing, and clear communication on product quality and manufacturing processes.\n",
       "\n",
       "Overall, consumer preferences in the sports apparel industry are shifting towards sustainability, versatility, performance, personalization, and transparency, influencing brand strategies and product offerings. \n",
       " ### Potential New Markets for Nike to Explore in 2024\n",
       "\n",
       "1. **India**: With a growing population, increasing disposable incomes, and a rising interest in health and fitness, India presents a significant opportunity for Nike to expand its presence and tap into a large consumer base.\n",
       "\n",
       "2. **Africa**: The African market, particularly countries with emerging economies and a young population, offers potential for Nike to introduce its products and capitalize on the growing demand for sportswear and athletic footwear.\n",
       "\n",
       "3. **Middle East**: Countries in the Middle East, known for their luxury shopping destinations and a growing interest in sports and fitness activities, could be strategic markets for Nike to target and establish a strong foothold.\n",
       "\n",
       "4. **Latin America**: Markets in Latin America, such as Brazil, Mexico, and Argentina, present opportunities for Nike to cater to a diverse consumer base and leverage the region's passion for sports and active lifestyles.\n",
       "\n",
       "5. **Southeast Asia**: Rapid urbanization, increasing urban middle-class population, and a trend towards health and wellness in countries like Indonesia, Thailand, and Vietnam make Southeast Asia an attractive region for Nike to explore and expand its market reach.\n",
       "\n",
       "By exploring these new markets in 2024, Nike can diversify its geographical presence, reach untapped consumer segments, and drive growth in emerging economies. \n",
       " ### Potential New Products or Services Nike Could Introduce in 2024\n",
       "\n",
       "1. **Smart Apparel**: Nike could explore the integration of technology into its apparel, such as smart fabrics that monitor performance metrics, provide feedback, or enhance comfort during workouts.\n",
       "\n",
       "2. **Athletic Accessories**: Introducing a line of athletic accessories like gym bags, water bottles, or fitness trackers could complement Nike's existing product offerings and provide additional value to customers.\n",
       "\n",
       "3. **Customization Platforms**: Offering personalized design options for footwear and apparel through online customization platforms could appeal to consumers seeking unique and tailored products.\n",
       "\n",
       "4. **Athletic Recovery Gear**: Developing recovery-focused products like compression wear, recovery sandals, or massage tools could cater to athletes and fitness enthusiasts looking to enhance post-workout recovery.\n",
       "\n",
       "5. **Sustainable Collections**: Launching sustainable collections made from eco-friendly materials, recycled fabrics, or biodegradable components could align with consumer preferences for environmentally conscious products.\n",
       "\n",
       "By introducing these new products or services in 2024, Nike can innovate its product portfolio, cater to evolving consumer needs, and differentiate itself in the competitive sports apparel market. \n",
       " ### Potential Marketing Strategies for Nike to Increase Revenue in Q3 2024\n",
       "\n",
       "1. **Influencer Partnerships**: Collaborating with popular athletes, celebrities, or social media influencers to promote Nike products can help reach a wider audience and drive sales.\n",
       "\n",
       "2. **Interactive Campaigns**: Launching interactive marketing campaigns, contests, or events that engage customers and create buzz around new product releases can generate excitement and increase brand visibility.\n",
       "\n",
       "3. **Social Media Engagement**: Leveraging social media platforms to connect with consumers, share user-generated content, and respond to feedback can build brand loyalty and encourage repeat purchases.\n",
       "\n",
       "4. **Localized Marketing**: Tailoring marketing messages, promotions, and product offerings to specific regions or target demographics can enhance relevance and appeal to diverse consumer groups.\n",
       "\n",
       "5. **Customer Loyalty Programs**: Implementing loyalty programs, exclusive offers, or rewards for repeat customers can incentivize brand loyalty, increase retention rates, and drive higher lifetime customer value.\n",
       "\n",
       "By employing these marketing strategies in Q3 2024, Nike can enhance its brand presence, attract new customers, and ultimately boost revenue growth."
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from IPython.display import display, Markdown\n",
    "\n",
    "display(Markdown(final_report))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "adv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
