{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "4be6be18-242e-46e3-a63f-d104d08ab2de",
   "metadata": {},
   "source": [
    "# Agentic workflows using Llama-Index\n",
    "The [Llama-Index](https://github.com/run-llama/llama_index) library and its submodules such as for [Ollama](https://docs.llamaindex.ai/en/stable/api_reference/llms/ollama/) and [OpenAI-like](https://docs.llamaindex.ai/en/stable/api_reference/llms/openai_like/) allow building agentic workflows using open-weight models. In such workflows the LLM decides which functions to call and it can call multiple functions in a row to answer a question.\n",
    "\n",
    "See also\n",
    "* [Agents in the ScaDS.AI Generative AI Notebooks](https://scads.github.io/generative-ai-notebooks/35_agents/readme.html)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "729e51e6-a8fd-4c5e-8b25-220e5b4b5421",
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.core.agent import ReActAgent\n",
    "from llama_index.llms.ollama import Ollama\n",
    "from llama_index.llms.openai_like import OpenAILike\n",
    "from llama_index.core.tools import FunctionTool\n",
    "import os"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1c0851d5-81d6-4dfb-b2cd-4b89bbaf23ef",
   "metadata": {},
   "source": [
    "In the following example we use the OpenAI-like API to access our institutional LLM server. Alternatively, one can setup a local installation of [Ollama](https://ollama.com), which would work, too."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "3afefc4d-918a-4367-9e6b-f1ce1c328452",
   "metadata": {},
   "outputs": [],
   "source": [
    "## Use this to play with a local model via ollama\n",
    "#llm = Ollama(model=\"llama3.2\", request_timeout=120.0)\n",
    "\n",
    "llm = OpenAILike(model=\"meta-llama/Llama-3.3-70B-Instruct\", request_timeout=120.0, api_base=\"https://llm.scads.ai/v1\", api_key=os.environ.get('SCADSAI_API_KEY'))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b24d4b77-5b26-4966-a6f2-0ed24c0892ab",
   "metadata": {},
   "source": [
    "We define a couple of tools, functions to answer specific questions. In the case shown here, we would like to deal with orders from customers and estimate their delivery dates when they approach us."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "2115f4a5-8850-4dd3-b6a9-a34d957c5334",
   "metadata": {},
   "outputs": [],
   "source": [
    "tools = []\n",
    "\n",
    "@tools.append\n",
    "def estimate_delivery_date_of_order(order_id:str) -> str:\n",
    "    \"\"\"Estimate the delivery date of a package identified by its order id.\"\"\"\n",
    "    if order_id == \"292123\":\n",
    "        return \"Friday\"\n",
    "    if order_id == \"292456\":\n",
    "        return \"Thursday\"\n",
    "    if order_id == \"292789\":\n",
    "        return \"Saturday\"\n",
    "    return \"Unknown\"\n",
    "\n",
    "@tools.append\n",
    "def get_recent_order_id(customer_name:str) -> str:\n",
    "    \"\"\"Get the most recent order id for a given customer\"\"\"\n",
    "    if customer_name.lower() == \"robert\":\n",
    "        return \"292123\"\n",
    "    if customer_name.lower() == \"alice\":\n",
    "        return \"292456\"\n",
    "    if customer_name.lower() == \"ivy\":\n",
    "        return \"292789\"\n",
    "    if customer_name.lower() == \"dennis\":\n",
    "        return \"2921010\"\n",
    "    return \"unknown\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3fe99085-155e-4962-a838-fd017a11d88b",
   "metadata": {},
   "source": [
    "We also add an unrelated function, which should never be called when dealing with customers and deliveries."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "f2f50948-1703-4dca-bf3b-9d46b762fcee",
   "metadata": {},
   "outputs": [],
   "source": [
    "@tools.append\n",
    "def get_weather(city:str)->str:\n",
    "    \"\"\"Returns the current weather in a given city.\"\"\"\n",
    "    return \"sunny\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f467dd3b-1909-49e2-a48f-50c15d272f08",
   "metadata": {},
   "source": [
    "Next, we setup a [ReActAgent](https://docs.llamaindex.ai/en/stable/api_reference/agent/react/) to deal with the given function and prompts."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "180e8f3a-2b0f-49eb-a002-ede430b932b4",
   "metadata": {},
   "outputs": [],
   "source": [
    "agent = ReActAgent.from_tools([FunctionTool.from_defaults(fn=t) for t in tools], llm=llm, verbose=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7f8cadf1-f15c-4b10-9481-3bcc08ab7a69",
   "metadata": {},
   "source": [
    "We can now ask questions to the agent. In verbose mode, you will see which functions it will call to answer our request."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "dcd2f1e2-fd13-4116-b8a3-510c298279dd",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "> Running step 89187412-52e5-43fb-8b04-1b17a14c4477. Step input: My Name is Robert. I ordered something. And I would like to know when it will arrive.\n",
      "\u001b[1;3;38;5;200mThought: The current language of the user is: English. I need to use a tool to help me answer the question.\n",
      "Action: get_recent_order_id\n",
      "Action Input: {'customer_name': 'Robert'}\n",
      "\u001b[0m\u001b[1;3;34mObservation: 292123\n",
      "\u001b[0m> Running step 490db98a-c140-46a6-a139-145656631264. Step input: None\n",
      "\u001b[1;3;38;5;200mThought: I have the order id. Now I can use another tool to estimate the delivery date.\n",
      "Action: estimate_delivery_date_of_order\n",
      "Action Input: {'order_id': '292123'}\n",
      "\u001b[0m\u001b[1;3;34mObservation: Friday\n",
      "\u001b[0m> Running step 20836298-e613-43e9-a86b-b3f4d80d2e51. Step input: None\n",
      "\u001b[1;3;38;5;200mThought: I can answer without using any more tools. I'll use the user's language to answer\n",
      "Answer: Your order will arrive on Friday.\n",
      "\u001b[0m"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'Your order will arrive on Friday.'"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "response = agent.chat(\"My Name is Robert. I ordered something. And I would like to know when it will arrive.\")\n",
    "response.response"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2f2262cb-12ab-42df-a6e0-c1a741e356d7",
   "metadata": {},
   "source": [
    "For demonstration purposes, we run this again."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "41e0da5d-a362-4042-b61a-9ad47b11fd09",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Your order will arrive on Thursday.'"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "agent = ReActAgent.from_tools([FunctionTool.from_defaults(fn=t) for t in tools], llm=llm)\n",
    "\n",
    "response = agent.chat(\"My Name is Alice. I ordered something. And I would like to know when it will arrive.\")\n",
    "response.response"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "eaaa7621-27ed-4477-bccf-d7cb6d786fb2",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "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.11.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}