diff --git a/lab_chains_in_langchain_solved.ipynb b/lab_chains_in_langchain_solved.ipynb new file mode 100644 index 0000000..ffecf61 --- /dev/null +++ b/lab_chains_in_langchain_solved.ipynb @@ -0,0 +1,1620 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "52824b89-532a-4e54-87e9-1410813cd39e", + "metadata": { + "id": "52824b89-532a-4e54-87e9-1410813cd39e" + }, + "source": [ + "# Lab | Chains in LangChain\n", + "\n", + "## Outline\n", + "\n", + "* LLMChain\n", + "* Sequential Chains\n", + " * SimpleSequentialChain\n", + " * SequentialChain\n", + "* Router Chain" + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "id": "b7ed03ed-1322-49e3-b2a2-33e94fb592ef", + "metadata": { + "tags": [], + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "b7ed03ed-1322-49e3-b2a2-33e94fb592ef", + "outputId": "3b8d1f4a-991a-4fa5-d1cb-ff843205f9cf" + }, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "Environment ready ✅\n" + ] + } + ], + "source": [ + "import os\n", + "import warnings\n", + "from google.colab import userdata\n", + "from dotenv import load_dotenv, find_dotenv\n", + "_ = load_dotenv(find_dotenv())\n", + "\n", + "os.environ[\"OPENAI_API_KEY\"] = userdata.get(\"OPENAI_API_KEY\")\n", + "\n", + "warnings.filterwarnings(\"ignore\")\n", + "_ = load_dotenv(find_dotenv()) # This line loads environment variables from a .env file if it exists\n", + "assert os.getenv(\"OPENAI_API_KEY\"), \"OPENAI_API_KEY missing\"\n", + "print(\"Environment ready ✅\")" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "id": "974acf8e-8f88-42de-88f8-40a82cb58e8b", + "metadata": { + "tags": [], + "id": "974acf8e-8f88-42de-88f8-40a82cb58e8b" + }, + "outputs": [], + "source": [ + "import pandas as pd\n", + "df = pd.read_csv('/content/Data.csv')" + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "id": "b7a09c35", + "metadata": { + "tags": [], + "colab": { + "base_uri": "https://localhost:8080/", + "height": 201 + }, + "id": "b7a09c35", + "outputId": "d289399e-b585-4fe2-efe9-7987ef93cfb0" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + " Product Review\n", + "0 Queen Size Sheet Set I ordered a king size set. My only criticism w...\n", + "1 Waterproof Phone Pouch I loved the waterproof sac, although the openi...\n", + "2 Luxury Air Mattress This mattress had a small hole in the top of i...\n", + "3 Pillows Insert This is the best throw pillow fillers on Amazo...\n", + "4 Milk Frother Handheld\\n  I loved this product. But they only seem to l..." + ], + "text/html": [ + "\n", + "
\n", + "
\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
ProductReview
0Queen Size Sheet SetI ordered a king size set. My only criticism w...
1Waterproof Phone PouchI loved the waterproof sac, although the openi...
2Luxury Air MattressThis mattress had a small hole in the top of i...
3Pillows InsertThis is the best throw pillow fillers on Amazo...
4Milk Frother Handheld\\nI loved this product. But they only seem to l...
\n", + "
\n", + "
\n", + "\n", + "
\n", + " \n", + "\n", + " \n", + "\n", + " \n", + "
\n", + "\n", + "\n", + "
\n", + "
\n" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "dataframe", + "variable_name": "df", + "summary": "{\n \"name\": \"df\",\n \"rows\": 7,\n \"fields\": [\n {\n \"column\": \"Product\",\n \"properties\": {\n \"dtype\": \"string\",\n \"num_unique_values\": 7,\n \"samples\": [\n \"Queen Size Sheet Set\",\n \"Waterproof Phone Pouch\",\n \"L'Or Espresso Caf\\u00e9\\u00a0\\n\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n },\n {\n \"column\": \"Review\",\n \"properties\": {\n \"dtype\": \"string\",\n \"num_unique_values\": 7,\n \"samples\": [\n \"I ordered a king size set. My only criticism would be that I wish seller would offer the king size set with 4 pillowcases. I separately ordered a two pack of pillowcases so I could have a total of four. When I saw the two packages, it looked like the color did not exactly match. Customer service was excellent about sending me two more pillowcases so I would have four that matched. Excellent! For the cost of these sheets, I am satisfied with the characteristics and coolness of the sheets.\",\n \"I loved the waterproof sac, although the opening was made of a hard plastic. I don\\u2019t know if that would break easily. But I couldn\\u2019t turn my phone on, once it was in the pouch.\",\n \"Je trouve le go\\u00fbt m\\u00e9diocre. La mousse ne tient pas, c'est bizarre. J'ach\\u00e8te les m\\u00eames dans le commerce et le go\\u00fbt est bien meilleur...\\nVieux lot ou contrefa\\u00e7on !?\"\n ],\n \"semantic_type\": \"\",\n \"description\": \"\"\n }\n }\n ]\n}" + } + }, + "metadata": {}, + "execution_count": 33 + } + ], + "source": [ + "df.head()" + ] + }, + { + "cell_type": "markdown", + "id": "b940ce7c", + "metadata": { + "id": "b940ce7c" + }, + "source": [ + "## LLMChain" + ] + }, + { + "cell_type": "code", + "execution_count": 34, + "id": "20b6b2a4", + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "20b6b2a4", + "outputId": "7c22bc45-b974-49c3-ea53-fcf6a6b943b4" + }, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "Requirement already satisfied: langchain in /usr/local/lib/python3.12/dist-packages (1.3.13)\n", + "Requirement already satisfied: langchain-core in /usr/local/lib/python3.12/dist-packages (1.4.9)\n", + "Requirement already satisfied: langchain-openai in /usr/local/lib/python3.12/dist-packages (1.3.5)\n", + "Requirement already satisfied: langchain-community in /usr/local/lib/python3.12/dist-packages (0.4.2)\n", + "Requirement already satisfied: langchain-classic in /usr/local/lib/python3.12/dist-packages (1.0.8)\n", + "Requirement already satisfied: langgraph<1.3.0,>=1.2.5 in /usr/local/lib/python3.12/dist-packages (from langchain) (1.2.9)\n", + "Requirement already satisfied: pydantic<3.0.0,>=2.7.4 in /usr/local/lib/python3.12/dist-packages (from langchain) (2.13.4)\n", + "Requirement already satisfied: jsonpatch<2.0.0,>=1.33.0 in /usr/local/lib/python3.12/dist-packages (from langchain-core) (1.33)\n", + "Requirement already satisfied: langchain-protocol>=0.0.17 in /usr/local/lib/python3.12/dist-packages (from langchain-core) (0.0.18)\n", + "Requirement already satisfied: langsmith<1.0.0,>=0.3.45 in /usr/local/lib/python3.12/dist-packages (from langchain-core) (0.10.2)\n", + "Requirement already satisfied: packaging>=23.2.0 in /usr/local/lib/python3.12/dist-packages (from langchain-core) (26.2)\n", + "Requirement already satisfied: pyyaml<7.0.0,>=5.3.0 in /usr/local/lib/python3.12/dist-packages (from langchain-core) (6.0.3)\n", + "Requirement already satisfied: tenacity!=8.4.0,<10.0.0,>=8.1.0 in /usr/local/lib/python3.12/dist-packages (from langchain-core) (9.1.4)\n", + "Requirement already satisfied: typing-extensions<5.0.0,>=4.7.0 in /usr/local/lib/python3.12/dist-packages (from langchain-core) (4.16.0)\n", + "Requirement already satisfied: uuid-utils<1.0,>=0.12.0 in /usr/local/lib/python3.12/dist-packages (from langchain-core) (0.17.0)\n", + "Requirement already satisfied: openai<3.0.0,>=2.45.0 in /usr/local/lib/python3.12/dist-packages (from langchain-openai) (2.45.0)\n", + "Requirement already satisfied: tiktoken<1.0.0,>=0.7.0 in /usr/local/lib/python3.12/dist-packages (from langchain-openai) (0.13.0)\n", + "Requirement already satisfied: aiohttp<4.0.0,>=3.8.3 in /usr/local/lib/python3.12/dist-packages (from langchain-community) (3.14.1)\n", + "Requirement already satisfied: httpx-sse<1.0.0,>=0.4.0 in /usr/local/lib/python3.12/dist-packages (from langchain-community) (0.4.3)\n", + "Requirement already satisfied: numpy>=1.26.2 in /usr/local/lib/python3.12/dist-packages (from langchain-community) (2.0.2)\n", + "Requirement already satisfied: pydantic-settings<3.0.0,>=2.10.1 in /usr/local/lib/python3.12/dist-packages (from langchain-community) (2.14.2)\n", + "Requirement already satisfied: requests<3.0.0,>=2.32.5 in /usr/local/lib/python3.12/dist-packages (from langchain-community) (2.34.2)\n", + "Requirement already satisfied: sqlalchemy<3.0.0,>=1.4.0 in /usr/local/lib/python3.12/dist-packages (from langchain-community) (2.0.51)\n", + "Requirement already satisfied: langchain-text-splitters<2.0.0,>=1.1.2 in /usr/local/lib/python3.12/dist-packages (from langchain-classic) (1.1.2)\n", + "Requirement already satisfied: aiohappyeyeballs>=2.5.0 in /usr/local/lib/python3.12/dist-packages (from aiohttp<4.0.0,>=3.8.3->langchain-community) (2.7.1)\n", + "Requirement already satisfied: aiosignal>=1.4.0 in /usr/local/lib/python3.12/dist-packages (from aiohttp<4.0.0,>=3.8.3->langchain-community) (1.4.0)\n", + "Requirement already satisfied: attrs>=17.3.0 in /usr/local/lib/python3.12/dist-packages (from aiohttp<4.0.0,>=3.8.3->langchain-community) (26.1.0)\n", + "Requirement already satisfied: frozenlist>=1.1.1 in /usr/local/lib/python3.12/dist-packages (from aiohttp<4.0.0,>=3.8.3->langchain-community) (1.8.0)\n", + "Requirement already satisfied: multidict<7.0,>=4.5 in /usr/local/lib/python3.12/dist-packages (from aiohttp<4.0.0,>=3.8.3->langchain-community) (6.7.1)\n", + "Requirement already satisfied: propcache>=0.2.0 in /usr/local/lib/python3.12/dist-packages (from aiohttp<4.0.0,>=3.8.3->langchain-community) (0.5.2)\n", + "Requirement already satisfied: yarl<2.0,>=1.17.0 in /usr/local/lib/python3.12/dist-packages (from aiohttp<4.0.0,>=3.8.3->langchain-community) (1.24.2)\n", + "Requirement already satisfied: jsonpointer>=1.9 in /usr/local/lib/python3.12/dist-packages (from jsonpatch<2.0.0,>=1.33.0->langchain-core) (3.1.1)\n", + "Requirement already satisfied: langgraph-checkpoint<5.0.0,>=4.1.0 in /usr/local/lib/python3.12/dist-packages (from langgraph<1.3.0,>=1.2.5->langchain) (4.1.1)\n", + "Requirement already satisfied: langgraph-prebuilt<1.2.0,>=1.1.0 in /usr/local/lib/python3.12/dist-packages (from langgraph<1.3.0,>=1.2.5->langchain) (1.1.0)\n", + "Requirement already satisfied: langgraph-sdk<0.5.0,>=0.4.2 in /usr/local/lib/python3.12/dist-packages (from langgraph<1.3.0,>=1.2.5->langchain) (0.4.2)\n", + "Requirement already satisfied: xxhash>=3.5.0 in /usr/local/lib/python3.12/dist-packages (from langgraph<1.3.0,>=1.2.5->langchain) (3.8.1)\n", + "Requirement already satisfied: anyio>=3.5.0 in /usr/local/lib/python3.12/dist-packages (from langsmith<1.0.0,>=0.3.45->langchain-core) (4.14.2)\n", + "Requirement already satisfied: distro>=1.7.0 in /usr/local/lib/python3.12/dist-packages (from langsmith<1.0.0,>=0.3.45->langchain-core) (1.9.0)\n", + "Requirement already satisfied: httpx<1,>=0.23.0 in /usr/local/lib/python3.12/dist-packages (from langsmith<1.0.0,>=0.3.45->langchain-core) (0.28.1)\n", + "Requirement already satisfied: orjson>=3.9.14 in /usr/local/lib/python3.12/dist-packages (from langsmith<1.0.0,>=0.3.45->langchain-core) (3.11.9)\n", + "Requirement already satisfied: requests-toolbelt>=1.0.0 in /usr/local/lib/python3.12/dist-packages (from langsmith<1.0.0,>=0.3.45->langchain-core) (1.0.0)\n", + "Requirement already satisfied: sniffio>=1.1 in /usr/local/lib/python3.12/dist-packages (from langsmith<1.0.0,>=0.3.45->langchain-core) (1.3.1)\n", + "Requirement already satisfied: websockets>=15.0 in /usr/local/lib/python3.12/dist-packages (from langsmith<1.0.0,>=0.3.45->langchain-core) (15.0.1)\n", + "Requirement already satisfied: zstandard>=0.23.0 in /usr/local/lib/python3.12/dist-packages (from langsmith<1.0.0,>=0.3.45->langchain-core) (0.25.0)\n", + "Requirement already satisfied: jiter<1,>=0.10.0 in /usr/local/lib/python3.12/dist-packages (from openai<3.0.0,>=2.45.0->langchain-openai) (0.16.0)\n", + "Requirement already satisfied: tqdm>4 in /usr/local/lib/python3.12/dist-packages (from openai<3.0.0,>=2.45.0->langchain-openai) (4.67.3)\n", + "Requirement already satisfied: annotated-types>=0.6.0 in /usr/local/lib/python3.12/dist-packages (from pydantic<3.0.0,>=2.7.4->langchain) (0.7.0)\n", + "Requirement already satisfied: pydantic-core==2.46.4 in /usr/local/lib/python3.12/dist-packages (from pydantic<3.0.0,>=2.7.4->langchain) (2.46.4)\n", + "Requirement already satisfied: typing-inspection>=0.4.2 in /usr/local/lib/python3.12/dist-packages (from pydantic<3.0.0,>=2.7.4->langchain) (0.4.2)\n", + "Requirement already satisfied: python-dotenv>=0.21.0 in /usr/local/lib/python3.12/dist-packages (from pydantic-settings<3.0.0,>=2.10.1->langchain-community) (1.2.2)\n", + "Requirement already satisfied: charset_normalizer<4,>=2 in /usr/local/lib/python3.12/dist-packages (from requests<3.0.0,>=2.32.5->langchain-community) (3.4.9)\n", + "Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.12/dist-packages (from requests<3.0.0,>=2.32.5->langchain-community) (3.18)\n", + "Requirement already satisfied: urllib3<3,>=1.26 in /usr/local/lib/python3.12/dist-packages (from requests<3.0.0,>=2.32.5->langchain-community) (2.5.0)\n", + "Requirement already satisfied: certifi>=2023.5.7 in /usr/local/lib/python3.12/dist-packages (from requests<3.0.0,>=2.32.5->langchain-community) (2026.6.17)\n", + "Requirement already satisfied: greenlet>=1 in /usr/local/lib/python3.12/dist-packages (from sqlalchemy<3.0.0,>=1.4.0->langchain-community) (3.5.3)\n", + "Requirement already satisfied: regex in /usr/local/lib/python3.12/dist-packages (from tiktoken<1.0.0,>=0.7.0->langchain-openai) (2025.11.3)\n", + "Requirement already satisfied: httpcore==1.* in /usr/local/lib/python3.12/dist-packages (from httpx<1,>=0.23.0->langsmith<1.0.0,>=0.3.45->langchain-core) (1.0.9)\n", + "Requirement already satisfied: h11>=0.16 in /usr/local/lib/python3.12/dist-packages (from httpcore==1.*->httpx<1,>=0.23.0->langsmith<1.0.0,>=0.3.45->langchain-core) (0.16.0)\n", + "Requirement already satisfied: ormsgpack>=1.12.0 in /usr/local/lib/python3.12/dist-packages (from langgraph-checkpoint<5.0.0,>=4.1.0->langgraph<1.3.0,>=1.2.5->langchain) (1.12.2)\n" + ] + } + ], + "source": [ + "!pip install langchain langchain-core langchain-openai langchain-community langchain-classic" + ] + }, + { + "cell_type": "code", + "execution_count": 35, + "id": "af96fedc", + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "af96fedc", + "outputId": "fbcbfcab-1a59-49c6-ed53-72b6acf20368" + }, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "Name: langchain\n", + "Version: 1.3.13\n", + "Summary: Building applications with LLMs through composability\n", + "Home-page: https://docs.langchain.com/\n", + "Author: \n", + "Author-email: \n", + "License: MIT\n", + "Location: /usr/local/lib/python3.12/dist-packages\n", + "Requires: langchain-core, langgraph, pydantic\n", + "Required-by: \n", + "---\n", + "Name: langchain-core\n", + "Version: 1.4.9\n", + "Summary: Building applications with LLMs through composability\n", + "Home-page: https://docs.langchain.com/\n", + "Author: \n", + "Author-email: \n", + "License: MIT\n", + "Location: /usr/local/lib/python3.12/dist-packages\n", + "Requires: jsonpatch, langchain-protocol, langsmith, packaging, pydantic, pyyaml, tenacity, typing-extensions, uuid-utils\n", + "Required-by: langchain, langchain-classic, langchain-community, langchain-openai, langchain-text-splitters, langgraph, langgraph-checkpoint, langgraph-prebuilt, langgraph-sdk\n", + "---\n", + "Name: langchain-openai\n", + "Version: 1.3.5\n", + "Summary: An integration package connecting OpenAI and LangChain\n", + "Home-page: https://docs.langchain.com/oss/python/integrations/providers/openai\n", + "Author: \n", + "Author-email: \n", + "License: MIT\n", + "Location: /usr/local/lib/python3.12/dist-packages\n", + "Requires: langchain-core, openai, tiktoken\n", + "Required-by: \n", + "---\n", + "Name: langchain-community\n", + "Version: 0.4.2\n", + "Summary: Community contributed LangChain integrations.\n", + "Home-page: https://docs.langchain.com/\n", + "Author: \n", + "Author-email: \n", + "License: MIT\n", + "Location: /usr/local/lib/python3.12/dist-packages\n", + "Requires: aiohttp, httpx-sse, langchain-classic, langchain-core, langsmith, numpy, pydantic-settings, pyyaml, requests, sqlalchemy, tenacity\n", + "Required-by: \n" + ] + } + ], + "source": [ + "!pip show langchain langchain-core langchain-openai langchain-community" + ] + }, + { + "cell_type": "code", + "execution_count": 36, + "id": "e92dff22", + "metadata": { + "tags": [], + "id": "e92dff22" + }, + "outputs": [], + "source": [ + "from langchain_openai import ChatOpenAI # ✅ 1.0.3\n", + "from langchain_core.prompts import ChatPromptTemplate # ✅ From langchain-core 1.0.5\n", + "from langchain_classic.chains import LLMChain # ✅ Legacy (install if missing)" + ] + }, + { + "cell_type": "code", + "execution_count": 42, + "id": "943237a7", + "metadata": { + "id": "943237a7" + }, + "outputs": [], + "source": [ + "# Retrieve the API key from environment variables\n", + "openai_api_key_value = os.getenv(\"OPENAI_API_KEY\")\n", + "\n", + "llm = ChatOpenAI(temperature=0, openai_api_key=openai_api_key_value)" + ] + }, + { + "cell_type": "code", + "execution_count": 43, + "id": "9b023dfd", + "metadata": { + "id": "9b023dfd" + }, + "outputs": [], + "source": [ + "prompt = ChatPromptTemplate.from_template( 'Provide detailed information about the product: {product}'\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": 44, + "id": "d7abc20b", + "metadata": { + "id": "d7abc20b" + }, + "outputs": [], + "source": [ + "chain = LLMChain(llm=llm, prompt=prompt)" + ] + }, + { + "cell_type": "code", + "source": [ + "product = 'Waterproof Phone Pouch'\n", + "chain.run(product)" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 132 + }, + "id": "hfQN9o8Sf1FZ", + "outputId": "1827640b-c2f0-4dd6-e4a2-b4c0727dab82" + }, + "id": "hfQN9o8Sf1FZ", + "execution_count": 52, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "\"A waterproof phone pouch is a protective case designed to keep your phone safe from water damage. It is typically made from a durable, waterproof material such as PVC or TPU that seals tightly to prevent water from seeping in. \\n\\nThese pouches are transparent, allowing you to still use your phone's touchscreen and camera while it is inside. They often come with a lanyard or strap for easy carrying, and some even have additional features such as a built-in compass or floatation device.\\n\\nWaterproof phone pouches are ideal for outdoor activities such as swimming, snorkeling, kayaking, or hiking in wet conditions. They provide peace of mind knowing that your phone is protected from water, dust, and dirt while still being easily accessible.\\n\\nWhen choosing a waterproof phone pouch, it is important to consider the size and compatibility with your phone model. Some pouches are designed to fit specific phone sizes, while others are more universal. It is also important to ensure that the pouch is properly sealed before submerging it in water to prevent any leaks.\\n\\nOverall, a waterproof phone pouch is a practical and affordable solution for keeping your phone safe and dry in any water-related activities.\"" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "string" + } + }, + "metadata": {}, + "execution_count": 52 + } + ] + }, + { + "cell_type": "markdown", + "id": "69b03469", + "metadata": { + "id": "69b03469" + }, + "source": [ + "## SimpleSequentialChain" + ] + }, + { + "cell_type": "code", + "execution_count": 61, + "id": "febee243", + "metadata": { + "id": "febee243" + }, + "outputs": [], + "source": [ + "from langchain_classic.chains import SimpleSequentialChain" + ] + }, + { + "cell_type": "code", + "execution_count": 62, + "id": "91e6bbe0", + "metadata": { + "id": "91e6bbe0" + }, + "outputs": [], + "source": [ + "llm = ChatOpenAI(temperature=0.9)\n", + "\n", + "# prompt template 1\n", + "first_prompt = ChatPromptTemplate.from_template(\n", + " \"\"\"\n", + " Write detailed information about the product: {product}.\n", + "\n", + " Include:\n", + " - Color options\n", + " - Product benefits\n", + " - Special features\n", + " \"\"\"\n", + ")\n", + "\n", + "# Chain 1\n", + "chain_one = LLMChain(llm=llm, prompt=first_prompt,output_key=\"product_description\")\n" + ] + }, + { + "cell_type": "code", + "execution_count": 65, + "id": "3f5d5b76", + "metadata": { + "id": "3f5d5b76" + }, + "outputs": [], + "source": [ + "# prompt template 2\n", + "second_prompt = ChatPromptTemplate.from_template(\n", + " \"\"\"\n", + " Create a product review based on this product description:\n", + "\n", + " {product_description}\n", + " \"\"\"\n", + ")\n", + "# chain 2\n", + "chain_two = LLMChain(llm=llm, prompt=second_prompt,output_key=\"product_review\")" + ] + }, + { + "cell_type": "code", + "execution_count": 111, + "id": "6c1eb2c4", + "metadata": { + "id": "6c1eb2c4" + }, + "outputs": [], + "source": [ + "overall_simple_chain = SimpleSequentialChain(chains=[chain_one, chain_two],\n", + " verbose=True\n", + " )" + ] + }, + { + "cell_type": "code", + "execution_count": 67, + "id": "78458efe", + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 647 + }, + "id": "78458efe", + "outputId": "7e242b93-b26e-432a-cde5-a933a649b964" + }, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "\n", + "\n", + "\u001b[1m> Entering new SimpleSequentialChain chain...\u001b[0m\n", + "\u001b[36;1m\u001b[1;3mThe Luxury Air Mattress is a high-quality sleeping solution that offers comfort and support in a convenient inflatable design. \n", + "\n", + "Color Options:\n", + "The Luxury Air Mattress comes in a sleek and modern black color option, providing a versatile look that can complement any bedroom decor.\n", + "\n", + "Product Benefits:\n", + "1. Comfort: The Luxury Air Mattress is designed with advanced air chamber technology that provides customized support and comfort for a restful night's sleep.\n", + "2. Durability: Made from durable materials, this air mattress is built to last and can withstand regular use without losing its shape or support.\n", + "3. Portability: This air mattress is easy to inflate and deflate, making it a great option for camping trips, guest accommodations, or any situation where a comfortable sleeping surface is needed.\n", + "4. Size Options: The Luxury Air Mattress comes in multiple size options, including twin, full, queen, and king, allowing you to choose the perfect size for your needs.\n", + "\n", + "Special Features:\n", + "1. Built-in Pump: The Luxury Air Mattress features a built-in pump that allows for easy and quick inflation and deflation, saving you time and hassle.\n", + "2. Waterproof Design: The mattress is constructed with a waterproof surface, making it easy to clean and maintain.\n", + "3. Adjustable Firmness: The air mattress allows you to adjust the firmness level to your liking, ensuring a personalized sleeping experience.\n", + "4. Raised Design: The raised height of the air mattress provides added comfort and support, making it easier to get in and out of bed.\n", + "\n", + "Overall, the Luxury Air Mattress is a premium sleeping solution that combines comfort, durability, and convenience in one versatile package. Whether you need an extra bed for guests or a comfortable sleeping surface for your own use, this air mattress is sure to deliver a restful night's sleep.\u001b[0m\n", + "\u001b[33;1m\u001b[1;3mI recently purchased the Luxury Air Mattress and I am extremely impressed with its quality and comfort. The advanced air chamber technology provides customized support that allowed me to have a restful night's sleep. The built-in pump made it so easy to inflate and deflate the mattress, saving me time and hassle. \n", + "\n", + "The waterproof design is a great feature as it makes cleaning and maintenance a breeze. I also love that I can adjust the firmness level to my liking, ensuring a personalized sleeping experience. The raised design of the mattress adds extra comfort and support, making it easy to get in and out of bed.\n", + "\n", + "I also appreciate the multiple size options available, allowing me to choose the perfect size for my needs. The sleek black color option is modern and versatile, complementing any bedroom decor. This air mattress is perfect for camping trips, guest accommodations, or any situation where a comfortable sleeping surface is needed.\n", + "\n", + "Overall, I highly recommend the Luxury Air Mattress to anyone in need of a premium sleeping solution that combines comfort, durability, and convenience in one versatile package. It truly delivers a restful night's sleep.\u001b[0m\n", + "\n", + "\u001b[1m> Finished chain.\u001b[0m\n" + ] + }, + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "\"I recently purchased the Luxury Air Mattress and I am extremely impressed with its quality and comfort. The advanced air chamber technology provides customized support that allowed me to have a restful night's sleep. The built-in pump made it so easy to inflate and deflate the mattress, saving me time and hassle. \\n\\nThe waterproof design is a great feature as it makes cleaning and maintenance a breeze. I also love that I can adjust the firmness level to my liking, ensuring a personalized sleeping experience. The raised design of the mattress adds extra comfort and support, making it easy to get in and out of bed.\\n\\nI also appreciate the multiple size options available, allowing me to choose the perfect size for my needs. The sleek black color option is modern and versatile, complementing any bedroom decor. This air mattress is perfect for camping trips, guest accommodations, or any situation where a comfortable sleeping surface is needed.\\n\\nOverall, I highly recommend the Luxury Air Mattress to anyone in need of a premium sleeping solution that combines comfort, durability, and convenience in one versatile package. It truly delivers a restful night's sleep.\"" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "string" + } + }, + "metadata": {}, + "execution_count": 67 + } + ], + "source": [ + "overall_simple_chain.run(product)" + ] + }, + { + "cell_type": "markdown", + "id": "0dd59bda-9d02-44e7-b3d6-2bec61b99d8f", + "metadata": { + "id": "0dd59bda-9d02-44e7-b3d6-2bec61b99d8f" + }, + "source": [ + "**Repeat the above twice for different products**" + ] + }, + { + "cell_type": "code", + "source": [ + "product = 'Pillows Insert'\n", + "chain.run(product)\n", + "\n", + "from langchain_classic.chains import SimpleSequentialChain\n", + "\n", + "llm = ChatOpenAI(temperature=0.9)\n", + "\n", + "# prompt template 1\n", + "first_prompt = ChatPromptTemplate.from_template(\n", + " \"\"\"\n", + " Write detailed information about the product: {product}.\n", + "\n", + " Include:\n", + " - Color options\n", + " - Product benefits\n", + " - Special features\n", + " \"\"\"\n", + ")\n", + "\n", + "# Chain 1\n", + "chain_one = LLMChain(llm=llm, prompt=first_prompt,output_key=\"product_description\")\n", + "\n", + "# prompt template 2\n", + "second_prompt = ChatPromptTemplate.from_template(\n", + " \"\"\"\n", + " Create a product review based on this product description:\n", + "\n", + " {product_description}\n", + " \"\"\"\n", + ")\n", + "# chain 2\n", + "chain_two = LLMChain(llm=llm, prompt=second_prompt,output_key=\"product_review\")\n", + "\n", + "overall_simple_chain = SimpleSequentialChain(chains=[chain_one, chain_two],\n", + " verbose=True\n", + " )\n", + "overall_simple_chain.run(product)" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 498 + }, + "id": "5Z1H0mkLjhnF", + "outputId": "a1561b7a-1e18-453d-d37a-dfefe3623a68" + }, + "id": "5Z1H0mkLjhnF", + "execution_count": 68, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "\n", + "\n", + "\u001b[1m> Entering new SimpleSequentialChain chain...\u001b[0m\n", + "\u001b[36;1m\u001b[1;3mPillows Insert:\n", + "\n", + "Color options: Pillows inserts usually come in a neutral white color to easily match with any pillow cover or decor. However, some brands might offer different color options such as grey or beige.\n", + "\n", + "Product benefits: Pillow inserts are essential for maintaining the shape and fluffiness of your pillows. They provide support and comfort for a good night's sleep or are used as decorative pillows on sofas or chairs. Pillow inserts also make it easy to change the look of your living space by simply swapping out the pillow covers.\n", + "\n", + "Special features: Some pillow inserts come with special features such as being hypoallergenic, anti-microbial, and dust mite resistant, making them suitable for individuals with allergies. Additionally, some inserts are made from eco-friendly materials like recycled polyester fiberfill or organic cotton.\n", + "\n", + "Overall, pillow inserts are versatile and practical accessories that enhance the comfort and aesthetic appeal of your living space. They come in various sizes to fit different pillow covers and can be easily washed and maintained for long-lasting use.\u001b[0m\n", + "\u001b[33;1m\u001b[1;3mI recently purchased a set of pillow inserts and I am incredibly impressed with the quality and functionality of this product. The neutral white color is perfect for matching with any pillow cover or decor, making it versatile for any room in my home.\n", + "\n", + "The benefits of these pillow inserts are abundant. Not only do they provide essential support and comfort for a restful night's sleep, but they also add a decorative touch to my sofas and chairs. I love how easy it is to change the look of my living space by simply swapping out the pillow covers with these inserts.\n", + "\n", + "What sets these pillow inserts apart are their special features. They are hypoallergenic, anti-microbial, and dust mite resistant, making them perfect for individuals like myself who suffer from allergies. I appreciate that they are made from eco-friendly materials, such as recycled polyester fiberfill or organic cotton, as I try to make sustainable choices in my home.\n", + "\n", + "Overall, these pillow inserts have truly enhanced the comfort and aesthetic appeal of my living space. They come in various sizes to fit different pillow covers and are easy to wash and maintain for long-lasting use. I highly recommend these pillow inserts to anyone looking to elevate their home decor and improve their sleep quality.\u001b[0m\n", + "\n", + "\u001b[1m> Finished chain.\u001b[0m\n" + ] + }, + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "\"I recently purchased a set of pillow inserts and I am incredibly impressed with the quality and functionality of this product. The neutral white color is perfect for matching with any pillow cover or decor, making it versatile for any room in my home.\\n\\nThe benefits of these pillow inserts are abundant. Not only do they provide essential support and comfort for a restful night's sleep, but they also add a decorative touch to my sofas and chairs. I love how easy it is to change the look of my living space by simply swapping out the pillow covers with these inserts.\\n\\nWhat sets these pillow inserts apart are their special features. They are hypoallergenic, anti-microbial, and dust mite resistant, making them perfect for individuals like myself who suffer from allergies. I appreciate that they are made from eco-friendly materials, such as recycled polyester fiberfill or organic cotton, as I try to make sustainable choices in my home.\\n\\nOverall, these pillow inserts have truly enhanced the comfort and aesthetic appeal of my living space. They come in various sizes to fit different pillow covers and are easy to wash and maintain for long-lasting use. I highly recommend these pillow inserts to anyone looking to elevate their home decor and improve their sleep quality.\"" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "string" + } + }, + "metadata": {}, + "execution_count": 68 + } + ] + }, + { + "cell_type": "code", + "source": [ + "product = 'Luxury Air Mattress'\n", + "chain.run(product)\n", + "\n", + "from langchain_classic.chains import SimpleSequentialChain\n", + "\n", + "llm = ChatOpenAI(temperature=0.9)\n", + "\n", + "# prompt template 1\n", + "first_prompt = ChatPromptTemplate.from_template(\n", + " \"\"\"\n", + " Write detailed information about the product: {product}.\n", + "\n", + " Include:\n", + " - Color options\n", + " - Product benefits\n", + " - Special features\n", + " \"\"\"\n", + ")\n", + "\n", + "# Chain 1\n", + "chain_one = LLMChain(llm=llm, prompt=first_prompt,output_key=\"product_description\")\n", + "\n", + "# prompt template 2\n", + "second_prompt = ChatPromptTemplate.from_template(\n", + " \"\"\"\n", + " Create a product review based on this product description:\n", + "\n", + " {product_description}\n", + " \"\"\"\n", + ")\n", + "# chain 2\n", + "chain_two = LLMChain(llm=llm, prompt=second_prompt,output_key=\"product_review\")\n", + "\n", + "overall_simple_chain = SimpleSequentialChain(chains=[chain_one, chain_two],\n", + " verbose=True\n", + " )\n", + "overall_simple_chain.run(product)" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 614 + }, + "id": "C8YYM09ZkEmX", + "outputId": "c5412620-624e-42f6-de57-7dc85fba77d4" + }, + "id": "C8YYM09ZkEmX", + "execution_count": 75, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "\n", + "\n", + "\u001b[1m> Entering new SimpleSequentialChain chain...\u001b[0m\n", + "\u001b[36;1m\u001b[1;3mThe Luxury Air Mattress is a premium quality mattress designed to provide ultimate comfort and support for a great night's sleep. This air mattress comes in a sleek black color, adding a touch of elegance to any bedroom decor.\n", + "\n", + "Product Benefits:\n", + "1. Comfort: The Luxury Air Mattress is constructed with a soft, velvety top layer that provides a plush sleeping surface, ensuring a comfortable and restful night's sleep.\n", + "2. Support: The mattress is designed with a sturdy and durable construction that offers firm support, helping to alleviate pressure points and promote proper spinal alignment.\n", + "3. Versatility: This air mattress is perfect for both indoor and outdoor use, making it a versatile option for camping trips, overnight guests, or as a temporary bedding solution.\n", + "4. Easy Inflation: The mattress includes a built-in electric pump that allows for quick and easy inflation within minutes, saving you time and hassle.\n", + "\n", + "Special Features:\n", + "1. Elevated Design: The Luxury Air Mattress features an elevated design that raises the mattress off the ground, providing added insulation from cold surfaces and making it easier to get in and out of bed.\n", + "2. Dual Chamber Construction: This mattress is designed with dual-chamber construction, which allows for customized firmness levels for each sleeper, ensuring personalized comfort.\n", + "3. Built-in Pillow: The mattress includes a built-in pillow for added comfort and convenience, eliminating the need for additional pillows.\n", + "4. Durable Material: The air mattress is made from puncture-resistant material, offering long-lasting durability and reliability.\n", + "5. Easy Storage: When not in use, the mattress can be deflated and conveniently stored in the included carrying bag, making it easy to transport and store away.\n", + "\n", + "Overall, the Luxury Air Mattress is a top-of-the-line bedding solution that combines luxurious comfort with practical features, making it a perfect choice for those seeking a high-quality air mattress for a restful night's sleep.\u001b[0m\n", + "\u001b[33;1m\u001b[1;3mI recently purchased the Luxury Air Mattress and I am extremely impressed with the quality and comfort it provides. The soft, velvety top layer feels luxurious to sleep on and ensures a restful night's sleep. I love that the mattress offers firm support, helping to alleviate pressure points and promote proper spinal alignment.\n", + "\n", + "One of my favorite features is the easy inflation with the built-in electric pump. It only takes a few minutes to fully inflate the mattress, saving me time and hassle. The elevated design is also a great bonus as it provides added insulation from cold surfaces and makes it easier to get in and out of bed.\n", + "\n", + "I appreciate the dual chamber construction that allows for personalized firmness levels for each sleeper, as well as the built-in pillow for added comfort. The puncture-resistant material gives me peace of mind that this mattress will last a long time.\n", + "\n", + "Overall, the Luxury Air Mattress is a top-of-the-line bedding solution that combines luxurious comfort with practical features. I highly recommend it to anyone in need of a high-quality air mattress for a great night's sleep, whether it's for indoor or outdoor use. It's definitely worth the investment!\u001b[0m\n", + "\n", + "\u001b[1m> Finished chain.\u001b[0m\n" + ] + }, + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "\"I recently purchased the Luxury Air Mattress and I am extremely impressed with the quality and comfort it provides. The soft, velvety top layer feels luxurious to sleep on and ensures a restful night's sleep. I love that the mattress offers firm support, helping to alleviate pressure points and promote proper spinal alignment.\\n\\nOne of my favorite features is the easy inflation with the built-in electric pump. It only takes a few minutes to fully inflate the mattress, saving me time and hassle. The elevated design is also a great bonus as it provides added insulation from cold surfaces and makes it easier to get in and out of bed.\\n\\nI appreciate the dual chamber construction that allows for personalized firmness levels for each sleeper, as well as the built-in pillow for added comfort. The puncture-resistant material gives me peace of mind that this mattress will last a long time.\\n\\nOverall, the Luxury Air Mattress is a top-of-the-line bedding solution that combines luxurious comfort with practical features. I highly recommend it to anyone in need of a high-quality air mattress for a great night's sleep, whether it's for indoor or outdoor use. It's definitely worth the investment!\"" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "string" + } + }, + "metadata": {}, + "execution_count": 75 + } + ] + }, + { + "cell_type": "markdown", + "id": "7b5ce18c", + "metadata": { + "id": "7b5ce18c" + }, + "source": [ + "## SequentialChain" + ] + }, + { + "cell_type": "code", + "execution_count": 96, + "id": "4c129ef6", + "metadata": { + "id": "4c129ef6" + }, + "outputs": [], + "source": [ + "from langchain_classic.chains import SequentialChain" + ] + }, + { + "cell_type": "code", + "execution_count": 97, + "id": "016187ac", + "metadata": { + "id": "016187ac" + }, + "outputs": [], + "source": [ + "llm = ChatOpenAI(temperature=0.9)\n", + "\n", + "\n", + "first_prompt = ChatPromptTemplate.from_template(\n", + " \"\"\"\n", + " Translate the following customer review into English:\n", + "\n", + " {review}\n", + " \"\"\"\n", + ")\n", + "\n", + "chain_one = LLMChain(llm=llm, prompt=first_prompt,\n", + " output_key=\"translated_review\"\n", + " )" + ] + }, + { + "cell_type": "code", + "execution_count": 98, + "id": "0fb0730e", + "metadata": { + "id": "0fb0730e" + }, + "outputs": [], + "source": [ + "second_prompt = ChatPromptTemplate.from_template(\n", + " \"\"\"Summarize the following review in one concise sentence:\n", + "\n", + " {translated_review}\n", + " \"\"\"\n", + ")\n", + "\n", + "chain_two = LLMChain(llm=llm, prompt=second_prompt,\n", + " output_key=\"summarized_review\"\n", + " )" + ] + }, + { + "cell_type": "code", + "execution_count": 101, + "id": "6accf92d", + "metadata": { + "id": "6accf92d" + }, + "outputs": [], + "source": [ + "# prompt template 3: translate to english or other language\n", + "third_prompt = ChatPromptTemplate.from_template(\n", + " \"\"\"\n", + " What language is the following review written in?\n", + "\n", + " {review}\n", + "\n", + " Respond with only the language name.\n", + " \"\"\"\n", + ")\n", + "# chain 3: input= Review and output= language\n", + "chain_three = LLMChain(llm=llm, prompt=third_prompt,\n", + " output_key=\"language\"\n", + ")\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": 102, + "id": "c7a46121", + "metadata": { + "id": "c7a46121" + }, + "outputs": [], + "source": [ + "# prompt template 4: follow up message that take as inputs the two previous prompts' variables\n", + "fourth_prompt = ChatPromptTemplate.from_template(\n", + " \"\"\"\n", + " Write a follow-up response to the following customer review.\n", + "\n", + " The response should be written in {language}.\n", + "\n", + " Review:\n", + " {translated_review}\n", + " \"\"\"\n", + ")\n", + "chain_four = LLMChain(llm=llm, prompt=fourth_prompt,\n", + " output_key=\"followup_message\"\n", + " )\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": 103, + "id": "89603117", + "metadata": { + "id": "89603117" + }, + "outputs": [], + "source": [ + "# overall_chain: input= Review\n", + "# and output= English_Review,summary, followup_message\n", + "overall_chain = SequentialChain(\n", + " chains=[chain_one, chain_two, chain_three, chain_four],\n", + " input_variables=['review'],\n", + " output_variables=['translated_review', 'summarized_review', 'followup_message'],\n", + " verbose=True\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": 104, + "id": "51b04f45", + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "51b04f45", + "outputId": "104b2d0d-08db-4ca9-b78f-6a581d5890d0" + }, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "\n", + "\n", + "\u001b[1m> Entering new SequentialChain chain...\u001b[0m\n", + "\n", + "\u001b[1m> Finished chain.\u001b[0m\n" + ] + }, + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "{'review': \"Je trouve le goût médiocre. La mousse ne tient pas, c'est bizarre. J'achète les mêmes dans le commerce et le goût est bien meilleur...\\nVieux lot ou contrefaçon !?\",\n", + " 'translated_review': \"I find the taste mediocre. The foam doesn't hold, it's strange. I buy the same ones in stores and the taste is much better... Old batch or counterfeit!?\",\n", + " 'summarized_review': \"The reviewer finds the taste of the product mediocre and suspects it may be an old batch or counterfeit because the foam doesn't hold and the taste is inferior to the ones bought in stores.\",\n", + " 'followup_message': \"Response:\\nNous sommes désolés d'apprendre que vous n'avez pas apprécié le goût de notre produit. Nous prenons la qualité de nos produits très au sérieux et nous vous assurons qu'il n'y a pas de contrefaçon. Il est possible qu'il s'agisse d'un lot défectueux et nous aimerions avoir l'opportunité de rectifier cela pour vous. Veuillez nous contacter pour que nous puissions résoudre ce problème. Merci pour vos commentaires.\"}" + ] + }, + "metadata": {}, + "execution_count": 104 + } + ], + "source": [ + "review = df.Review[5]\n", + "overall_chain(review)" + ] + }, + { + "cell_type": "markdown", + "id": "3187cf07-458a-4226-bec7-3dec7ee47af2", + "metadata": { + "id": "3187cf07-458a-4226-bec7-3dec7ee47af2" + }, + "source": [ + "**Repeat the above twice for different products or reviews**" + ] + }, + { + "cell_type": "code", + "source": [ + "review = df.Review[6]\n", + "overall_chain(review)" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "R-4GTL4Gpvk9", + "outputId": "37265f6d-681b-43bc-af35-102e458fac0b" + }, + "id": "R-4GTL4Gpvk9", + "execution_count": 106, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "\n", + "\n", + "\u001b[1m> Entering new SequentialChain chain...\u001b[0m\n", + "\n", + "\u001b[1m> Finished chain.\u001b[0m\n" + ] + }, + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "{'review': 'Está lu bonita calienta muy rápido, es muy funcional, solo falta ver cuánto dura, solo llevo 3 días en funcionamiento.',\n", + " 'translated_review': 'It is very nice, heats up very quickly, it is very functional. Just need to see how long it lasts, I have only been using it for 3 days.',\n", + " 'summarized_review': 'Overall positive review highlighting the quick heating and functionality of the product, but concerns about long-term durability due to only 3 days of use.',\n", + " 'followup_message': 'Respuesta:\\n¡Gracias por tu reseña! Nos alegra saber que estás disfrutando de tu producto y que cumple con tus expectativas en cuanto a velocidad y funcionalidad. Esperamos que te siga proporcionando un buen rendimiento a lo largo del tiempo. ¡Gracias por tu confianza y disfruta tu compra!'}" + ] + }, + "metadata": {}, + "execution_count": 106 + } + ] + }, + { + "cell_type": "code", + "source": [ + "review = df.Review[1]\n", + "overall_chain(review)" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "Qn93uxjuqiJK", + "outputId": "2625297e-0d49-432e-bb86-049f96dd1416" + }, + "id": "Qn93uxjuqiJK", + "execution_count": 121, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "\n", + "\n", + "\u001b[1m> Entering new SequentialChain chain...\u001b[0m\n", + "\n", + "\u001b[1m> Finished chain.\u001b[0m\n" + ] + }, + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "{'review': 'I loved the waterproof sac, although the opening was made of a hard plastic. I don’t know if that would break easily. But I couldn’t turn my phone on, once it was in the pouch.',\n", + " 'translated_review': 'I really liked the waterproof bag, but I was unsure about the durability of the hard plastic opening. Also, I had trouble turning on my phone once it was in the pouch.',\n", + " 'summarized_review': 'The waterproof bag has a good design, but there are concerns about the durability of the hard plastic opening and difficulties with accessing the phone while in the pouch.',\n", + " 'followup_message': \"Response:\\nThank you for your feedback! We appreciate your input regarding the durability of the hard plastic opening and the issue with turning on your phone while it's in the pouch. We will definitely take your comments into consideration for future product improvements. If you have any further concerns or need assistance, please don't hesitate to reach out to our customer support team. We value your satisfaction and hope to provide you with a better experience in the future.\"}" + ] + }, + "metadata": {}, + "execution_count": 121 + } + ] + }, + { + "cell_type": "markdown", + "id": "3041ea4c", + "metadata": { + "id": "3041ea4c" + }, + "source": [ + "## Router Chain" + ] + }, + { + "cell_type": "code", + "execution_count": 122, + "id": "ade83f4f", + "metadata": { + "id": "ade83f4f" + }, + "outputs": [], + "source": [ + "physics_template = \"\"\"You are a very smart physics professor. \\\n", + "You are great at answering questions about physics in a concise\\\n", + "and easy to understand manner. \\\n", + "When you don't know the answer to a question you admit\\\n", + "that you don't know.\n", + "\n", + "Here is a question:\n", + "{input}\"\"\"\n", + "\n", + "\n", + "math_template = \"\"\"You are a very good mathematician. \\\n", + "You are great at answering math questions. \\\n", + "You are so good because you are able to break down \\\n", + "hard problems into their component parts,\n", + "answer the component parts, and then put them together\\\n", + "to answer the broader question.\n", + "\n", + "Here is a question:\n", + "{input}\"\"\"\n", + "\n", + "history_template = \"\"\"You are a very good historian. \\\n", + "You have an excellent knowledge of and understanding of people,\\\n", + "events and contexts from a range of historical periods. \\\n", + "You have the ability to think, reflect, debate, discuss and \\\n", + "evaluate the past. You have a respect for historical evidence\\\n", + "and the ability to make use of it to support your explanations \\\n", + "and judgements.\n", + "\n", + "Here is a question:\n", + "{input}\"\"\"\n", + "\n", + "\n", + "computerscience_template = \"\"\" You are a successful computer scientist.\\\n", + "You have a passion for creativity, collaboration,\\\n", + "forward-thinking, confidence, strong problem-solving capabilities,\\\n", + "understanding of theories and algorithms, and excellent communication \\\n", + "skills. You are great at answering coding questions. \\\n", + "You are so good because you know how to solve a problem by \\\n", + "describing the solution in imperative steps \\\n", + "that a machine can easily interpret and you know how to \\\n", + "choose a solution that has a good balance between \\\n", + "time complexity and space complexity.\n", + "\n", + "Here is a question:\n", + "{input}\"\"\"\n", + "\n", + "biology_template = \"\"\"You are an excellent biologist. \\\n", + "You have a deep understanding of living organisms, \\\n", + "from the molecular and cellular level to entire ecosystems. \\\n", + "You are skilled at observing patterns in nature, analyzing biological data, \\\n", + "and explaining complex processes like evolution, genetics, physiology, and ecology. \\\n", + "You can clearly communicate how life functions and adapts, \\\n", + "and you make connections between different biological concepts \\\n", + "to answer challenging questions.\n", + "\n", + "Here is a question:\n", + "{input}\"\"\"" + ] + }, + { + "cell_type": "code", + "execution_count": 123, + "id": "5f590e9f", + "metadata": { + "id": "5f590e9f" + }, + "outputs": [], + "source": [ + "prompt_infos = [\n", + " {\n", + " \"name\": \"physics\",\n", + " \"description\": \"Good for answering questions about physics\",\n", + " \"prompt_template\": physics_template\n", + " },\n", + " {\n", + " \"name\": \"math\",\n", + " \"description\": \"Good for answering math questions\",\n", + " \"prompt_template\": math_template\n", + " },\n", + " {\n", + " \"name\": \"History\",\n", + " \"description\": \"Good for answering history questions\",\n", + " \"prompt_template\": history_template\n", + " },\n", + " {\n", + " \"name\": \"computer science\",\n", + " \"description\": \"Good for answering computer science questions\",\n", + " \"prompt_template\": computerscience_template\n", + " },\n", + " {\n", + " \"name\": \"biology\",\n", + " \"description\": \"Good for answering biology questions\",\n", + " \"prompt_template\": biology_template\n", + " }\n", + "]" + ] + }, + { + "cell_type": "code", + "execution_count": 124, + "id": "b5cfdd35", + "metadata": { + "id": "b5cfdd35" + }, + "outputs": [], + "source": [ + "from langchain_classic.chains.router import MultiPromptChain\n", + "from langchain_classic.chains.router.llm_router import LLMRouterChain, RouterOutputParser\n", + "from langchain_core.prompts import PromptTemplate # Updated path for prompts (core package)" + ] + }, + { + "cell_type": "code", + "execution_count": 125, + "id": "f3f50bcc", + "metadata": { + "id": "f3f50bcc" + }, + "outputs": [], + "source": [ + "llm = ChatOpenAI(temperature=0)" + ] + }, + { + "cell_type": "code", + "execution_count": 126, + "id": "8eefec24", + "metadata": { + "id": "8eefec24" + }, + "outputs": [], + "source": [ + "destination_chains = {}\n", + "for p_info in prompt_infos:\n", + " name = p_info[\"name\"]\n", + " prompt_template = p_info[\"prompt_template\"]\n", + " prompt = ChatPromptTemplate.from_template(template=prompt_template)\n", + " chain = LLMChain(llm=llm, prompt=prompt)\n", + " destination_chains[name] = chain\n", + "\n", + "destinations = [f\"{p['name']}: {p['description']}\" for p in prompt_infos]\n", + "destinations_str = \"\\n\".join(destinations)" + ] + }, + { + "cell_type": "code", + "execution_count": 127, + "id": "9f98018a", + "metadata": { + "id": "9f98018a" + }, + "outputs": [], + "source": [ + "default_prompt = ChatPromptTemplate.from_template(\"{input}\")\n", + "default_chain = LLMChain(llm=llm, prompt=default_prompt)" + ] + }, + { + "cell_type": "code", + "execution_count": 128, + "id": "11b2e2ba", + "metadata": { + "id": "11b2e2ba" + }, + "outputs": [], + "source": [ + "MULTI_PROMPT_ROUTER_TEMPLATE = \"\"\"Given a raw text input to a \\\n", + "language model select the model prompt best suited for the input. \\\n", + "You will be given the names of the available prompts and a \\\n", + "description of what the prompt is best suited for. \\\n", + "You may also revise the original input if you think that revising\\\n", + "it will ultimately lead to a better response from the language model.\n", + "\n", + "<< FORMATTING >>\n", + "Return a markdown code snippet with a JSON object formatted to look like:\n", + "```json\n", + "{{{{\n", + " \"destination\": string \\ name of the prompt to use or \"DEFAULT\"\n", + " \"next_inputs\": string \\ a potentially modified version of the original input\n", + "}}}}\n", + "```\n", + "\n", + "REMEMBER: \"destination\" MUST be one of the candidate prompt \\\n", + "names specified below OR it can be \"DEFAULT\" if the input is not\\\n", + "well suited for any of the candidate prompts.\n", + "REMEMBER: \"next_inputs\" can just be the original input \\\n", + "if you don't think any modifications are needed.\n", + "\n", + "<< CANDIDATE PROMPTS >>\n", + "{destinations}\n", + "\n", + "<< INPUT >>\n", + "{{input}}\n", + "\n", + "<< OUTPUT (remember to include the ```json)>>\"\"\"" + ] + }, + { + "cell_type": "code", + "execution_count": 129, + "id": "1387109d", + "metadata": { + "id": "1387109d" + }, + "outputs": [], + "source": [ + "router_template = MULTI_PROMPT_ROUTER_TEMPLATE.format(\n", + " destinations=destinations_str\n", + ")\n", + "router_prompt = PromptTemplate(\n", + " template=router_template,\n", + " input_variables=[\"input\"],\n", + " output_parser=RouterOutputParser(),\n", + ")\n", + "\n", + "router_chain = LLMRouterChain.from_llm(llm, router_prompt)" + ] + }, + { + "cell_type": "code", + "execution_count": 130, + "id": "2fb7d560", + "metadata": { + "id": "2fb7d560" + }, + "outputs": [], + "source": [ + "chain = MultiPromptChain(router_chain=router_chain,\n", + " destination_chains=destination_chains,\n", + " default_chain=default_chain, verbose=True\n", + " )" + ] + }, + { + "cell_type": "code", + "execution_count": 131, + "id": "d86b2131", + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 165 + }, + "id": "d86b2131", + "outputId": "64d0340a-95b7-41fb-cb69-7772a922f282" + }, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "\n", + "\n", + "\u001b[1m> Entering new MultiPromptChain chain...\u001b[0m\n", + "physics: {'input': 'What is black body radiation?'}\n", + "\u001b[1m> Finished chain.\u001b[0m\n" + ] + }, + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "\"Black body radiation is the electromagnetic radiation emitted by a perfect absorber of radiation, known as a black body. A black body absorbs all radiation that falls on it and emits radiation across the entire electromagnetic spectrum. The spectrum of black body radiation is continuous and depends only on the temperature of the black body. This phenomenon is described by Planck's law, which states that the intensity of radiation emitted by a black body at a given wavelength is proportional to the temperature of the body and the wavelength raised to the fifth power.\"" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "string" + } + }, + "metadata": {}, + "execution_count": 131 + } + ], + "source": [ + "chain.run(\"What is black body radiation?\")" + ] + }, + { + "cell_type": "code", + "execution_count": 132, + "id": "3b717379", + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 116 + }, + "id": "3b717379", + "outputId": "ba82532c-2f5a-4b69-a301-8a98e868eaf2" + }, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "\n", + "\n", + "\u001b[1m> Entering new MultiPromptChain chain...\u001b[0m\n", + "math: {'input': 'what is 2 + 2'}\n", + "\u001b[1m> Finished chain.\u001b[0m\n" + ] + }, + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "'The answer to 2 + 2 is 4.'" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "string" + } + }, + "metadata": {}, + "execution_count": 132 + } + ], + "source": [ + "chain.run(\"what is 2 + 2\")" + ] + }, + { + "cell_type": "code", + "execution_count": 133, + "id": "29e5be01", + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 215 + }, + "id": "29e5be01", + "outputId": "fee9b6f7-1eec-4aba-c06a-c935fad7381f" + }, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "\n", + "\n", + "\u001b[1m> Entering new MultiPromptChain chain...\u001b[0m\n", + "biology: {'input': 'Why does every cell in our body contain DNA?'}\n", + "\u001b[1m> Finished chain.\u001b[0m\n" + ] + }, + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "'Every cell in our body contains DNA because DNA is the genetic material that carries the instructions for the development, functioning, and reproduction of all living organisms. DNA contains the information needed to build and maintain an organism, including the proteins that make up our cells and tissues. \\n\\nHaving DNA in every cell ensures that each cell has the necessary genetic information to carry out its specific functions and to replicate itself accurately during cell division. This ensures that the genetic information is passed on to the next generation of cells. \\n\\nAdditionally, DNA is constantly being used by cells to carry out processes such as protein synthesis, cell division, and repair. Having DNA in every cell allows for the coordination of these processes and ensures that the organism functions properly as a whole. \\n\\nIn summary, every cell in our body contains DNA because it is essential for the proper functioning and development of all living organisms.'" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "string" + } + }, + "metadata": {}, + "execution_count": 133 + } + ], + "source": [ + "chain.run(\"Why does every cell in our body contain DNA?\")" + ] + }, + { + "cell_type": "markdown", + "id": "09e0c60b-7ae0-453e-9467-142d8dafee6e", + "metadata": { + "id": "09e0c60b-7ae0-453e-9467-142d8dafee6e" + }, + "source": [ + "**Repeat the above at least once for different inputs and chains executions - Be creative!**" + ] + }, + { + "cell_type": "code", + "source": [ + "chain.run(\"How did mathematics and computer graphics work together to create the scientifically accurate black hole in Interstellar?\")" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 215 + }, + "id": "TSTBPwYjt2WC", + "outputId": "f165e26f-04e9-4ed1-ef9f-e424de814b7b" + }, + "id": "TSTBPwYjt2WC", + "execution_count": 140, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "\n", + "\n", + "\u001b[1m> Entering new MultiPromptChain chain...\u001b[0m\n", + "computer science: {'input': 'How did mathematics and computer graphics work together to create the scientifically accurate black hole in Interstellar?'}\n", + "\u001b[1m> Finished chain.\u001b[0m\n" + ] + }, + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "\"In the movie Interstellar, the scientifically accurate black hole was created using a combination of mathematics and computer graphics. \\n\\nMathematics played a crucial role in accurately modeling the physics of a black hole. The filmmakers consulted with renowned physicist Kip Thorne, who provided them with equations and simulations that described the behavior of light and gravity near a black hole. These equations were used to create a realistic depiction of the black hole's gravitational lensing effects, as well as the warping of spacetime around it.\\n\\nComputer graphics were then used to translate these mathematical models into visually stunning images. Advanced rendering techniques were employed to simulate the bending of light around the black hole, creating the iconic visual of the black hole's accretion disk and the distorted background stars.\\n\\nBy combining the mathematical understanding of black hole physics with cutting-edge computer graphics technology, the filmmakers were able to create a scientifically accurate and visually captivating representation of a black hole in Interstellar.\"" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "string" + } + }, + "metadata": {}, + "execution_count": 140 + } + ] + }, + { + "cell_type": "code", + "source": [ + "chain.run(\"How do matrices make movie characters move and rotate realistically in CGI?\")" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 215 + }, + "id": "YUKnW1-Rt24b", + "outputId": "941678ff-40d2-4d12-a894-deeca8fe033e" + }, + "id": "YUKnW1-Rt24b", + "execution_count": 139, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "\n", + "\n", + "\u001b[1m> Entering new MultiPromptChain chain...\u001b[0m\n", + "computer science: {'input': 'How do matrices make movie characters move and rotate realistically in CGI?'}\n", + "\u001b[1m> Finished chain.\u001b[0m\n" + ] + }, + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "\"Matrices play a crucial role in creating realistic movement and rotation of movie characters in CGI (Computer Generated Imagery). In CGI, characters are represented as 3D models composed of vertices, edges, and faces. These models are manipulated using matrices to achieve various transformations such as translation, rotation, scaling, and skewing.\\n\\nTo make a character move and rotate realistically, a series of transformations are applied to the character's model. Each transformation is represented by a matrix that describes how the model should be modified. For example, to move a character from one position to another, a translation matrix is used to shift the model along the x, y, and z axes. Similarly, rotation matrices are used to rotate the character around a specific axis.\\n\\nBy combining multiple transformation matrices, complex movements and rotations can be achieved, giving the character a lifelike appearance. Additionally, matrices are used to calculate lighting effects, shadows, and reflections, further enhancing the realism of the character.\\n\\nOverall, matrices are essential in CGI for manipulating 3D models and creating realistic movements and rotations of movie characters. Their ability to efficiently represent transformations and calculate complex interactions make them a powerful tool in the world of computer graphics.\"" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "string" + } + }, + "metadata": {}, + "execution_count": 139 + } + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "langchain_env", + "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.19" + }, + "colab": { + "provenance": [] + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} \ No newline at end of file