From b0e9254fe8a5fc53568e03a885870391e7934e56 Mon Sep 17 00:00:00 2001 From: spqdot Date: Mon, 27 Jul 2026 15:53:37 +0100 Subject: [PATCH] task completed --- .gitignore | 1 + lab-chains-in-langchain.ipynb | 829 ++++++++++++++++++++++++++++++---- 2 files changed, 752 insertions(+), 78 deletions(-) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2eea525 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +.env \ No newline at end of file diff --git a/lab-chains-in-langchain.ipynb b/lab-chains-in-langchain.ipynb index 290f3bb..fd7e3ab 100644 --- a/lab-chains-in-langchain.ipynb +++ b/lab-chains-in-langchain.ipynb @@ -1,5 +1,30 @@ { "cells": [ + { + "cell_type": "code", + "execution_count": 14, + "id": "4cd79fc7", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "c:\\Users\\Shrabani P\\IronHack\\Week7_Day1\\venv_lab\\Scripts\\python.exe\n", + "0.2.43\n", + "c:\\Users\\Shrabani P\\IronHack\\Week7_Day1\\venv_lab\\Lib\\site-packages\\langchain_core\\__init__.py\n" + ] + } + ], + "source": [ + "import langchain_core\n", + "import sys\n", + "\n", + "print(sys.executable)\n", + "print(langchain_core.__version__)\n", + "print(langchain_core.__file__)" + ] + }, { "cell_type": "markdown", "id": "52824b89-532a-4e54-87e9-1410813cd39e", @@ -18,7 +43,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 15, "id": "541eb2f1", "metadata": {}, "outputs": [], @@ -29,7 +54,7 @@ }, { "cell_type": "code", - "execution_count": 3, + "execution_count": null, "id": "b7ed03ed-1322-49e3-b2a2-33e94fb592ef", "metadata": { "tags": [] @@ -37,9 +62,9 @@ "outputs": [], "source": [ "import os\n", - "\n", "from dotenv import load_dotenv, find_dotenv\n", - "_ = load_dotenv(find_dotenv())\n", + "\n", + "load_dotenv(find_dotenv())\n", "\n", "OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')\n", "HUGGINGFACEHUB_API_TOKEN = os.getenv('HUGGINGFACEHUB_API_TOKEN')" @@ -47,19 +72,32 @@ }, { "cell_type": "code", - "execution_count": 5, + "execution_count": 17, "id": "b84e441b", "metadata": { "tags": [] }, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Requirement already satisfied: pandas in c:\\Users\\Shrabani P\\IronHack\\Week7_Day1\\venv_lab\\Lib\\site-packages (3.0.5)\n", + "Requirement already satisfied: numpy>=1.26.0 in c:\\Users\\Shrabani P\\IronHack\\Week7_Day1\\venv_lab\\Lib\\site-packages (from pandas) (1.26.4)\n", + "Requirement already satisfied: python-dateutil>=2.8.2 in c:\\Users\\Shrabani P\\IronHack\\Week7_Day1\\venv_lab\\Lib\\site-packages (from pandas) (2.9.0.post0)\n", + "Requirement already satisfied: tzdata in c:\\Users\\Shrabani P\\IronHack\\Week7_Day1\\venv_lab\\Lib\\site-packages (from pandas) (2026.3)\n", + "Requirement already satisfied: six>=1.5 in c:\\Users\\Shrabani P\\IronHack\\Week7_Day1\\venv_lab\\Lib\\site-packages (from python-dateutil>=2.8.2->pandas) (1.17.0)\n", + "Note: you may need to restart the kernel to use updated packages.\n" + ] + } + ], "source": [ - "#!pip install pandas" + "pip install pandas" ] }, { "cell_type": "code", - "execution_count": 13, + "execution_count": 18, "id": "974acf8e-8f88-42de-88f8-40a82cb58e8b", "metadata": { "tags": [] @@ -67,12 +105,12 @@ "outputs": [], "source": [ "import pandas as pd\n", - "df = pd.read_csv('./lab/data/Data.csv')" + "df = pd.read_csv(r\"C:\\Users\\Shrabani P\\IronHack\\Week7_Day1\\Lab_Week7_Day1\\lab-chains-in-langchain\\data\\Data.csv\")" ] }, { "cell_type": "code", - "execution_count": 15, + "execution_count": 19, "id": "b7a09c35", "metadata": { "tags": [] @@ -126,7 +164,7 @@ " \n", " \n", " 4\n", - " Milk Frother Handheld\\n\n", + " Milk Frother Handheld\\r\\n\n", " I loved this product. But they only seem to l...\n", " \n", " \n", @@ -134,15 +172,22 @@ "" ], "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..." + " Product \\\n", + "0 Queen Size Sheet Set \n", + "1 Waterproof Phone Pouch \n", + "2 Luxury Air Mattress \n", + "3 Pillows Insert \n", + "4 Milk Frother Handheld\\r\\n \n", + "\n", + " Review \n", + "0 I ordered a king size set. My only criticism w... \n", + "1 I loved the waterproof sac, although the openi... \n", + "2 This mattress had a small hole in the top of i... \n", + "3 This is the best throw pillow fillers on Amazo... \n", + "4  I loved this product. But they only seem to l... " ] }, - "execution_count": 15, + "execution_count": 19, "metadata": {}, "output_type": "execute_result" } @@ -161,17 +206,52 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 20, "id": "427e1119", "metadata": {}, "outputs": [], "source": [ - "!pip install langchain_community" + "#!pip install langchain_community" ] }, { "cell_type": "code", - "execution_count": 17, + "execution_count": 21, + "id": "bc05fdce", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Python executable:\n", + "c:\\Users\\Shrabani P\\IronHack\\Week7_Day1\\venv_lab\\Scripts\\python.exe\n", + "\n", + "LangChain Core version:\n", + "0.2.43\n", + "\n", + "LangChain Core file:\n", + "c:\\Users\\Shrabani P\\IronHack\\Week7_Day1\\venv_lab\\Lib\\site-packages\\langchain_core\\__init__.py\n" + ] + } + ], + "source": [ + "import sys\n", + "import langchain_core\n", + "\n", + "print(\"Python executable:\")\n", + "print(sys.executable)\n", + "\n", + "print(\"\\nLangChain Core version:\")\n", + "print(langchain_core.__version__)\n", + "\n", + "print(\"\\nLangChain Core file:\")\n", + "print(langchain_core.__file__)" + ] + }, + { + "cell_type": "code", + "execution_count": 22, "id": "e92dff22", "metadata": { "tags": [] @@ -185,46 +265,154 @@ }, { "cell_type": "code", - "execution_count": null, - "id": "943237a7", + "execution_count": 23, + "id": "a3f35125", "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "LangChain: 0.2.17\n", + "LangChain Core: 0.2.43\n", + "LangChain OpenAI: 0.1.25\n" + ] + } + ], + "source": [ + "import langchain\n", + "import langchain_core\n", + "import importlib.metadata\n", + "\n", + "print(\"LangChain:\", langchain.__version__)\n", + "print(\"LangChain Core:\", langchain_core.__version__)\n", + "print(\"LangChain OpenAI:\", importlib.metadata.version(\"langchain-openai\"))" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "id": "0895338b", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "OpenAI: 1.40.8\n", + "httpx: 0.28.1\n" + ] + } + ], + "source": [ + "import openai\n", + "import httpx\n", + "\n", + "print(\"OpenAI:\", openai.__version__)\n", + "print(\"httpx:\", httpx.__version__)" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "36b5e1e0", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0.27.2\n" + ] + } + ], + "source": [ + "import httpx\n", + "print(httpx.__version__)" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "38947582", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "client= async_client= root_client= root_async_client= temperature=0.0 openai_api_key=SecretStr('**********') openai_proxy=''\n" + ] + } + ], "source": [ "#Replace None by your own value and justify\n", - "llm = ChatOpenAI(temperature=None)\n" + "from langchain_openai import ChatOpenAI\n", + "\n", + "llm = ChatOpenAI(temperature=0)\n", + "print(llm)\n" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 6, "id": "cdcdb42d", "metadata": {}, "outputs": [], "source": [ - "prompt = ChatPromptTemplate.from_template( #Write a query that would take a variable to describe any product\n", - " \n", - ")" + "from langchain.prompts import ChatPromptTemplate\n", + "prompt = ChatPromptTemplate.from_template(\"Write a detailed and positive Amazon product review for the following product: {product}\")\n" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 8, "id": "d7abc20b", "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "C:\\Users\\Shrabani P\\AppData\\Local\\Temp\\ipykernel_9852\\1810907789.py:2: LangChainDeprecationWarning: The class `LLMChain` was deprecated in LangChain 0.1.17 and will be removed in 1.0. Use RunnableSequence, e.g., `prompt | llm` instead.\n", + " chain = LLMChain(llm=llm, prompt=prompt)\n" + ] + } + ], "source": [ "\n", + "from langchain.chains import LLMChain\n", "chain = LLMChain(llm=llm, prompt=prompt)" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 10, "id": "ad44d1fb", "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "C:\\Users\\Shrabani P\\AppData\\Local\\Temp\\ipykernel_9852\\3521529869.py:3: LangChainDeprecationWarning: The method `Chain.run` was deprecated in langchain 0.1.0 and will be removed in 1.0. Use invoke instead.\n", + " chain.run(product)\n" + ] + }, + { + "data": { + "text/plain": [ + "\"I absolutely love my new Wireless Bluetooth Headphones! These headphones have completely changed my listening experience and I couldn't be happier with my purchase.\\n\\nFirst of all, the sound quality is amazing. The bass is deep and rich, the mids are clear, and the highs are crisp. I can hear every detail in my music, whether I'm listening to my favorite songs or watching a movie. The noise-cancelling feature is also fantastic, as it blocks out any background noise and allows me to fully immerse myself in whatever I'm listening to.\\n\\nThe Bluetooth connectivity is seamless and I have had no issues with pairing my headphones to my devices. The range is also impressive, as I can walk around my house without any signal interruptions. The battery life is great as well, lasting me several hours on a single charge. I also appreciate the comfort of the headphones, as they are lightweight and the ear cups are soft and cushioned.\\n\\nOverall, I highly recommend these Wireless Bluetooth Headphones to anyone in the market for a new pair of headphones. The sound quality, connectivity, battery life, and comfort are all top-notch. I am extremely satisfied with my purchase and will definitely be purchasing from this brand again in the future.\"" + ] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ - "product = #Select a product type to be describe\n", + "product = \"Wireless Bluetooth Headphones\"\n", + "\n", "chain.run(product)" ] }, @@ -238,7 +426,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 11, "id": "febee243", "metadata": {}, "outputs": [], @@ -248,7 +436,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 13, "id": "2f31aa8a", "metadata": {}, "outputs": [], @@ -257,8 +445,7 @@ "\n", "# prompt template 1\n", "first_prompt = ChatPromptTemplate.from_template(\n", - " #Repeat the initial query or create a new query that would feed into the second prompt\n", - ")\n", + " \"Write a detailed and engaging product description for the following product: {product}\")\n", "\n", "# Chain 1\n", "chain_one = LLMChain(llm=llm, prompt=first_prompt)" @@ -266,7 +453,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 14, "id": "3f5d5b76", "metadata": {}, "outputs": [], @@ -274,7 +461,7 @@ "\n", "# prompt template 2\n", "second_prompt = ChatPromptTemplate.from_template(\n", - " #Write the second prompt query that takes an input variable whose input will come from the previous prompt\"\n", + " \"Based on the following product description, create a catchy marketing slogan:\\n\\n{product_description}\"\n", ")\n", "# chain 2\n", "chain_two = LLMChain(llm=llm, prompt=second_prompt)" @@ -282,7 +469,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 15, "id": "6c1eb2c4", "metadata": {}, "outputs": [], @@ -294,10 +481,46 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 16, "id": "78458efe", "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "Error in StdOutCallbackHandler.on_chain_start callback: AttributeError(\"'NoneType' object has no attribute 'get'\")\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\u001b[36;1m\u001b[1;3mIntroducing the ultimate in convenience and technology - our Wireless Bluetooth Headphones. Experience unparalleled sound quality and freedom of movement with these sleek and stylish headphones.\n", + "\n", + "With cutting-edge Bluetooth technology, you can seamlessly connect to any Bluetooth-enabled device, allowing you to listen to your favorite music or take calls with crystal-clear clarity. Say goodbye to tangled cords and bulky adapters, as these headphones provide a hassle-free audio experience.\n", + "\n", + "Featuring an ergonomic design and adjustable headband, these headphones are built for maximum comfort, even during long listening sessions. The soft cushioned ear cups provide a snug fit and excellent noise isolation, allowing you to immerse yourself in your music without any distractions.\n", + "\n", + "Whether you're jogging in the park, working out at the gym, or commuting to work, these headphones are the perfect companion for your active lifestyle. The rechargeable battery provides up to 12 hours of continuous playback, so you can enjoy your music all day long.\n", + "\n", + "Take your audio experience to the next level with our Wireless Bluetooth Headphones. Upgrade your listening experience and enjoy the freedom of wireless connectivity today.\u001b[0m\n", + "\u001b[33;1m\u001b[1;3m\"Cut the cord and elevate your sound with our Wireless Bluetooth Headphones\"\u001b[0m\n", + "\n", + "\u001b[1m> Finished chain.\u001b[0m\n" + ] + }, + { + "data": { + "text/plain": [ + "'\"Cut the cord and elevate your sound with our Wireless Bluetooth Headphones\"'" + ] + }, + "execution_count": 16, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "overall_simple_chain.run(product)" ] @@ -320,7 +543,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 21, "id": "4c129ef6", "metadata": {}, "outputs": [], @@ -330,7 +553,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 23, "id": "016187ac", "metadata": {}, "outputs": [], @@ -339,50 +562,51 @@ "\n", "\n", "first_prompt = ChatPromptTemplate.from_template(\n", - " #This prompt should translate a review\n", + " \"Translate the following customer review from English to Spanish:\\n\\n{review}\"\n", ")\n", "\n", + "\n", "chain_one = LLMChain(llm=llm, prompt=first_prompt, \n", - " output_key=None #Give a name to your output\n", + " output_key=\"translated_review\" #Give a name to your output\n", " )\n" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 24, "id": "0fb0730e", "metadata": {}, "outputs": [], "source": [ "second_prompt = ChatPromptTemplate.from_template(\n", - " #Write a promplt to summarize a review\n", + " \"Summarize the following review in one sentence:\\n\\n{translated_review}\"\n", ")\n", "\n", "chain_two = LLMChain(llm=llm, prompt=second_prompt, \n", - " output_key=None #give a name to this output\n", + " output_key=\"summary\" #give a name to this output\n", " )\n" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 27, "id": "6accf92d", "metadata": {}, "outputs": [], "source": [ "# prompt template 3: translate to english or other language\n", "third_prompt = ChatPromptTemplate.from_template(\n", - " None\n", + " \"Analyze the sentiment of the following review summary and classify it as Positive, Negative, or Neutral:\\n\\n{summary}\"\n", ")\n", "# chain 3: input= Review and output= language\n", "chain_three = LLMChain(llm=llm, prompt=third_prompt,\n", - " output_key=None\n", + " output_key=\"sentiment\"\n", " )\n" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 28, "id": "c7a46121", "metadata": {}, "outputs": [], @@ -390,16 +614,16 @@ "\n", "# prompt template 4: follow up message that take as inputs the two previous prompts' variables\n", "fourth_prompt = ChatPromptTemplate.from_template(\n", - " None\n", + " \"Write a polite response to the customer based on this sentiment: {sentiment}\"\n", ")\n", "chain_four = LLMChain(llm=llm, prompt=fourth_prompt,\n", - " output_key=None\n", + " output_key=\"response\"\n", " )\n" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 30, "id": "89603117", "metadata": {}, "outputs": [], @@ -408,8 +632,8 @@ "# and output= English_Review,summary, followup_message\n", "overall_chain = SequentialChain(\n", " chains=[chain_one, chain_two, chain_three, chain_four],\n", - " input_variables=None,\n", - " output_variables=[None, None, None],\n", + " input_variables=[\"review\"],\n", + " output_variables=[\"translated_review\", \"summary\", \"sentiment\", \"response\"],\n", " verbose=True\n", ")" ] @@ -433,6 +657,296 @@ "**Repeat the above twice for different products or reviews**" ] }, + { + "cell_type": "code", + "execution_count": 31, + "id": "f1c0d324", + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "Error in StdOutCallbackHandler.on_chain_start callback: AttributeError(\"'NoneType' object has no attribute 'get'\")\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "\u001b[1m> Finished chain.\u001b[0m\n", + "{'review': 'This laptop is fast, lightweight, and has excellent battery life.', 'translated_review': 'Esta computadora portátil es rápida, liviana y tiene una excelente duración de la batería.', 'summary': 'Esta computadora portátil es rápida, liviana y tiene una excelente duración de la batería.', 'sentiment': 'Positive', 'response': \"Thank you so much for your kind words! We are thrilled to hear that you had a positive experience with our product/service. If you have any questions or need further assistance, please don't hesitate to reach out to us. We appreciate your support!\"}\n" + ] + } + ], + "source": [ + "review1 = \"This laptop is fast, lightweight, and has excellent battery life.\"\n", + "result1 = overall_chain.invoke({\"review\": review1})\n", + "print(result1)" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "id": "a469fa5f", + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "Error in StdOutCallbackHandler.on_chain_start callback: AttributeError(\"'NoneType' object has no attribute 'get'\")\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "\u001b[1m> Finished chain.\u001b[0m\n", + "{'review': 'The headphones have poor sound quality and the battery drains quickly.', 'translated_review': 'Los auriculares tienen una mala calidad de sonido y la batería se agota rápidamente.', 'summary': 'Los auriculares tienen una mala calidad de sonido y la duración de la batería es corta.', 'sentiment': 'Negative', 'response': 'Thank you for sharing your feedback with us. We apologize for any inconvenience or dissatisfaction you have experienced. Your input is valuable to us as we strive to improve our service and meet the needs of our customers. If there is anything specific you would like to address or discuss further, please feel free to reach out to us. We appreciate your business and hope to have the opportunity to serve you better in the future.'}\n" + ] + } + ], + "source": [ + "review2 = \"The headphones have poor sound quality and the battery drains quickly.\"\n", + "result2 = overall_chain.invoke({\"review\": review2})\n", + "print(result2)" + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "id": "47312046", + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "Error in StdOutCallbackHandler.on_chain_start callback: AttributeError(\"'NoneType' object has no attribute 'get'\")\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "\u001b[1m> Finished chain.\u001b[0m\n", + "{'review': 'The coffee maker is easy to use and makes great coffee every morning.', 'translated_review': 'La cafetera es fácil de usar y hace un café delicioso todas las mañanas.', 'summary': 'La cafetera es fácil de usar y produce café delicioso todas las mañanas.', 'sentiment': 'Positive', 'response': \"Thank you so much for your kind words! We truly appreciate your positive feedback and are delighted to hear that you enjoyed your experience with us. We strive to provide excellent service to all our customers, and it means a lot to us to know that we have met your expectations. If you ever have any questions or need assistance in the future, please don't hesitate to reach out. Thank you for choosing us as your provider and we look forward to serving you again soon.\"}\n" + ] + } + ], + "source": [ + "review3 = \"The coffee maker is easy to use and makes great coffee every morning.\"\n", + "result3 = overall_chain.invoke({\"review\": review3})\n", + "print(result3)" + ] + }, + { + "cell_type": "code", + "execution_count": 34, + "id": "0dd357e5", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "I absolutely love my new Smart Watch! This device has completely changed the way I approach my daily routine and has become an essential part of my everyday life.\n", + "\n", + "First and foremost, the design of the Smart Watch is sleek and stylish. I love the modern look and feel of the watch, and it looks great with any outfit. The touchscreen display is vibrant and easy to read, making it simple to navigate through the various features and functions.\n", + "\n", + "The functionality of the Smart Watch is truly impressive. I can track my steps, monitor my heart rate, and even receive notifications from my phone right on my wrist. The built-in GPS is incredibly accurate, and I love being able to track my runs and hikes without having to carry my phone with me.\n", + "\n", + "One of my favorite features of the Smart Watch is the sleep tracking. I have always struggled with getting a good night's sleep, but the watch has helped me identify patterns and make adjustments to improve my sleep quality. The battery life is also impressive, lasting me several days on a single charge.\n", + "\n", + "Overall, I cannot recommend the Smart Watch enough. It has truly enhanced my daily life and helped me stay on top of my health and fitness goals. If you are in the market for a smartwatch, look no further than this fantastic product.\n", + "I recently purchased the Gaming Laptop and I am extremely impressed with its performance and features. From the moment I opened the box, I could tell that this laptop was built with quality in mind. The design is sleek and modern, with a backlit keyboard that adds a cool touch to the overall look.\n", + "\n", + "The gaming experience on this laptop is top-notch. The graphics are crisp and clear, and the processing power is lightning fast. I have played several high-intensity games on this laptop and it has handled them with ease. The cooling system works efficiently to prevent overheating, even during long gaming sessions.\n", + "\n", + "One of the standout features of this laptop is the display. The screen is vibrant and immersive, with a high refresh rate that makes gameplay incredibly smooth. The sound quality is also impressive, with loud and clear audio that enhances the gaming experience.\n", + "\n", + "In addition to its gaming capabilities, this laptop is also great for everyday use. The battery life is decent, lasting several hours on a single charge. The keyboard is comfortable to type on, and the touchpad is responsive and accurate.\n", + "\n", + "Overall, I highly recommend the Gaming Laptop to anyone in the market for a high-performance gaming laptop. It offers excellent value for the price and delivers on all fronts. Whether you are a casual gamer or a hardcore enthusiast, this laptop will exceed your expectations.\n", + "I absolutely love my new wireless earbuds! These earbuds have completely changed my listening experience and I couldn't be happier with my purchase.\n", + "\n", + "First of all, the sound quality is amazing. The bass is deep and rich, the mids are clear, and the highs are crisp. I can hear every detail in my music, podcasts, and phone calls. The noise-cancelling feature is also fantastic, as it blocks out any background noise so I can fully immerse myself in whatever I'm listening to.\n", + "\n", + "The design of the earbuds is sleek and modern. They fit comfortably in my ears and stay in place even when I'm on the move. The touch controls are easy to use and allow me to adjust the volume, skip tracks, and answer calls with just a tap of my finger.\n", + "\n", + "The battery life is impressive as well. I can use these earbuds for hours on end without needing to recharge them. The charging case is compact and convenient, making it easy to take my earbuds with me wherever I go.\n", + "\n", + "Overall, I highly recommend these wireless earbuds to anyone in the market for a new pair. The sound quality, design, and battery life are all top-notch, and I couldn't be happier with my purchase. Trust me, you won't be disappointed with these earbuds!\n" + ] + } + ], + "source": [ + "product1 = \"Smart Watch\"\n", + "print(chain.run(product1))\n", + "\n", + "product2 = \"Gaming Laptop\"\n", + "print(chain.run(product2))\n", + "\n", + "product3 = \"Wireless Earbuds\"\n", + "print(chain.run(product3))" + ] + }, + { + "cell_type": "markdown", + "id": "8d42c8a6", + "metadata": {}, + "source": [ + "### Analyze the sentiment\n" + ] + }, + { + "cell_type": "code", + "execution_count": 35, + "id": "c097fa40", + "metadata": {}, + "outputs": [], + "source": [ + "first_prompt = ChatPromptTemplate.from_template(\n", + " \"Determine whether the following movie review is Positive, Negative, or Neutral:\\n\\n{review}\"\n", + ")\n", + "\n", + "chain_one = LLMChain(\n", + " llm=llm,\n", + " prompt=first_prompt,\n", + " output_key=\"sentiment\"\n", + ")" + ] + }, + { + "cell_type": "markdown", + "id": "bf09b4d8", + "metadata": {}, + "source": [ + "### Recommend a movie" + ] + }, + { + "cell_type": "code", + "execution_count": 36, + "id": "b9986ed7", + "metadata": {}, + "outputs": [], + "source": [ + "second_prompt = ChatPromptTemplate.from_template(\n", + " \"Based on the sentiment '{sentiment}', recommend a similar movie.\"\n", + ")\n", + "\n", + "chain_two = LLMChain(\n", + " llm=llm,\n", + " prompt=second_prompt,\n", + " output_key=\"recommendation\"\n", + ")" + ] + }, + { + "cell_type": "markdown", + "id": "5ecf1e60", + "metadata": {}, + "source": [ + "### Explain the recommendation" + ] + }, + { + "cell_type": "code", + "execution_count": 37, + "id": "03109f3d", + "metadata": {}, + "outputs": [], + "source": [ + "third_prompt = ChatPromptTemplate.from_template(\n", + " \"Explain in 2-3 sentences why someone would enjoy this movie:\\n\\n{recommendation}\"\n", + ")\n", + "\n", + "chain_three = LLMChain(\n", + " llm=llm,\n", + " prompt=third_prompt,\n", + " output_key=\"explanation\"\n", + ")" + ] + }, + { + "cell_type": "markdown", + "id": "61916dae", + "metadata": {}, + "source": [ + "### Write a tweet" + ] + }, + { + "cell_type": "code", + "execution_count": 38, + "id": "af76b313", + "metadata": {}, + "outputs": [], + "source": [ + "fourth_prompt = ChatPromptTemplate.from_template(\n", + " \"Write a short tweet promoting this movie:\\n\\n{explanation}\"\n", + ")\n", + "\n", + "chain_four = LLMChain(\n", + " llm=llm,\n", + " prompt=fourth_prompt,\n", + " output_key=\"tweet\"\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": 39, + "id": "f297e974", + "metadata": {}, + "outputs": [], + "source": [ + "from langchain.chains import SequentialChain\n", + "\n", + "overall_chain = SequentialChain(\n", + " chains=[chain_one, chain_two, chain_three, chain_four],\n", + " input_variables=[\"review\"],\n", + " output_variables=[\"sentiment\", \"recommendation\", \"explanation\", \"tweet\"],\n", + " verbose=True\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": 40, + "id": "39a3a33d", + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "Error in StdOutCallbackHandler.on_chain_start callback: AttributeError(\"'NoneType' object has no attribute 'get'\")\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "\u001b[1m> Finished chain.\u001b[0m\n", + "{'review': 'The movie had an amazing story, fantastic acting, and stunning visuals.', 'sentiment': 'Positive', 'recommendation': 'I recommend \"Finding Nemo\", a heartwarming animated film about a father clownfish named Marlin who embarks on a journey to find his son, Nemo, who has been captured by a scuba diver. The movie is filled with humor, adventure, and themes of love and family, making it a positive and uplifting experience for viewers.', 'explanation': 'Viewers would enjoy \"Finding Nemo\" for its endearing characters, beautiful animation, and engaging storyline that explores the bond between parent and child. The film\\'s humor and heartwarming moments make it a delightful and uplifting experience for audiences of all ages.', 'tweet': '\"Dive into the heartwarming underwater world of \\'Finding Nemo\\'! With lovable characters, stunning animation, and a touching storyline, this film is a must-watch for the whole family. 🐠🌊 #FindingNemo #Pixar #FamilyMovieNight\"'}\n" + ] + } + ], + "source": [ + "review = \"The movie had an amazing story, fantastic acting, and stunning visuals.\"\n", + "\n", + "result = overall_chain.invoke({\"review\": review})\n", + "\n", + "print(result)" + ] + }, { "cell_type": "markdown", "id": "3041ea4c", @@ -443,7 +957,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 41, "id": "ade83f4f", "metadata": {}, "outputs": [], @@ -509,7 +1023,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 42, "id": "5f590e9f", "metadata": {}, "outputs": [], @@ -545,7 +1059,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 43, "id": "31b06fc8", "metadata": {}, "outputs": [], @@ -557,7 +1071,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 44, "id": "f3f50bcc", "metadata": {}, "outputs": [], @@ -567,7 +1081,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 45, "id": "8eefec24", "metadata": {}, "outputs": [], @@ -586,7 +1100,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 46, "id": "9f98018a", "metadata": {}, "outputs": [], @@ -597,10 +1111,21 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 47, "id": "11b2e2ba", "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "<>:1: SyntaxWarning: invalid escape sequence '\\ '\n", + "<>:1: SyntaxWarning: invalid escape sequence '\\ '\n", + "C:\\Users\\Shrabani P\\AppData\\Local\\Temp\\ipykernel_9852\\2160379643.py:1: SyntaxWarning: invalid escape sequence '\\ '\n", + " MULTI_PROMPT_ROUTER_TEMPLATE = \"\"\"Given a raw text input to a \\\n" + ] + } + ], "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", @@ -635,7 +1160,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 48, "id": "1387109d", "metadata": {}, "outputs": [], @@ -654,10 +1179,19 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 49, "id": "2fb7d560", "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "C:\\Users\\Shrabani P\\AppData\\Local\\Temp\\ipykernel_9852\\3038952769.py:1: LangChainDeprecationWarning: Use RunnableLambda to select from multiple prompt templates. See example in API reference: https://api.python.langchain.com/en/latest/chains/langchain.chains.router.multi_prompt.MultiPromptChain.html\n", + " chain = MultiPromptChain(router_chain=router_chain,\n" + ] + } + ], "source": [ "chain = MultiPromptChain(router_chain=router_chain, \n", " destination_chains=destination_chains, \n", @@ -667,30 +1201,108 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 50, "id": "d86b2131", "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "Error in StdOutCallbackHandler.on_chain_start callback: AttributeError(\"'NoneType' object has no attribute 'get'\")\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "physics: {'input': 'What is black body radiation?'}\n", + "\u001b[1m> Finished chain.\u001b[0m\n" + ] + }, + { + "data": { + "text/plain": [ + "\"Black body radiation refers to the electromagnetic radiation emitted by a perfect black body, which is an idealized physical body that absorbs all incident electromagnetic radiation. The radiation emitted by a black body depends only on its temperature and follows a specific distribution known as Planck's law. This radiation is characterized by a continuous spectrum of wavelengths and intensities, with the peak intensity shifting to shorter wavelengths as the temperature of the black body increases. Black body radiation plays a key role in understanding concepts such as thermal radiation and the quantization of energy in quantum mechanics.\"" + ] + }, + "execution_count": 50, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "chain.run(\"What is black body radiation?\")" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 51, "id": "3b717379", "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "Error in StdOutCallbackHandler.on_chain_start callback: AttributeError(\"'NoneType' object has no attribute 'get'\")\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "math: {'input': 'what is 2 + 2'}\n", + "\u001b[1m> Finished chain.\u001b[0m\n" + ] + }, + { + "data": { + "text/plain": [ + "'The answer to 2 + 2 is 4.'" + ] + }, + "execution_count": 51, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "chain.run(\"what is 2 + 2\")" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 52, "id": "29e5be01", "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "Error in StdOutCallbackHandler.on_chain_start callback: AttributeError(\"'NoneType' object has no attribute 'get'\")\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "biology: {'input': 'Why does every cell in our body contain DNA?'}\n", + "\u001b[1m> Finished chain.\u001b[0m\n" + ] + }, + { + "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.'" + ] + }, + "execution_count": 52, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "chain.run(\"Why does every cell in our body contain DNA?\")" ] @@ -702,11 +1314,72 @@ "source": [ "**Repeat the above at least once for different inputs and chains executions - Be creative!**" ] + }, + { + "cell_type": "code", + "execution_count": 53, + "id": "302ca336", + "metadata": {}, + "outputs": [], + "source": [ + "from langchain.prompts import PromptTemplate\n", + "\n", + "order_prompt = PromptTemplate(\n", + " input_variables=[\"input\"],\n", + " template=\"You are an order support specialist. Answer this question:\\n{input}\"\n", + ")\n", + "\n", + "tech_prompt = PromptTemplate(\n", + " input_variables=[\"input\"],\n", + " template=\"You are a technical support specialist. Answer this question:\\n{input}\"\n", + ")\n", + "\n", + "billing_prompt = PromptTemplate(\n", + " input_variables=[\"input\"],\n", + " template=\"You are a billing specialist. Answer this question:\\n{input}\"\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": 54, + "id": "c04bb2f9", + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "Error in StdOutCallbackHandler.on_chain_start callback: AttributeError(\"'NoneType' object has no attribute 'get'\")\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "None: {'input': 'I have a question about my recent order. Can you help me?'}\n", + "\u001b[1m> Finished chain.\u001b[0m\n", + "Of course! I'll do my best to assist you. What is your question about your recent order?\n" + ] + } + ], + "source": [ + "response = chain.run(\"I have a question about my recent order. Can you help me?\")\n", + "print(response)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6051840f", + "metadata": {}, + "outputs": [], + "source": [] } ], "metadata": { "kernelspec": { - "display_name": "Python 3 (ipykernel)", + "display_name": "venv_lab (3.12.4.final.0)", "language": "python", "name": "python3" }, @@ -720,7 +1393,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.11.8" + "version": "3.12.4" } }, "nbformat": 4,