From d8f44ff7b74aba1d62d3cddac08e2a190c6f3185 Mon Sep 17 00:00:00 2001
From: DNL <240179864+zeroKool1ne@users.noreply.github.com>
Date: Tue, 14 Jul 2026 21:40:21 +0200
Subject: [PATCH] lab solved
---
lab-chains-in-langchain.ipynb | 1500 +++++++++++++++++----------------
1 file changed, 778 insertions(+), 722 deletions(-)
diff --git a/lab-chains-in-langchain.ipynb b/lab-chains-in-langchain.ipynb
index 290f3bb..b8aa962 100644
--- a/lab-chains-in-langchain.ipynb
+++ b/lab-chains-in-langchain.ipynb
@@ -1,728 +1,784 @@
{
- "cells": [
- {
- "cell_type": "markdown",
- "id": "52824b89-532a-4e54-87e9-1410813cd39e",
- "metadata": {},
- "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": null,
- "id": "541eb2f1",
- "metadata": {},
- "outputs": [],
- "source": [
- "import warnings\n",
- "warnings.filterwarnings('ignore')"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 3,
- "id": "b7ed03ed-1322-49e3-b2a2-33e94fb592ef",
- "metadata": {
- "tags": []
- },
- "outputs": [],
- "source": [
- "import os\n",
- "\n",
- "from dotenv import load_dotenv, find_dotenv\n",
- "_ = load_dotenv(find_dotenv())\n",
- "\n",
- "OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')\n",
- "HUGGINGFACEHUB_API_TOKEN = os.getenv('HUGGINGFACEHUB_API_TOKEN')"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 5,
- "id": "b84e441b",
- "metadata": {
- "tags": []
- },
- "outputs": [],
- "source": [
- "#!pip install pandas"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 13,
- "id": "974acf8e-8f88-42de-88f8-40a82cb58e8b",
- "metadata": {
- "tags": []
- },
- "outputs": [],
- "source": [
- "import pandas as pd\n",
- "df = pd.read_csv('./lab/data/Data.csv')"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 15,
- "id": "b7a09c35",
- "metadata": {
- "tags": []
- },
- "outputs": [
+ "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": 7,
+ "id": "541eb2f1",
+ "metadata": {
+ "id": "541eb2f1"
+ },
+ "outputs": [],
+ "source": [
+ "import warnings\n",
+ "warnings.filterwarnings('ignore')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 13,
+ "id": "b7ed03ed-1322-49e3-b2a2-33e94fb592ef",
+ "metadata": {
+ "tags": [],
+ "id": "b7ed03ed-1322-49e3-b2a2-33e94fb592ef"
+ },
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "from google.colab import userdata\n",
+ "\n",
+ "CLAUDE_API_KEY = userdata.get('claude_ironhack')\n",
+ "os.environ[\"ANTHROPIC_API_KEY\"] = CLAUDE_API_KEY # so pickt langchain_anthropic den Key automatisch auf\n",
+ "\n",
+ "import pandas as pd\n",
+ "df = pd.read_csv('https://raw.githubusercontent.com/zeroKool1ne/lab-chains-in-langchain/main/data/Data.csv')\n",
+ "df.head()\n",
+ "HUGGINGFACEHUB_API_TOKEN = os.getenv('hugging_face')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "b84e441b",
+ "metadata": {
+ "tags": [],
+ "id": "b84e441b"
+ },
+ "outputs": [],
+ "source": [
+ "#!pip install pandas"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 14,
+ "id": "974acf8e-8f88-42de-88f8-40a82cb58e8b",
+ "metadata": {
+ "tags": [],
+ "id": "974acf8e-8f88-42de-88f8-40a82cb58e8b",
+ "outputId": "7e8de6d1-33d5-44a4-d913-ff3ce3c0e63a",
+ "colab": {
+ "base_uri": "https://localhost:8080/",
+ "height": 206
+ }
+ },
+ "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",
+ " Product | \n",
+ " Review | \n",
+ "
\n",
+ " \n",
+ " \n",
+ " \n",
+ " | 0 | \n",
+ " Queen Size Sheet Set | \n",
+ " I ordered a king size set. My only criticism w... | \n",
+ "
\n",
+ " \n",
+ " | 1 | \n",
+ " Waterproof Phone Pouch | \n",
+ " I loved the waterproof sac, although the openi... | \n",
+ "
\n",
+ " \n",
+ " | 2 | \n",
+ " Luxury Air Mattress | \n",
+ " This mattress had a small hole in the top of i... | \n",
+ "
\n",
+ " \n",
+ " | 3 | \n",
+ " Pillows Insert | \n",
+ " This is the best throw pillow fillers on Amazo... | \n",
+ "
\n",
+ " \n",
+ " | 4 | \n",
+ " Milk Frother Handheld\\n | \n",
+ " I loved this product. But they only seem to l... | \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": 14
+ }
+ ],
+ "source": [
+ "import pandas as pd\n",
+ "\n",
+ "# github.com/DEINUSER/DEINFORK/blob/main/data/dataset.csv\n",
+ "# → raw.githubusercontent.com/DEINUSER/DEINFORK/main/data/dataset.csv\n",
+ "\n",
+ "url = \"https://raw.githubusercontent.com/zeroKool1ne/lab-chains-in-langchain/refs/heads/main/data/Data.csv\"\n",
+ "df = pd.read_csv(url)\n",
+ "df.head()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "b7a09c35",
+ "metadata": {
+ "tags": [],
+ "id": "b7a09c35",
+ "outputId": "aa87df63-7c63-45ac-c510-cf6ae156012f"
+ },
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "\n",
+ "\n",
+ "
\n",
+ " \n",
+ " \n",
+ " | \n",
+ " Product | \n",
+ " Review | \n",
+ "
\n",
+ " \n",
+ " \n",
+ " \n",
+ " | 0 | \n",
+ " Queen Size Sheet Set | \n",
+ " I ordered a king size set. My only criticism w... | \n",
+ "
\n",
+ " \n",
+ " | 1 | \n",
+ " Waterproof Phone Pouch | \n",
+ " I loved the waterproof sac, although the openi... | \n",
+ "
\n",
+ " \n",
+ " | 2 | \n",
+ " Luxury Air Mattress | \n",
+ " This mattress had a small hole in the top of i... | \n",
+ "
\n",
+ " \n",
+ " | 3 | \n",
+ " Pillows Insert | \n",
+ " This is the best throw pillow fillers on Amazo... | \n",
+ "
\n",
+ " \n",
+ " | 4 | \n",
+ " Milk Frother Handheld\\n | \n",
+ " I loved this product. But they only seem to l... | \n",
+ "
\n",
+ " \n",
+ "
\n",
+ "
"
+ ],
+ "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..."
+ ]
+ },
+ "execution_count": 15,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "df.head()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "b940ce7c",
+ "metadata": {
+ "id": "b940ce7c"
+ },
+ "source": [
+ "## LLMChain"
+ ]
+ },
{
- "data": {
- "text/html": [
- "\n",
- "\n",
- "
\n",
- " \n",
- " \n",
- " | \n",
- " Product | \n",
- " Review | \n",
- "
\n",
- " \n",
- " \n",
- " \n",
- " | 0 | \n",
- " Queen Size Sheet Set | \n",
- " I ordered a king size set. My only criticism w... | \n",
- "
\n",
- " \n",
- " | 1 | \n",
- " Waterproof Phone Pouch | \n",
- " I loved the waterproof sac, although the openi... | \n",
- "
\n",
- " \n",
- " | 2 | \n",
- " Luxury Air Mattress | \n",
- " This mattress had a small hole in the top of i... | \n",
- "
\n",
- " \n",
- " | 3 | \n",
- " Pillows Insert | \n",
- " This is the best throw pillow fillers on Amazo... | \n",
- "
\n",
- " \n",
- " | 4 | \n",
- " Milk Frother Handheld\\n | \n",
- " I loved this product. But they only seem to l... | \n",
- "
\n",
- " \n",
- "
\n",
- "
"
+ "cell_type": "code",
+ "execution_count": 1,
+ "id": "427e1119",
+ "metadata": {
+ "id": "427e1119",
+ "outputId": "c4fc3f51-5232-4947-8ebc-220902a38c9a",
+ "colab": {
+ "base_uri": "https://localhost:8080/"
+ }
+ },
+ "outputs": [
+ {
+ "output_type": "stream",
+ "name": "stdout",
+ "text": [
+ "Collecting langchain_community\n",
+ " Downloading langchain_community-0.4.2-py3-none-any.whl.metadata (3.4 kB)\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",
+ "Collecting httpx-sse<1.0.0,>=0.4.0 (from langchain_community)\n",
+ " Downloading httpx_sse-0.4.3-py3-none-any.whl.metadata (9.7 kB)\n",
+ "Collecting langchain-classic<2.0.0,>=1.0.7 (from langchain_community)\n",
+ " Downloading langchain_classic-1.0.8-py3-none-any.whl.metadata (5.1 kB)\n",
+ "Requirement already satisfied: langchain-core<2.0.0,>=1.4.0 in /usr/local/lib/python3.12/dist-packages (from langchain_community) (1.4.8)\n",
+ "Requirement already satisfied: langsmith<1.0.0,>=0.1.125 in /usr/local/lib/python3.12/dist-packages (from langchain_community) (0.9.1)\n",
+ "Requirement already satisfied: numpy>=1.26.2 in /usr/local/lib/python3.12/dist-packages (from langchain_community) (2.0.2)\n",
+ "Collecting pydantic-settings<3.0.0,>=2.10.1 (from langchain_community)\n",
+ " Downloading pydantic_settings-2.14.2-py3-none-any.whl.metadata (3.4 kB)\n",
+ "Requirement already satisfied: pyyaml<7.0.0,>=5.3.0 in /usr/local/lib/python3.12/dist-packages (from langchain_community) (6.0.3)\n",
+ "Collecting requests<3.0.0,>=2.32.5 (from langchain_community)\n",
+ " Downloading requests-2.34.2-py3-none-any.whl.metadata (4.8 kB)\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: tenacity!=8.4.0,<10.0.0,>=8.1.0 in /usr/local/lib/python3.12/dist-packages (from langchain_community) (9.1.4)\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.6.2)\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: typing_extensions>=4.4 in /usr/local/lib/python3.12/dist-packages (from aiohttp<4.0.0,>=3.8.3->langchain_community) (4.15.0)\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",
+ "Collecting langchain-text-splitters<2.0.0,>=1.1.2 (from langchain-classic<2.0.0,>=1.0.7->langchain_community)\n",
+ " Downloading langchain_text_splitters-1.1.2-py3-none-any.whl.metadata (3.3 kB)\n",
+ "Requirement already satisfied: pydantic<3.0.0,>=2.7.4 in /usr/local/lib/python3.12/dist-packages (from langchain-classic<2.0.0,>=1.0.7->langchain_community) (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<2.0.0,>=1.4.0->langchain_community) (1.33)\n",
+ "Requirement already satisfied: langchain-protocol>=0.0.17 in /usr/local/lib/python3.12/dist-packages (from langchain-core<2.0.0,>=1.4.0->langchain_community) (0.0.18)\n",
+ "Requirement already satisfied: packaging>=23.2.0 in /usr/local/lib/python3.12/dist-packages (from langchain-core<2.0.0,>=1.4.0->langchain_community) (26.2)\n",
+ "Requirement already satisfied: uuid-utils<1.0,>=0.12.0 in /usr/local/lib/python3.12/dist-packages (from langchain-core<2.0.0,>=1.4.0->langchain_community) (0.16.2)\n",
+ "Requirement already satisfied: anyio>=3.5.0 in /usr/local/lib/python3.12/dist-packages (from langsmith<1.0.0,>=0.1.125->langchain_community) (4.14.0)\n",
+ "Requirement already satisfied: distro>=1.7.0 in /usr/local/lib/python3.12/dist-packages (from langsmith<1.0.0,>=0.1.125->langchain_community) (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.1.125->langchain_community) (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.1.125->langchain_community) (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.1.125->langchain_community) (1.0.0)\n",
+ "Requirement already satisfied: sniffio>=1.1 in /usr/local/lib/python3.12/dist-packages (from langsmith<1.0.0,>=0.1.125->langchain_community) (1.3.1)\n",
+ "Requirement already satisfied: websockets>=15.0 in /usr/local/lib/python3.12/dist-packages (from langsmith<1.0.0,>=0.1.125->langchain_community) (15.0.1)\n",
+ "Requirement already satisfied: xxhash>=3.0.0 in /usr/local/lib/python3.12/dist-packages (from langsmith<1.0.0,>=0.1.125->langchain_community) (3.7.1)\n",
+ "Requirement already satisfied: zstandard>=0.23.0 in /usr/local/lib/python3.12/dist-packages (from langsmith<1.0.0,>=0.1.125->langchain_community) (0.25.0)\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: typing-inspection>=0.4.0 in /usr/local/lib/python3.12/dist-packages (from pydantic-settings<3.0.0,>=2.10.1->langchain_community) (0.4.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.7)\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.2)\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.1.125->langchain_community) (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.1.125->langchain_community) (0.16.0)\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<2.0.0,>=1.4.0->langchain_community) (3.1.1)\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-classic<2.0.0,>=1.0.7->langchain_community) (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-classic<2.0.0,>=1.0.7->langchain_community) (2.46.4)\n",
+ "Downloading langchain_community-0.4.2-py3-none-any.whl (2.4 MB)\n",
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m2.4/2.4 MB\u001b[0m \u001b[31m27.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
+ "\u001b[?25hDownloading httpx_sse-0.4.3-py3-none-any.whl (9.0 kB)\n",
+ "Downloading langchain_classic-1.0.8-py3-none-any.whl (1.0 MB)\n",
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m1.0/1.0 MB\u001b[0m \u001b[31m53.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
+ "\u001b[?25hDownloading pydantic_settings-2.14.2-py3-none-any.whl (61 kB)\n",
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m61.7/61.7 kB\u001b[0m \u001b[31m5.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
+ "\u001b[?25hDownloading requests-2.34.2-py3-none-any.whl (73 kB)\n",
+ "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m73.1/73.1 kB\u001b[0m \u001b[31m6.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
+ "\u001b[?25hDownloading langchain_text_splitters-1.1.2-py3-none-any.whl (35 kB)\n",
+ "Installing collected packages: requests, httpx-sse, pydantic-settings, langchain-text-splitters, langchain-classic, langchain_community\n",
+ " Attempting uninstall: requests\n",
+ " Found existing installation: requests 2.32.4\n",
+ " Uninstalling requests-2.32.4:\n",
+ " Successfully uninstalled requests-2.32.4\n",
+ "\u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n",
+ "google-colab 1.0.0 requires requests==2.32.4, but you have requests 2.34.2 which is incompatible.\u001b[0m\u001b[31m\n",
+ "\u001b[0mSuccessfully installed httpx-sse-0.4.3 langchain-classic-1.0.8 langchain-text-splitters-1.1.2 langchain_community-0.4.2 pydantic-settings-2.14.2 requests-2.34.2\n"
+ ]
+ }
],
- "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..."
+ "source": [
+ "!pip install langchain_community"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 15,
+ "id": "e92dff22",
+ "metadata": {
+ "tags": [],
+ "id": "e92dff22",
+ "outputId": "65b543d8-1ae8-4be2-a196-e5afd78bd70e",
+ "colab": {
+ "base_uri": "https://localhost:8080/",
+ "height": 278
+ }
+ },
+ "outputs": [
+ {
+ "output_type": "execute_result",
+ "data": {
+ "text/plain": [
+ "'# Best Names for a Queen Size Sheet Set Company\\n\\nHere are some strong options:\\n\\n## Direct/Descriptive\\n- **Royal Linens** - suggests quality and the \"royal\" size\\n- **Queen Bedding Co.** - straightforward and clear\\n- **Premium Sheet Company** - emphasizes quality\\n\\n## More Creative\\n- **Luxe Linens** - upscale, memorable\\n- **Thread & Crown** - elegant, subtle reference to \"queen\"\\n- **Serene Sheets** - focuses on comfort/sleep quality\\n- **Woven Royalty** - combines product with size reference\\n\\n## Modern/Trendy\\n- **Nest & Linen** - cozy, contemporary feel\\n- **Threshold Home** - suggests quality standards\\n- **Fiber & Form** - emphasizes craftsmanship\\n\\n## Key Considerations\\n- **Avoid being too narrow** if you might expand product lines later\\n- **Make it memorable** - something customers can easily recall and spell\\n- **Consider your brand positioning** - luxury, eco-friendly, affordable, etc.\\n\\n**My top pick:** **Luxe Linens** or **Royal Linens** — they\\'re professional, memorable, and naturally suggest quality bedding without limiting you to just queen sizes.\\n\\nWhat\\'s your brand\\'s positioning or target market? That would help narrow it down further.'"
+ ],
+ "application/vnd.google.colaboratory.intrinsic+json": {
+ "type": "string"
+ }
+ },
+ "metadata": {},
+ "execution_count": 15
+ }
+ ],
+ "source": [
+ "!pip install -q langchain_community langchain-anthropic\n",
+ "\n",
+ "from langchain_anthropic import ChatAnthropic\n",
+ "from langchain_core.prompts import ChatPromptTemplate\n",
+ "from langchain_classic.chains import LLMChain\n",
+ "\n",
+ "# temperature=0.7: genug Kreativität für einen Produktnamen, aber nicht wild halluzinierend\n",
+ "llm = ChatAnthropic(model=\"claude-haiku-4-5\", temperature=0.7)\n",
+ "\n",
+ "prompt = ChatPromptTemplate.from_template(\n",
+ " \"What is the best name to describe a company that makes {product}?\"\n",
+ ")\n",
+ "chain = LLMChain(llm=llm, prompt=prompt)\n",
+ "\n",
+ "product = df.Product[0] # \"Queen Size Sheet Set\"\n",
+ "chain.run(product)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "69b03469",
+ "metadata": {
+ "id": "69b03469"
+ },
+ "source": [
+ "## SimpleSequentialChain"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 16,
+ "id": "943237a7",
+ "metadata": {
+ "id": "943237a7",
+ "outputId": "76617009-aaa8-425b-b897-b3fccc4c5174",
+ "colab": {
+ "base_uri": "https://localhost:8080/"
+ }
+ },
+ "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",
+ " 'English_Review': \"# English Translation\\n\\nI find the taste mediocre. The mousse doesn't hold up, it's strange. I buy the same ones in stores and the taste is much better...\\nOld batch or counterfeit!?\",\n",
+ " 'summary': 'The reviewer found the product disappointing due to mediocre taste and poor mousse texture, suspecting it may be an old or counterfeit batch compared to store-bought versions.',\n",
+ " 'followup_message': \"# Réponse de suivi\\n\\nMerci d'avoir partagé vos commentaires détaillés. Nous sommes vraiment désolés d'apprendre que votre expérience avec notre produit n'a pas été à la hauteur de vos attentes.\\n\\nVos observations concernant le goût médiocre et la texture de la mousse sont des préoccupations que nous prenons très au sérieux. Nous vous assurons que nous n'utilisons que des ingrédients de qualité supérieure dans nos formulations standards.\\n\\nConcernant votre suspicion d'un lot ancien ou contrefait, nous aimerions investiguer davantage :\\n\\n- **Pouvez-vous vérifier la date d'expiration** sur l'emballage ?\\n- **Où avez-vous acheté ce produit ?** (plateforme en ligne, détaillant spécifique, etc.)\\n- **Pouvez-vous nous envoyer une photo** du numéro de lot et de l'emballage ?\\n\\nCes informations nous aideront à déterminer l'authenticité et la fraîcheur du produit. Si nous découvrons qu'il s'agit effectivement d'un problème de qualité ou d'authenticité, nous serons heureux de vous proposer un remboursement complet ou un remplacement.\\n\\nNous apprécions votre vigilance et souhaitons rectifier cette situation.\"}"
+ ]
+ },
+ "metadata": {},
+ "execution_count": 16
+ }
+ ],
+ "source": [
+ "#Replace None by your own value and justify\n",
+ "from langchain_classic.chains import SequentialChain\n",
+ "\n",
+ "llm = ChatAnthropic(model=\"claude-haiku-4-5\", temperature=0.9)\n",
+ "\n",
+ "first_prompt = ChatPromptTemplate.from_template(\n",
+ " \"Translate the following review to English:\\n\\n{Review}\"\n",
+ ")\n",
+ "chain_one = LLMChain(llm=llm, prompt=first_prompt, output_key=\"English_Review\")\n",
+ "\n",
+ "second_prompt = ChatPromptTemplate.from_template(\n",
+ " \"Can you summarize the following review in 1 sentence:\\n\\n{English_Review}\"\n",
+ ")\n",
+ "chain_two = LLMChain(llm=llm, prompt=second_prompt, output_key=\"summary\")\n",
+ "\n",
+ "third_prompt = ChatPromptTemplate.from_template(\n",
+ " \"What language is the following review:\\n\\n{Review}\"\n",
+ ")\n",
+ "chain_three = LLMChain(llm=llm, prompt=third_prompt, output_key=\"language\")\n",
+ "\n",
+ "fourth_prompt = ChatPromptTemplate.from_template(\n",
+ " \"Write a follow up response to the following summary in the specified language:\"\n",
+ " \"\\n\\nSummary: {summary}\\n\\nLanguage: {language}\"\n",
+ ")\n",
+ "chain_four = LLMChain(llm=llm, prompt=fourth_prompt, output_key=\"followup_message\")\n",
+ "\n",
+ "overall_chain = SequentialChain(\n",
+ " chains=[chain_one, chain_two, chain_three, chain_four],\n",
+ " input_variables=[\"Review\"],\n",
+ " output_variables=[\"English_Review\", \"summary\", \"followup_message\"],\n",
+ " verbose=True\n",
+ ")\n",
+ "\n",
+ "review = df.Review[5]\n",
+ "overall_chain(review)\n"
+ ]
+ },
+ {
+ "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": "markdown",
+ "id": "7b5ce18c",
+ "metadata": {
+ "id": "7b5ce18c"
+ },
+ "source": [
+ "## SequentialChain"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "source": [
+ "from langchain_classic.chains import SequentialChain\n",
+ "\n",
+ "llm = ChatAnthropic(model=\"claude-haiku-4-5\", temperature=0.9)\n",
+ "\n",
+ "first_prompt = ChatPromptTemplate.from_template(\n",
+ " \"Translate the following review to English:\\n\\n{Review}\"\n",
+ ")\n",
+ "chain_one = LLMChain(llm=llm, prompt=first_prompt, output_key=\"English_Review\")\n",
+ "\n",
+ "second_prompt = ChatPromptTemplate.from_template(\n",
+ " \"Can you summarize the following review in 1 sentence:\\n\\n{English_Review}\"\n",
+ ")\n",
+ "chain_two = LLMChain(llm=llm, prompt=second_prompt, output_key=\"summary\")\n",
+ "\n",
+ "third_prompt = ChatPromptTemplate.from_template(\n",
+ " \"What language is the following review:\\n\\n{Review}\"\n",
+ ")\n",
+ "chain_three = LLMChain(llm=llm, prompt=third_prompt, output_key=\"language\")\n",
+ "\n",
+ "fourth_prompt = ChatPromptTemplate.from_template(\n",
+ " \"Write a follow up response to the following summary in the specified language:\"\n",
+ " \"\\n\\nSummary: {summary}\\n\\nLanguage: {language}\"\n",
+ ")\n",
+ "chain_four = LLMChain(llm=llm, prompt=fourth_prompt, output_key=\"followup_message\")\n",
+ "\n",
+ "overall_chain = SequentialChain(\n",
+ " chains=[chain_one, chain_two, chain_three, chain_four],\n",
+ " input_variables=[\"Review\"],\n",
+ " output_variables=[\"English_Review\", \"summary\", \"followup_message\"],\n",
+ " verbose=True\n",
+ ")\n",
+ "\n",
+ "review = df.Review[5]\n",
+ "overall_chain(review)"
+ ],
+ "metadata": {
+ "id": "fBMDQpv7IpXv",
+ "outputId": "d03dbc60-cb4e-4b0a-cd5a-7889e3979450",
+ "colab": {
+ "base_uri": "https://localhost:8080/"
+ }
+ },
+ "id": "fBMDQpv7IpXv",
+ "execution_count": 17,
+ "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",
+ " 'English_Review': \"# Translation to English:\\n\\nI find the taste mediocre. The foam doesn't hold up, it's strange. I buy the same ones in stores and the taste is much better...\\nOld batch or counterfeit!?\",\n",
+ " 'summary': \"The reviewer is dissatisfied with the product's mediocre taste and poor foam quality, suspecting it may be an old or counterfeit batch compared to store-bought versions.\",\n",
+ " 'followup_message': \"# Réponse de suivi\\n\\nMerci beaucoup pour votre retour détaillé. Nous sommes vraiment désolés d'apprendre que vous avez eu une expérience décevante avec notre produit concernant le goût et la qualité de la mousse.\\n\\nVos préoccupations sont tout à fait légitimes, et nous prenons très au sérieux la possibilité que vous ayez reçu un lot ancien ou contrefait. Cela ne correspond absolument pas aux standards de qualité que nous garantissons.\\n\\n**Nous vous proposons :**\\n\\n- De nous contacter directement avec les détails de votre achat (date, numéro de lot si visible, lieu d'achat)\\n- Un remplacement immédiat du produit ou un remboursement complet\\n- Une vérification de l'authenticité du produit pour assurer qu'il provient de notre source officielle\\n\\nNous aimerions également comprendre où vous avez acheté cet article, car si c'est auprès d'un revendeur non autorisé, cela pourrait expliquer la différence de qualité par rapport à vos achats en magasin.\\n\\nN'hésitez pas à nous envoyer une photo du produit et de son emballage pour que nous puissions enquêter plus avant.\\n\\nMerci de nous donner l'opportunité de corriger cette situation.\"}"
+ ]
+ },
+ "metadata": {},
+ "execution_count": 17
+ }
+ ]
+ },
+ {
+ "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": "markdown",
+ "id": "3041ea4c",
+ "metadata": {
+ "id": "3041ea4c"
+ },
+ "source": [
+ "## Router Chain"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "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\n",
+ "\n",
+ "llm = ChatAnthropic(model=\"claude-haiku-4-5\", temperature=0)\n",
+ "\n",
+ "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)\n",
+ "\n",
+ "default_prompt = ChatPromptTemplate.from_template(\"{input}\")\n",
+ "default_chain = LLMChain(llm=llm, prompt=default_prompt)\n",
+ "\n",
+ "router_template = MULTI_PROMPT_ROUTER_TEMPLATE.format(destinations=destinations_str)\n",
+ "router_prompt = PromptTemplate(\n",
+ " template=router_template,\n",
+ " input_variables=[\"input\"],\n",
+ " output_parser=RouterOutputParser(),\n",
+ ")\n",
+ "router_chain = LLMRouterChain.from_llm(llm, router_prompt)\n",
+ "\n",
+ "chain = MultiPromptChain(router_chain=router_chain,\n",
+ " destination_chains=destination_chains,\n",
+ " default_chain=default_chain, verbose=True)\n",
+ "\n",
+ "chain.run(\"What is black body radiation?\")\n",
+ "chain.run(\"what is 2 + 2\")\n",
+ "chain.run(\"Why does every cell in our body contain DNA?\")\n",
+ "chain.run(\"What triggered the fall of the Berlin Wall?\") # eigenes kreatives Beispiel für die \"be creative\"-Anforderung"
+ ],
+ "metadata": {
+ "id": "2d9aHfPEI53a",
+ "outputId": "f32252ef-5e79-44c2-e831-974f169a5ba8",
+ "colab": {
+ "base_uri": "https://localhost:8080/",
+ "height": 245
+ }
+ },
+ "id": "2d9aHfPEI53a",
+ "execution_count": 18,
+ "outputs": [
+ {
+ "output_type": "error",
+ "ename": "NameError",
+ "evalue": "name 'prompt_infos' is not defined",
+ "traceback": [
+ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
+ "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)",
+ "\u001b[0;32m/tmp/ipykernel_2230/3359830302.py\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 6\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 7\u001b[0m \u001b[0mdestination_chains\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m{\u001b[0m\u001b[0;34m}\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 8\u001b[0;31m \u001b[0;32mfor\u001b[0m \u001b[0mp_info\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mprompt_infos\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 9\u001b[0m \u001b[0mname\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mp_info\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m\"name\"\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 10\u001b[0m \u001b[0mprompt_template\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mp_info\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m\"prompt_template\"\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
+ "\u001b[0;31mNameError\u001b[0m: name 'prompt_infos' is not defined"
+ ]
+ }
+ ]
+ },
+ {
+ "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!**"
]
- },
- "execution_count": 15,
- "metadata": {},
- "output_type": "execute_result"
}
- ],
- "source": [
- "df.head()"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "b940ce7c",
- "metadata": {},
- "source": [
- "## LLMChain"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "id": "427e1119",
- "metadata": {},
- "outputs": [],
- "source": [
- "!pip install langchain_community"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 17,
- "id": "e92dff22",
- "metadata": {
- "tags": []
- },
- "outputs": [],
- "source": [
- "from langchain_openai import ChatOpenAI\n",
- "from langchain.prompts import ChatPromptTemplate\n",
- "from langchain.chains import LLMChain"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "id": "943237a7",
- "metadata": {},
- "outputs": [],
- "source": [
- "#Replace None by your own value and justify\n",
- "llm = ChatOpenAI(temperature=None)\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "id": "cdcdb42d",
- "metadata": {},
- "outputs": [],
- "source": [
- "prompt = ChatPromptTemplate.from_template( #Write a query that would take a variable to describe any product\n",
- " \n",
- ")"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "id": "d7abc20b",
- "metadata": {},
- "outputs": [],
- "source": [
- "\n",
- "chain = LLMChain(llm=llm, prompt=prompt)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "id": "ad44d1fb",
- "metadata": {},
- "outputs": [],
- "source": [
- "product = #Select a product type to be describe\n",
- "chain.run(product)"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "69b03469",
- "metadata": {},
- "source": [
- "## SimpleSequentialChain"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "id": "febee243",
- "metadata": {},
- "outputs": [],
- "source": [
- "from langchain.chains import SimpleSequentialChain"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "id": "2f31aa8a",
- "metadata": {},
- "outputs": [],
- "source": [
- "llm = ChatOpenAI(temperature=0.9)\n",
- "\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",
- "\n",
- "# Chain 1\n",
- "chain_one = LLMChain(llm=llm, prompt=first_prompt)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "id": "3f5d5b76",
- "metadata": {},
- "outputs": [],
- "source": [
- "\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",
- ")\n",
- "# chain 2\n",
- "chain_two = LLMChain(llm=llm, prompt=second_prompt)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "id": "6c1eb2c4",
- "metadata": {},
- "outputs": [],
- "source": [
- "overall_simple_chain = SimpleSequentialChain(chains=[chain_one, chain_two],\n",
- " verbose=True\n",
- " )"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "id": "78458efe",
- "metadata": {},
- "outputs": [],
- "source": [
- "overall_simple_chain.run(product)"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "0dd59bda-9d02-44e7-b3d6-2bec61b99d8f",
- "metadata": {},
- "source": [
- "**Repeat the above twice for different products**"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "7b5ce18c",
- "metadata": {},
- "source": [
- "## SequentialChain"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "id": "4c129ef6",
- "metadata": {},
- "outputs": [],
- "source": [
- "from langchain.chains import SequentialChain"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "id": "016187ac",
- "metadata": {},
- "outputs": [],
- "source": [
- "llm = ChatOpenAI(temperature=0.9)\n",
- "\n",
- "\n",
- "first_prompt = ChatPromptTemplate.from_template(\n",
- " #This prompt should translate a review\n",
- ")\n",
- "\n",
- "chain_one = LLMChain(llm=llm, prompt=first_prompt, \n",
- " output_key=None #Give a name to your output\n",
- " )\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "id": "0fb0730e",
- "metadata": {},
- "outputs": [],
- "source": [
- "second_prompt = ChatPromptTemplate.from_template(\n",
- " #Write a promplt to summarize a review\n",
- ")\n",
- "\n",
- "chain_two = LLMChain(llm=llm, prompt=second_prompt, \n",
- " output_key=None #give a name to this output\n",
- " )\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "id": "6accf92d",
- "metadata": {},
- "outputs": [],
- "source": [
- "# prompt template 3: translate to english or other language\n",
- "third_prompt = ChatPromptTemplate.from_template(\n",
- " None\n",
- ")\n",
- "# chain 3: input= Review and output= language\n",
- "chain_three = LLMChain(llm=llm, prompt=third_prompt,\n",
- " output_key=None\n",
- " )\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "id": "c7a46121",
- "metadata": {},
- "outputs": [],
- "source": [
- "\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",
- ")\n",
- "chain_four = LLMChain(llm=llm, prompt=fourth_prompt,\n",
- " output_key=None\n",
- " )\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "id": "89603117",
- "metadata": {},
- "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=None,\n",
- " output_variables=[None, None, None],\n",
- " verbose=True\n",
- ")"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "id": "51b04f45",
- "metadata": {},
- "outputs": [],
- "source": [
- "review = df.Review[5]\n",
- "overall_chain(review)"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "3187cf07-458a-4226-bec7-3dec7ee47af2",
- "metadata": {},
- "source": [
- "**Repeat the above twice for different products or reviews**"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "3041ea4c",
- "metadata": {},
- "source": [
- "## Router Chain"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "id": "ade83f4f",
- "metadata": {},
- "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": null,
- "id": "5f590e9f",
- "metadata": {},
- "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": null,
- "id": "31b06fc8",
- "metadata": {},
- "outputs": [],
- "source": [
- "from langchain.chains.router import MultiPromptChain\n",
- "from langchain.chains.router.llm_router import LLMRouterChain,RouterOutputParser\n",
- "from langchain.prompts import PromptTemplate"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "id": "f3f50bcc",
- "metadata": {},
- "outputs": [],
- "source": [
- "llm = ChatOpenAI(temperature=0)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "id": "8eefec24",
- "metadata": {},
- "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": null,
- "id": "9f98018a",
- "metadata": {},
- "outputs": [],
- "source": [
- "default_prompt = ChatPromptTemplate.from_template(\"{input}\")\n",
- "default_chain = LLMChain(llm=llm, prompt=default_prompt)"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "id": "11b2e2ba",
- "metadata": {},
- "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": null,
- "id": "1387109d",
- "metadata": {},
- "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": null,
- "id": "2fb7d560",
- "metadata": {},
- "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": null,
- "id": "d86b2131",
- "metadata": {},
- "outputs": [],
- "source": [
- "chain.run(\"What is black body radiation?\")"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "id": "3b717379",
- "metadata": {},
- "outputs": [],
- "source": [
- "chain.run(\"what is 2 + 2\")"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "id": "29e5be01",
- "metadata": {},
- "outputs": [],
- "source": [
- "chain.run(\"Why does every cell in our body contain DNA?\")"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "09e0c60b-7ae0-453e-9467-142d8dafee6e",
- "metadata": {},
- "source": [
- "**Repeat the above at least once for different inputs and chains executions - Be creative!**"
- ]
- }
- ],
- "metadata": {
- "kernelspec": {
- "display_name": "Python 3 (ipykernel)",
- "language": "python",
- "name": "python3"
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3 (ipykernel)",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.11.8"
+ },
+ "colab": {
+ "provenance": []
+ }
},
- "language_info": {
- "codemirror_mode": {
- "name": "ipython",
- "version": 3
- },
- "file_extension": ".py",
- "mimetype": "text/x-python",
- "name": "python",
- "nbconvert_exporter": "python",
- "pygments_lexer": "ipython3",
- "version": "3.11.8"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 5
-}
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
\ No newline at end of file
|