{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "2582dceb-5c5b-429b-a0a5-cd4aadbede28",
   "metadata": {},
   "source": [
    "## The most relevant things of LangChain in 15 minutes"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "96b8500b-f5c4-4826-81c9-4dfdd6580755",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "from dotenv import load_dotenv, find_dotenv\n",
    "_ = load_dotenv(find_dotenv())\n",
    "openai_api_key = os.environ[\"OPENAI_API_KEY\"]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f0a0dce8-6b28-4d10-a653-bf66847b8648",
   "metadata": {},
   "source": [
    "### Connect with LM"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "200545d3-0f14-43f5-b749-06f2dc13a453",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_openai import OpenAI"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "eea210b4-28f3-4060-ae77-8bba410e437a",
   "metadata": {},
   "outputs": [],
   "source": [
    "my_creative_llm = OpenAI(temperature=0.9)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "e605a626-24e9-4c1f-9829-21c059722342",
   "metadata": {},
   "outputs": [],
   "source": [
    "question = \"What are the 5 best things to do in life?\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "12624519-5a4c-4b26-ac9c-db8dd3639a0a",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/Users/juliocolomer/.pyenv/versions/3.11.4/envs/venv020124/lib/python3.11/site-packages/langchain_core/_api/deprecation.py:117: LangChainDeprecationWarning: The function `__call__` was deprecated in LangChain 0.1.7 and will be removed in 0.2.0. Use invoke instead.\n",
      "  warn_deprecated(\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "1. Travel: Experiencing new cultures and places can broaden our perspectives and create unforgettable memories.\n",
      "\n",
      "2. Pursue a Passion: Whether it's a hobby, career, or personal goal, pursuing something we are passionate about can bring a sense of fulfillment and purpose to our lives.\n",
      "\n",
      "3. Connect with Others: Building and maintaining meaningful relationships with friends, family, and community can provide support, love, and a sense of belonging.\n",
      "\n",
      "4. Learn and Grow: Continuous learning and personal development can lead to self-discovery and improved skills, contributing to personal growth and satisfaction.\n",
      "\n",
      "5. Giving Back: Engaging in acts of kindness and volunteering can bring joy and fulfillment through helping others and making a positive impact in the world.\n"
     ]
    }
   ],
   "source": [
    "print(my_creative_llm(question))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "96dccfc1-5881-4bec-9c12-c13ca321b744",
   "metadata": {},
   "source": [
    "### Create a prompt template to wrap the user input"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "59a1af92-3067-4e15-8ce9-e160e099db4b",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.prompts import PromptTemplate"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "ce0ec015-83bd-4912-85f3-5c4ee2e9a131",
   "metadata": {},
   "outputs": [],
   "source": [
    "my_prompt_template = PromptTemplate(\n",
    "    input_variables = [\"destination\"],\n",
    "    template = \"What are the 3 best things to do in {destination}?\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "619ad98a-48b2-4630-8079-cb5eb7f2944f",
   "metadata": {},
   "outputs": [],
   "source": [
    "user_input = \"Barcelona\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "26e558c0-d6b4-4363-b3d9-2f925dcb81aa",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "1. Visit Gaudi's Masterpieces: Antoni Gaudí was a renowned Catalan architect and his works are iconic to the city of Barcelona. Some of his most famous works include the Sagrada Familia, Park Güell, and Casa Batlló. These architectural masterpieces are must-see attractions when visiting Barcelona.\n",
      "\n",
      "2. Stroll along La Rambla: La Rambla is a bustling pedestrian street lined with shops, restaurants, and street performers. It is a great place to soak in the vibrant atmosphere of the city, try some local cuisine, and shop for souvenirs. It also leads to the famous La Boqueria market, where you can find a wide variety of fresh produce, meats, and cheeses.\n",
      "\n",
      "3. Explore the Gothic Quarter: The Gothic Quarter, or Barri Gòtic, is the oldest part of the city and is filled with narrow cobblestone streets, medieval buildings, and charming squares. It is a great place to get lost and discover hidden gems, such as the stunning Barcelona Cathedral and the Plaça Reial. It also has a vibrant nightlife scene, with plenty of bars and restaurants to choose from.\n"
     ]
    }
   ],
   "source": [
    "print(my_creative_llm(my_prompt_template.format(destination=user_input)))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e9acae73-c386-4456-8c97-10bac4fa4383",
   "metadata": {},
   "source": [
    "### Combine instructions in chains"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "9eaba1e0-6217-49bd-8fb3-e413576ce566",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.prompts import PromptTemplate\n",
    "from langchain_openai import OpenAI\n",
    "from langchain.chains import LLMChain"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "031b4795-629d-4346-ae66-6c052429ef19",
   "metadata": {},
   "outputs": [],
   "source": [
    "my_no_creative_llm = OpenAI(temperature=0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "4fc23d0b-cc3e-4ff0-bcb3-3dff94613145",
   "metadata": {},
   "outputs": [],
   "source": [
    "my_prompt_template = PromptTemplate(\n",
    "    input_variables = [\"politician\"],\n",
    "    template = \"What are the 3 most remarkable achievements of {politician}?\",\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "175c8c74-5c85-4b41-8b9c-0a66ebc63e21",
   "metadata": {},
   "outputs": [],
   "source": [
    "my_chain = LLMChain(llm=my_no_creative_llm, prompt=my_prompt_template)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "d934b520-89af-4f95-b1a6-ce7f90b73222",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/Users/juliocolomer/.pyenv/versions/3.11.4/envs/venv020124/lib/python3.11/site-packages/langchain_core/_api/deprecation.py:117: LangChainDeprecationWarning: The function `run` was deprecated in LangChain 0.1.0 and will be removed in 0.2.0. Use invoke instead.\n",
      "  warn_deprecated(\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "1. Leadership during World War II: Churchill's leadership during World War II is widely considered to be his most remarkable achievement. As Prime Minister of the United Kingdom, he rallied the British people and inspired them to resist Nazi Germany, even when the country was facing defeat. His speeches, determination, and strategic decisions played a crucial role in the Allied victory.\n",
      "\n",
      "2. Iron Curtain Speech: In 1946, Churchill delivered his famous \"Iron Curtain\" speech in Fulton, Missouri, where he warned of the growing threat of Soviet communism and called for a united front against it. This speech is considered a turning point in the Cold War and solidified Churchill's reputation as a visionary leader.\n",
      "\n",
      "3. Nobel Prize in Literature: In 1953, Churchill was awarded the Nobel Prize in Literature for his numerous works, including his six-volume memoir \"The Second World War.\" This recognition not only highlighted his literary talent but also his significant contributions to history and politics. He remains the only British Prime Minister to have received this honor.\n"
     ]
    }
   ],
   "source": [
    "print(my_chain.run(\"Churchill\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0ae8e2df-8e9c-409c-a18d-1dccf72367db",
   "metadata": {},
   "source": [
    "### Agents: give reasoning power to LMs\n",
    "1. Load some external tools (google search, llm-math, etc)\n",
    "2. Initialize an agent type on top of the LM\n",
    "3. Run the agent and she will decide the tools to use based on your input"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2236ce09-27cb-4400-a5d7-9459c544721f",
   "metadata": {},
   "source": [
    "*Careful: operations with agents are more expensive in tokens. We will not execute the code in this demo. To comment out an entire cell in Mac: Command + /*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "c85fd297-d6c8-45ea-901d-751b4c6d81af",
   "metadata": {},
   "outputs": [],
   "source": [
    "# from langchain.agents import load_tools\n",
    "# from langchain.agents import initialize_agent\n",
    "# from langchain.llms import OpenAI\n",
    "# tools = load_tools([\"serpapi\", \"llm-math\"], llm=llm)\n",
    "# agent = initialize_agent(tools, llm, agent=\"zero-shot-react-description\", verbose=True)\n",
    "# agent.run(\"Who is the current leader of Japan? What is the largest prime number that is smaller than their age?\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "154c8ee5-5706-41cf-a7a7-b6fa564f3b9e",
   "metadata": {},
   "source": [
    "### Add memory"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "9db87c29-77ce-4d52-8e9a-d88b7ed0da37",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain import ConversationChain"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "d2ae3745-6d28-4944-925b-e29febf9c0c5",
   "metadata": {},
   "outputs": [],
   "source": [
    "my_no_creative_llm = OpenAI(temperature=0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "8224f7cf-c1ea-41df-b2f5-4ed903eb4a2d",
   "metadata": {},
   "outputs": [],
   "source": [
    "my_conversation = ConversationChain(llm=my_no_creative_llm, verbose=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "89d8a833-7941-4beb-bac1-c5386e49480e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new ConversationChain chain...\u001b[0m\n",
      "Prompt after formatting:\n",
      "\u001b[32;1m\u001b[1;3mThe following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\n",
      "\n",
      "Current conversation:\n",
      "\n",
      "Human: hi there!\n",
      "AI:\u001b[0m\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/Users/juliocolomer/.pyenv/versions/3.11.4/envs/venv020124/lib/python3.11/site-packages/langchain_core/_api/deprecation.py:117: LangChainDeprecationWarning: The function `__call__` was deprecated in LangChain 0.1.0 and will be removed in 0.2.0. Use invoke instead.\n",
      "  warn_deprecated(\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'input': 'hi there!',\n",
       " 'history': '',\n",
       " 'response': \" Hello! It's nice to meet you. I am an AI created by OpenAI. I am constantly learning and improving my abilities through machine learning algorithms. How can I assist you today?\"}"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "my_conversation(\"hi there!\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "f0203b4c-e619-4ffa-bcd2-df135c0377b8",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new ConversationChain chain...\u001b[0m\n",
      "Prompt after formatting:\n",
      "\u001b[32;1m\u001b[1;3mThe following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\n",
      "\n",
      "Current conversation:\n",
      "Human: hi there!\n",
      "AI:  Hello! It's nice to meet you. I am an AI created by OpenAI. I am constantly learning and improving my abilities through machine learning algorithms. How can I assist you today?\n",
      "Human: My name is Julio. What is your name?\n",
      "AI:\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'input': 'My name is Julio. What is your name?',\n",
       " 'history': \"Human: hi there!\\nAI:  Hello! It's nice to meet you. I am an AI created by OpenAI. I am constantly learning and improving my abilities through machine learning algorithms. How can I assist you today?\",\n",
       " 'response': \" My name is OpenAI. It's not a traditional name like Julio, but it represents my purpose as an open-source artificial intelligence. What brings you to chat with me today, Julio?\"}"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "my_conversation(\"My name is Julio. What is your name?\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "fea2dd07-0b84-4f02-8814-b685f4a793ab",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new ConversationChain chain...\u001b[0m\n",
      "Prompt after formatting:\n",
      "\u001b[32;1m\u001b[1;3mThe following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\n",
      "\n",
      "Current conversation:\n",
      "Human: hi there!\n",
      "AI:  Hello! It's nice to meet you. I am an AI created by OpenAI. I am constantly learning and improving my abilities through machine learning algorithms. How can I assist you today?\n",
      "Human: My name is Julio. What is your name?\n",
      "AI:  My name is OpenAI. It's not a traditional name like Julio, but it represents my purpose as an open-source artificial intelligence. What brings you to chat with me today, Julio?\n",
      "Human: Do you remember my name?\n",
      "AI:\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "' Yes, Julio. I have a database of information that includes your name and other details about our previous interactions. I am constantly updating and organizing this information to better assist you. Is there something specific you would like to discuss?'"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "my_conversation.predict(input=\"Do you remember my name?\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "07b3da01-bfd8-4e80-bc08-34003f05e6c1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "memory=ConversationBufferMemory(chat_memory=ChatMessageHistory(messages=[HumanMessage(content='hi there!'), AIMessage(content=\" Hello! It's nice to meet you. I am an AI created by OpenAI. I am constantly learning and improving my abilities through machine learning algorithms. How can I assist you today?\"), HumanMessage(content='My name is Julio. What is your name?'), AIMessage(content=\" My name is OpenAI. It's not a traditional name like Julio, but it represents my purpose as an open-source artificial intelligence. What brings you to chat with me today, Julio?\"), HumanMessage(content='Do you remember my name?'), AIMessage(content=' Yes, Julio. I have a database of information that includes your name and other details about our previous interactions. I am constantly updating and organizing this information to better assist you. Is there something specific you would like to discuss?')])) verbose=True llm=OpenAI(client=<openai.resources.completions.Completions object at 0x13782b910>, async_client=<openai.resources.completions.AsyncCompletions object at 0x1378306d0>, temperature=0.0, openai_api_key='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', openai_proxy='')\n"
     ]
    }
   ],
   "source": [
    "print(my_conversation)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "52f24c85-f9b5-4cd5-8ad2-a38704f85359",
   "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.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
