├── L1-models_prompts_parsers.ipynb ├── L2-memory.ipynb ├── L3-chains.ipynb ├── L4-QnA.ipynb ├── L5-Evaluation.ipynb ├── L6-Agents.ipynb ├── LICENSE ├── README.md ├── data.csv └── myntra_products_catalog.csv /L1-models_prompts_parsers.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "attachments": {}, 5 | "cell_type": "markdown", 6 | "metadata": {}, 7 | "source": [ 8 | "# LangChain: Models, Prompts and Output Parsers\n", 9 | "\n", 10 | "\n", 11 | "## Outline\n", 12 | "\n", 13 | " * Direct API calls to OpenAI\n", 14 | " * API calls through LangChain:\n", 15 | " * Prompts\n", 16 | " * Models\n", 17 | " * Output parsers" 18 | ] 19 | }, 20 | { 21 | "attachments": {}, 22 | "cell_type": "markdown", 23 | "metadata": {}, 24 | "source": [ 25 | "## Get your [OpenAI API Key](https://platform.openai.com/account/api-keys)" 26 | ] 27 | }, 28 | { 29 | "cell_type": "code", 30 | "execution_count": 32, 31 | "metadata": {}, 32 | "outputs": [], 33 | "source": [ 34 | "#!pip install python-dotenv\n", 35 | "#!pip install openai" 36 | ] 37 | }, 38 | { 39 | "cell_type": "code", 40 | "execution_count": 33, 41 | "metadata": {}, 42 | "outputs": [], 43 | "source": [ 44 | "import openai\n", 45 | "import os\n", 46 | "from dotenv import load_dotenv, find_dotenv\n", 47 | "_ = load_dotenv(find_dotenv()) # load environment variables from .env\n", 48 | "openai.api_key = os.getenv(\"OPENAI_API_KEY\")" 49 | ] 50 | }, 51 | { 52 | "attachments": {}, 53 | "cell_type": "markdown", 54 | "metadata": {}, 55 | "source": [ 56 | "## Chat API : OpenAI\n", 57 | "\n", 58 | "Let's start with a direct API calls to OpenAI." 59 | ] 60 | }, 61 | { 62 | "cell_type": "code", 63 | "execution_count": 34, 64 | "metadata": {}, 65 | "outputs": [], 66 | "source": [ 67 | "def get_completion(prompt, model=\"gpt-3.5-turbo\"):\n", 68 | " messages = [{\"role\": \"user\", \"content\": prompt}]\n", 69 | " response = openai.ChatCompletion.create(\n", 70 | " model=model,\n", 71 | " messages=messages,\n", 72 | " temperature=0, \n", 73 | " )\n", 74 | " return response.choices[0].message[\"content\"]\n" 75 | ] 76 | }, 77 | { 78 | "cell_type": "code", 79 | "execution_count": 35, 80 | "metadata": {}, 81 | "outputs": [ 82 | { 83 | "data": { 84 | "text/plain": [ 85 | "'As an AI language model, I can tell you that the answer to 1+1 is 2.'" 86 | ] 87 | }, 88 | "execution_count": 35, 89 | "metadata": {}, 90 | "output_type": "execute_result" 91 | } 92 | ], 93 | "source": [ 94 | "get_completion(\"What is 1+1?\")" 95 | ] 96 | }, 97 | { 98 | "cell_type": "code", 99 | "execution_count": 36, 100 | "metadata": {}, 101 | "outputs": [], 102 | "source": [ 103 | "customer_email = \"\"\"\n", 104 | "Arrr, I be fuming that me blender lid \\\n", 105 | "flew off and splattered me kitchen walls \\\n", 106 | "with smoothie! And to make matters worse, \\\n", 107 | "the warranty don't cover the cost of \\\n", 108 | "cleaning up me kitchen. I need yer help \\\n", 109 | "right now, matey!\n", 110 | "\"\"\"" 111 | ] 112 | }, 113 | { 114 | "cell_type": "code", 115 | "execution_count": 37, 116 | "metadata": {}, 117 | "outputs": [], 118 | "source": [ 119 | "style = \"\"\"American English \\\n", 120 | "in a calm and respectful tone\n", 121 | "\"\"\"" 122 | ] 123 | }, 124 | { 125 | "cell_type": "code", 126 | "execution_count": 38, 127 | "metadata": {}, 128 | "outputs": [ 129 | { 130 | "name": "stdout", 131 | "output_type": "stream", 132 | "text": [ 133 | "Translate the text that is delimited by triple backticks \n", 134 | "into a style that is American English in a calm and respectful tone\n", 135 | ".\n", 136 | "text: ```\n", 137 | "Reach out to the delivery manager or Cisco contact you've working with to build this connection. to our knowledge we have no control over how attatch handles characters (greek letters in this case).\n", 138 | "Maybe they might have some workaround, but to our knowledge we have no control over how that thing works (platform limitation).\n", 139 | "```\n", 140 | "\n" 141 | ] 142 | } 143 | ], 144 | "source": [ 145 | "prompt = f\"\"\"Translate the text \\\n", 146 | "that is delimited by triple backticks \n", 147 | "into a style that is {style}.\n", 148 | "text: ```{customer_email}```\n", 149 | "\"\"\"\n", 150 | "\n", 151 | "print(prompt)" 152 | ] 153 | }, 154 | { 155 | "cell_type": "code", 156 | "execution_count": 39, 157 | "metadata": {}, 158 | "outputs": [], 159 | "source": [ 160 | "response = get_completion(prompt)" 161 | ] 162 | }, 163 | { 164 | "cell_type": "code", 165 | "execution_count": 40, 166 | "metadata": {}, 167 | "outputs": [ 168 | { 169 | "data": { 170 | "text/plain": [ 171 | "\"Please contact the delivery manager or your Cisco representative who has been assisting you with establishing this connection. As far as we know, we do not have any influence over how attatch handles characters, such as Greek letters in this instance. Perhaps they may have a solution, but to our understanding, we are limited by the platform's capabilities.\"" 172 | ] 173 | }, 174 | "execution_count": 40, 175 | "metadata": {}, 176 | "output_type": "execute_result" 177 | } 178 | ], 179 | "source": [ 180 | "response" 181 | ] 182 | }, 183 | { 184 | "attachments": {}, 185 | "cell_type": "markdown", 186 | "metadata": {}, 187 | "source": [ 188 | "## Chat API : LangChain\n", 189 | "\n", 190 | "Let's try how we can do the same using LangChain." 191 | ] 192 | }, 193 | { 194 | "cell_type": "code", 195 | "execution_count": 41, 196 | "metadata": {}, 197 | "outputs": [], 198 | "source": [ 199 | "#!pip install --upgrade langchain" 200 | ] 201 | }, 202 | { 203 | "attachments": {}, 204 | "cell_type": "markdown", 205 | "metadata": {}, 206 | "source": [ 207 | "### Model" 208 | ] 209 | }, 210 | { 211 | "cell_type": "code", 212 | "execution_count": 42, 213 | "metadata": {}, 214 | "outputs": [], 215 | "source": [ 216 | "from langchain.chat_models import ChatOpenAI" 217 | ] 218 | }, 219 | { 220 | "cell_type": "code", 221 | "execution_count": 43, 222 | "metadata": {}, 223 | "outputs": [ 224 | { 225 | "data": { 226 | "text/plain": [ 227 | "ChatOpenAI(verbose=False, callbacks=None, callback_manager=None, client=, model_name='gpt-3.5-turbo', temperature=0.0, model_kwargs={}, openai_api_key='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', openai_api_base='', openai_organization='', openai_proxy='', request_timeout=None, max_retries=6, streaming=False, n=1, max_tokens=None)" 228 | ] 229 | }, 230 | "execution_count": 43, 231 | "metadata": {}, 232 | "output_type": "execute_result" 233 | } 234 | ], 235 | "source": [ 236 | "# To control the randomness and creativity of the generated\n", 237 | "# text by an LLM, use temperature = 0.0\n", 238 | "chat = ChatOpenAI(temperature=0.0)\n", 239 | "chat" 240 | ] 241 | }, 242 | { 243 | "attachments": {}, 244 | "cell_type": "markdown", 245 | "metadata": {}, 246 | "source": [ 247 | "### Prompt template" 248 | ] 249 | }, 250 | { 251 | "cell_type": "code", 252 | "execution_count": 44, 253 | "metadata": {}, 254 | "outputs": [], 255 | "source": [ 256 | "template_string = \"\"\"Translate the text \\\n", 257 | "that is delimited by triple backticks \\\n", 258 | "into a style that is {style}. \\\n", 259 | "text: ```{text}```\n", 260 | "\"\"\"" 261 | ] 262 | }, 263 | { 264 | "cell_type": "code", 265 | "execution_count": 45, 266 | "metadata": {}, 267 | "outputs": [], 268 | "source": [ 269 | "from langchain.prompts import ChatPromptTemplate\n", 270 | "\n", 271 | "prompt_template = ChatPromptTemplate.from_template(template_string)\n" 272 | ] 273 | }, 274 | { 275 | "cell_type": "code", 276 | "execution_count": 46, 277 | "metadata": {}, 278 | "outputs": [ 279 | { 280 | "data": { 281 | "text/plain": [ 282 | "PromptTemplate(input_variables=['style', 'text'], output_parser=None, partial_variables={}, template='Translate the text that is delimited by triple backticks into a style that is {style}. text: ```{text}```\\n', template_format='f-string', validate_template=True)" 283 | ] 284 | }, 285 | "execution_count": 46, 286 | "metadata": {}, 287 | "output_type": "execute_result" 288 | } 289 | ], 290 | "source": [ 291 | "prompt_template.messages[0].prompt" 292 | ] 293 | }, 294 | { 295 | "cell_type": "code", 296 | "execution_count": 47, 297 | "metadata": {}, 298 | "outputs": [ 299 | { 300 | "data": { 301 | "text/plain": [ 302 | "['style', 'text']" 303 | ] 304 | }, 305 | "execution_count": 47, 306 | "metadata": {}, 307 | "output_type": "execute_result" 308 | } 309 | ], 310 | "source": [ 311 | "prompt_template.messages[0].prompt.input_variables" 312 | ] 313 | }, 314 | { 315 | "cell_type": "code", 316 | "execution_count": 48, 317 | "metadata": {}, 318 | "outputs": [], 319 | "source": [ 320 | "customer_style = \"\"\"American English \\\n", 321 | "in a calm and respectful tone\n", 322 | "\"\"\"" 323 | ] 324 | }, 325 | { 326 | "cell_type": "code", 327 | "execution_count": 49, 328 | "metadata": {}, 329 | "outputs": [], 330 | "source": [ 331 | "customer_email = \"\"\"\n", 332 | "Arrr, I be fuming that me blender lid \\\n", 333 | "flew off and splattered me kitchen walls \\\n", 334 | "with smoothie! And to make matters worse, \\\n", 335 | "the warranty don't cover the cost of \\\n", 336 | "cleaning up me kitchen. I need yer help \\\n", 337 | "right now, matey!\n", 338 | "\"\"\"" 339 | ] 340 | }, 341 | { 342 | "cell_type": "code", 343 | "execution_count": 50, 344 | "metadata": {}, 345 | "outputs": [], 346 | "source": [ 347 | "customer_messages = prompt_template.format_messages(\n", 348 | " style=customer_style,\n", 349 | " text=customer_email)" 350 | ] 351 | }, 352 | { 353 | "cell_type": "code", 354 | "execution_count": 51, 355 | "metadata": {}, 356 | "outputs": [ 357 | { 358 | "name": "stdout", 359 | "output_type": "stream", 360 | "text": [ 361 | "\n", 362 | "\n" 363 | ] 364 | } 365 | ], 366 | "source": [ 367 | "print(type(customer_messages))\n", 368 | "print(type(customer_messages[0]))" 369 | ] 370 | }, 371 | { 372 | "cell_type": "code", 373 | "execution_count": 52, 374 | "metadata": {}, 375 | "outputs": [ 376 | { 377 | "name": "stdout", 378 | "output_type": "stream", 379 | "text": [ 380 | "content=\"Translate the text that is delimited by triple backticks into a style that is American English in a calm and respectful tone\\n. text: ```\\nArrr, I be fuming that me blender lid flew off and splattered me kitchen walls with smoothie! And to make matters worse, the warranty don't cover the cost of cleaning up me kitchen. I need yer help right now, matey!\\n```\\n\" additional_kwargs={} example=False\n" 381 | ] 382 | } 383 | ], 384 | "source": [ 385 | "print(customer_messages[0])" 386 | ] 387 | }, 388 | { 389 | "cell_type": "code", 390 | "execution_count": 53, 391 | "metadata": {}, 392 | "outputs": [], 393 | "source": [ 394 | "# Call the LLM to translate to the style of the customer message\n", 395 | "customer_response = chat(customer_messages)" 396 | ] 397 | }, 398 | { 399 | "cell_type": "code", 400 | "execution_count": 54, 401 | "metadata": {}, 402 | "outputs": [ 403 | { 404 | "name": "stdout", 405 | "output_type": "stream", 406 | "text": [ 407 | "I'm really frustrated that my blender lid flew off and made a mess of my kitchen walls with smoothie. To add to my frustration, the warranty doesn't cover the cost of cleaning up my kitchen. Can you please help me out, friend?\n" 408 | ] 409 | } 410 | ], 411 | "source": [ 412 | "print(customer_response.content)" 413 | ] 414 | }, 415 | { 416 | "cell_type": "code", 417 | "execution_count": 55, 418 | "metadata": {}, 419 | "outputs": [], 420 | "source": [ 421 | "service_reply = \"\"\"Hey there customer, \\\n", 422 | "the warranty does not cover \\\n", 423 | "cleaning expenses for your kitchen \\\n", 424 | "because it's your fault that \\\n", 425 | "you misused your blender \\\n", 426 | "by forgetting to put the lid on before \\\n", 427 | "starting the blender. \\\n", 428 | "Tough luck! See ya!\n", 429 | "\"\"\"" 430 | ] 431 | }, 432 | { 433 | "cell_type": "code", 434 | "execution_count": 56, 435 | "metadata": {}, 436 | "outputs": [], 437 | "source": [ 438 | "service_style_pirate = \"\"\"\\\n", 439 | "a polite tone \\\n", 440 | "that speaks in Spanish\\\n", 441 | "\"\"\"" 442 | ] 443 | }, 444 | { 445 | "cell_type": "code", 446 | "execution_count": 57, 447 | "metadata": {}, 448 | "outputs": [ 449 | { 450 | "name": "stdout", 451 | "output_type": "stream", 452 | "text": [ 453 | "Translate the text that is delimited by triple backticks into a style that is a polite tone that speaks in Spanish. text: ```Hey there customer, the warranty does not cover cleaning expenses for your kitchen because it's your fault that you misused your blender by forgetting to put the lid on before starting the blender. Tough luck! See ya!\n", 454 | "```\n", 455 | "\n" 456 | ] 457 | } 458 | ], 459 | "source": [ 460 | "service_messages = prompt_template.format_messages(\n", 461 | " style=service_style_pirate,\n", 462 | " text=service_reply)\n", 463 | "\n", 464 | "print(service_messages[0].content)" 465 | ] 466 | }, 467 | { 468 | "cell_type": "code", 469 | "execution_count": 58, 470 | "metadata": {}, 471 | "outputs": [ 472 | { 473 | "name": "stderr", 474 | "output_type": "stream", 475 | "text": [ 476 | "Retrying langchain.chat_models.openai.ChatOpenAI.completion_with_retry.._completion_with_retry in 1.0 seconds as it raised RateLimitError: Rate limit reached for default-gpt-3.5-turbo in organization org-RTaSSDWLRLKfbx1k0mNjvZeD on requests per min. Limit: 3 / min. Please try again in 20s. Contact us through our help center at help.openai.com if you continue to have issues. Please add a payment method to your account to increase your rate limit. Visit https://platform.openai.com/account/billing to add a payment method..\n" 477 | ] 478 | }, 479 | { 480 | "name": "stderr", 481 | "output_type": "stream", 482 | "text": [ 483 | "Retrying langchain.chat_models.openai.ChatOpenAI.completion_with_retry.._completion_with_retry in 2.0 seconds as it raised RateLimitError: Rate limit reached for default-gpt-3.5-turbo in organization org-RTaSSDWLRLKfbx1k0mNjvZeD on requests per min. Limit: 3 / min. Please try again in 20s. Contact us through our help center at help.openai.com if you continue to have issues. Please add a payment method to your account to increase your rate limit. Visit https://platform.openai.com/account/billing to add a payment method..\n", 484 | "Retrying langchain.chat_models.openai.ChatOpenAI.completion_with_retry.._completion_with_retry in 4.0 seconds as it raised RateLimitError: Rate limit reached for default-gpt-3.5-turbo in organization org-RTaSSDWLRLKfbx1k0mNjvZeD on requests per min. Limit: 3 / min. Please try again in 20s. Contact us through our help center at help.openai.com if you continue to have issues. Please add a payment method to your account to increase your rate limit. Visit https://platform.openai.com/account/billing to add a payment method..\n", 485 | "Retrying langchain.chat_models.openai.ChatOpenAI.completion_with_retry.._completion_with_retry in 8.0 seconds as it raised RateLimitError: Rate limit reached for default-gpt-3.5-turbo in organization org-RTaSSDWLRLKfbx1k0mNjvZeD on requests per min. Limit: 3 / min. Please try again in 20s. Contact us through our help center at help.openai.com if you continue to have issues. Please add a payment method to your account to increase your rate limit. Visit https://platform.openai.com/account/billing to add a payment method..\n" 486 | ] 487 | }, 488 | { 489 | "name": "stdout", 490 | "output_type": "stream", 491 | "text": [ 492 | "Hola estimado cliente, lamentablemente la garantía no cubre los gastos de limpieza de su cocina debido a que fue su culpa haber utilizado incorrectamente la licuadora al olvidar poner la tapa antes de encenderla. Lamentamos las molestias. ¡Hasta pronto!\n" 493 | ] 494 | } 495 | ], 496 | "source": [ 497 | "service_response = chat(service_messages)\n", 498 | "print(service_response.content)" 499 | ] 500 | }, 501 | { 502 | "attachments": {}, 503 | "cell_type": "markdown", 504 | "metadata": {}, 505 | "source": [ 506 | "## Output Parsers\n", 507 | "\n", 508 | "Let's start with defining how we would like the LLM output to look like:" 509 | ] 510 | }, 511 | { 512 | "cell_type": "code", 513 | "execution_count": 59, 514 | "metadata": {}, 515 | "outputs": [ 516 | { 517 | "data": { 518 | "text/plain": [ 519 | "{'gift': False, 'delivery_days': 5, 'price_value': 'pretty affordable!'}" 520 | ] 521 | }, 522 | "execution_count": 59, 523 | "metadata": {}, 524 | "output_type": "execute_result" 525 | } 526 | ], 527 | "source": [ 528 | "{\n", 529 | " \"gift\": False,\n", 530 | " \"delivery_days\": 5,\n", 531 | " \"price_value\": \"pretty affordable!\"\n", 532 | "}" 533 | ] 534 | }, 535 | { 536 | "cell_type": "code", 537 | "execution_count": 60, 538 | "metadata": {}, 539 | "outputs": [], 540 | "source": [ 541 | "customer_review = \"\"\"\\\n", 542 | "This leaf blower is pretty amazing. It has four settings:\\\n", 543 | "candle blower, gentle breeze, windy city, and tornado. \\\n", 544 | "It arrived in two days, just in time for my wife's \\\n", 545 | "anniversary present. \\\n", 546 | "I think my wife liked it so much she was speechless. \\\n", 547 | "So far I've been the only one using it, and I've been \\\n", 548 | "using it every other morning to clear the leaves on our lawn. \\\n", 549 | "It's slightly more expensive than the other leaf blowers \\\n", 550 | "out there, but I think it's worth it for the extra features.\n", 551 | "\"\"\"\n", 552 | "\n", 553 | "review_template = \"\"\"\\\n", 554 | "For the following text, extract the following information:\n", 555 | "\n", 556 | "gift: Was the item purchased as a gift for someone else? \\\n", 557 | "Answer True if yes, False if not or unknown.\n", 558 | "\n", 559 | "delivery_days: How many days did it take for the product \\\n", 560 | "to arrive? If this information is not found, output -1.\n", 561 | "\n", 562 | "price_value: Extract any sentences about the value or price,\\\n", 563 | "and output them as a comma separated Python list.\n", 564 | "\n", 565 | "Format the output as JSON with the following keys:\n", 566 | "gift\n", 567 | "delivery_days\n", 568 | "price_value\n", 569 | "\n", 570 | "text: {text}\n", 571 | "\"\"\"" 572 | ] 573 | }, 574 | { 575 | "cell_type": "code", 576 | "execution_count": 61, 577 | "metadata": {}, 578 | "outputs": [ 579 | { 580 | "name": "stdout", 581 | "output_type": "stream", 582 | "text": [ 583 | "input_variables=['text'] output_parser=None partial_variables={} messages=[HumanMessagePromptTemplate(prompt=PromptTemplate(input_variables=['text'], output_parser=None, partial_variables={}, template='For the following text, extract the following information:\\n\\ngift: Was the item purchased as a gift for someone else? Answer True if yes, False if not or unknown.\\n\\ndelivery_days: How many days did it take for the product to arrive? If this information is not found, output -1.\\n\\nprice_value: Extract any sentences about the value or price,and output them as a comma separated Python list.\\n\\nFormat the output as JSON with the following keys:\\ngift\\ndelivery_days\\nprice_value\\n\\ntext: {text}\\n', template_format='f-string', validate_template=True), additional_kwargs={})]\n" 584 | ] 585 | } 586 | ], 587 | "source": [ 588 | "from langchain.prompts import ChatPromptTemplate\n", 589 | "\n", 590 | "prompt_template = ChatPromptTemplate.from_template(review_template)\n", 591 | "print(prompt_template)" 592 | ] 593 | }, 594 | { 595 | "cell_type": "code", 596 | "execution_count": 62, 597 | "metadata": {}, 598 | "outputs": [ 599 | { 600 | "name": "stderr", 601 | "output_type": "stream", 602 | "text": [ 603 | "Retrying langchain.chat_models.openai.ChatOpenAI.completion_with_retry.._completion_with_retry in 1.0 seconds as it raised RateLimitError: Rate limit reached for default-gpt-3.5-turbo in organization org-RTaSSDWLRLKfbx1k0mNjvZeD on requests per min. Limit: 3 / min. Please try again in 20s. Contact us through our help center at help.openai.com if you continue to have issues. Please add a payment method to your account to increase your rate limit. Visit https://platform.openai.com/account/billing to add a payment method..\n", 604 | "Retrying langchain.chat_models.openai.ChatOpenAI.completion_with_retry.._completion_with_retry in 2.0 seconds as it raised RateLimitError: Rate limit reached for default-gpt-3.5-turbo in organization org-RTaSSDWLRLKfbx1k0mNjvZeD on requests per min. Limit: 3 / min. Please try again in 20s. Contact us through our help center at help.openai.com if you continue to have issues. Please add a payment method to your account to increase your rate limit. Visit https://platform.openai.com/account/billing to add a payment method..\n", 605 | "Retrying langchain.chat_models.openai.ChatOpenAI.completion_with_retry.._completion_with_retry in 4.0 seconds as it raised RateLimitError: Rate limit reached for default-gpt-3.5-turbo in organization org-RTaSSDWLRLKfbx1k0mNjvZeD on requests per min. Limit: 3 / min. Please try again in 20s. Contact us through our help center at help.openai.com if you continue to have issues. Please add a payment method to your account to increase your rate limit. Visit https://platform.openai.com/account/billing to add a payment method..\n", 606 | "Retrying langchain.chat_models.openai.ChatOpenAI.completion_with_retry.._completion_with_retry in 8.0 seconds as it raised RateLimitError: Rate limit reached for default-gpt-3.5-turbo in organization org-RTaSSDWLRLKfbx1k0mNjvZeD on requests per min. Limit: 3 / min. Please try again in 20s. Contact us through our help center at help.openai.com if you continue to have issues. Please add a payment method to your account to increase your rate limit. Visit https://platform.openai.com/account/billing to add a payment method..\n" 607 | ] 608 | }, 609 | { 610 | "name": "stdout", 611 | "output_type": "stream", 612 | "text": [ 613 | "{\n", 614 | " \"gift\": true,\n", 615 | " \"delivery_days\": 2,\n", 616 | " \"price_value\": [\"It's slightly more expensive than the other leaf blowers out there, but I think it's worth it for the extra features.\"]\n", 617 | "}\n" 618 | ] 619 | } 620 | ], 621 | "source": [ 622 | "messages = prompt_template.format_messages(text=customer_review)\n", 623 | "chat = ChatOpenAI(temperature=0.0)\n", 624 | "response = chat(messages)\n", 625 | "print(response.content)\n" 626 | ] 627 | }, 628 | { 629 | "cell_type": "code", 630 | "execution_count": 63, 631 | "metadata": {}, 632 | "outputs": [ 633 | { 634 | "data": { 635 | "text/plain": [ 636 | "str" 637 | ] 638 | }, 639 | "execution_count": 63, 640 | "metadata": {}, 641 | "output_type": "execute_result" 642 | } 643 | ], 644 | "source": [ 645 | "type(response.content)" 646 | ] 647 | }, 648 | { 649 | "cell_type": "code", 650 | "execution_count": 64, 651 | "metadata": {}, 652 | "outputs": [ 653 | { 654 | "ename": "AttributeError", 655 | "evalue": "'str' object has no attribute 'get'", 656 | "output_type": "error", 657 | "traceback": [ 658 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", 659 | "\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)", 660 | "Cell \u001b[0;32mIn[64], line 4\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[39m# You will get an error by running this line of code \u001b[39;00m\n\u001b[1;32m 2\u001b[0m \u001b[39m# because'gift' is not a dictionary\u001b[39;00m\n\u001b[1;32m 3\u001b[0m \u001b[39m# 'gift' is a string\u001b[39;00m\n\u001b[0;32m----> 4\u001b[0m response\u001b[39m.\u001b[39;49mcontent\u001b[39m.\u001b[39;49mget(\u001b[39m'\u001b[39m\u001b[39mgift\u001b[39m\u001b[39m'\u001b[39m)\n", 661 | "\u001b[0;31mAttributeError\u001b[0m: 'str' object has no attribute 'get'" 662 | ] 663 | } 664 | ], 665 | "source": [ 666 | "# You will get an error by running this line of code \n", 667 | "# because'gift' is not a dictionary\n", 668 | "# 'gift' is a string\n", 669 | "response.content.get('gift')" 670 | ] 671 | }, 672 | { 673 | "attachments": {}, 674 | "cell_type": "markdown", 675 | "metadata": {}, 676 | "source": [ 677 | "### Parse the LLM output string into a Python dictionary" 678 | ] 679 | }, 680 | { 681 | "cell_type": "code", 682 | "execution_count": null, 683 | "metadata": {}, 684 | "outputs": [], 685 | "source": [ 686 | "from langchain.output_parsers import ResponseSchema\n", 687 | "from langchain.output_parsers import StructuredOutputParser" 688 | ] 689 | }, 690 | { 691 | "cell_type": "code", 692 | "execution_count": null, 693 | "metadata": {}, 694 | "outputs": [], 695 | "source": [ 696 | "gift_schema = ResponseSchema(name=\"gift\",\n", 697 | " description=\"Was the item purchased\\\n", 698 | " as a gift for someone else? \\\n", 699 | " Answer True if yes,\\\n", 700 | " False if not or unknown.\")\n", 701 | "delivery_days_schema = ResponseSchema(name=\"delivery_days\",\n", 702 | " description=\"How many days\\\n", 703 | " did it take for the product\\\n", 704 | " to arrive? If this \\\n", 705 | " information is not found,\\\n", 706 | " output -1.\")\n", 707 | "price_value_schema = ResponseSchema(name=\"price_value\",\n", 708 | " description=\"Extract any\\\n", 709 | " sentences about the value or \\\n", 710 | " price, and output them as a \\\n", 711 | " comma separated Python list.\")\n", 712 | "\n", 713 | "response_schemas = [gift_schema, \n", 714 | " delivery_days_schema,\n", 715 | " price_value_schema]" 716 | ] 717 | }, 718 | { 719 | "cell_type": "code", 720 | "execution_count": null, 721 | "metadata": {}, 722 | "outputs": [], 723 | "source": [ 724 | "output_parser = StructuredOutputParser.from_response_schemas(response_schemas)" 725 | ] 726 | }, 727 | { 728 | "cell_type": "code", 729 | "execution_count": null, 730 | "metadata": {}, 731 | "outputs": [], 732 | "source": [ 733 | "format_instructions = output_parser.get_format_instructions()\n" 734 | ] 735 | }, 736 | { 737 | "cell_type": "code", 738 | "execution_count": null, 739 | "metadata": {}, 740 | "outputs": [ 741 | { 742 | "name": "stdout", 743 | "output_type": "stream", 744 | "text": [ 745 | "The output should be a markdown code snippet formatted in the following schema, including the leading and trailing \"```json\" and \"```\":\n", 746 | "\n", 747 | "```json\n", 748 | "{\n", 749 | "\t\"gift\": string // Was the item purchased as a gift for someone else? Answer True if yes, False if not or unknown.\n", 750 | "\t\"delivery_days\": string // How many days did it take for the product to arrive? If this information is not found, output -1.\n", 751 | "\t\"price_value\": string // Extract any sentences about the value or price, and output them as a comma separated Python list.\n", 752 | "}\n", 753 | "```\n" 754 | ] 755 | } 756 | ], 757 | "source": [ 758 | "print(format_instructions)" 759 | ] 760 | }, 761 | { 762 | "cell_type": "code", 763 | "execution_count": null, 764 | "metadata": {}, 765 | "outputs": [], 766 | "source": [ 767 | "review_template_2 = \"\"\"\\\n", 768 | "For the following text, extract the following information:\n", 769 | "\n", 770 | "gift: Was the item purchased as a gift for someone else? \\\n", 771 | "Answer True if yes, False if not or unknown.\n", 772 | "\n", 773 | "delivery_days: How many days did it take for the product\\\n", 774 | "to arrive? If this information is not found, output -1.\n", 775 | "\n", 776 | "price_value: Extract any sentences about the value or price,\\\n", 777 | "and output them as a comma separated Python list.\n", 778 | "\n", 779 | "text: {text}\n", 780 | "\n", 781 | "{format_instructions}\n", 782 | "\"\"\"\n", 783 | "\n", 784 | "prompt = ChatPromptTemplate.from_template(template=review_template_2)\n", 785 | "\n", 786 | "messages = prompt.format_messages(text=customer_review, \n", 787 | " format_instructions=format_instructions)" 788 | ] 789 | }, 790 | { 791 | "cell_type": "code", 792 | "execution_count": null, 793 | "metadata": {}, 794 | "outputs": [ 795 | { 796 | "name": "stdout", 797 | "output_type": "stream", 798 | "text": [ 799 | "For the following text, extract the following information:\n", 800 | "\n", 801 | "gift: Was the item purchased as a gift for someone else? Answer True if yes, False if not or unknown.\n", 802 | "\n", 803 | "delivery_days: How many days did it take for the product to arrive? If this information is not found, output -1.\n", 804 | "\n", 805 | "price_value: Extract any sentences about the value or price,and output them as a comma separated Python list.\n", 806 | "\n", 807 | "Format the output as JSON with the following keys:\n", 808 | "gift\n", 809 | "delivery_days\n", 810 | "price_value\n", 811 | "\n", 812 | "text: This leaf blower is pretty amazing. It has four settings:candle blower, gentle breeze, windy city, and tornado. It arrived in two days, just in time for my wife's anniversary present. I think my wife liked it so much she was speechless. So far I've been the only one using it, and I've been using it every other morning to clear the leaves on our lawn. It's slightly more expensive than the other leaf blowers out there, but I think it's worth it for the extra features.\n", 813 | "\n", 814 | "\n" 815 | ] 816 | } 817 | ], 818 | "source": [ 819 | "print(messages[0].content)" 820 | ] 821 | }, 822 | { 823 | "cell_type": "code", 824 | "execution_count": null, 825 | "metadata": {}, 826 | "outputs": [], 827 | "source": [ 828 | "response = chat(messages)" 829 | ] 830 | }, 831 | { 832 | "cell_type": "code", 833 | "execution_count": null, 834 | "metadata": {}, 835 | "outputs": [ 836 | { 837 | "name": "stdout", 838 | "output_type": "stream", 839 | "text": [ 840 | "{\n", 841 | " \"gift\": true,\n", 842 | " \"delivery_days\": 2,\n", 843 | " \"price_value\": [\"It's slightly more expensive than the other leaf blowers out there, but I think it's worth it for the extra features.\"]\n", 844 | "}\n" 845 | ] 846 | } 847 | ], 848 | "source": [ 849 | "print(response.content)" 850 | ] 851 | }, 852 | { 853 | "cell_type": "code", 854 | "execution_count": null, 855 | "metadata": {}, 856 | "outputs": [], 857 | "source": [ 858 | "output_dict = output_parser.parse(response.content)" 859 | ] 860 | }, 861 | { 862 | "cell_type": "code", 863 | "execution_count": null, 864 | "metadata": {}, 865 | "outputs": [ 866 | { 867 | "data": { 868 | "text/plain": [ 869 | "{'gift': True,\n", 870 | " 'delivery_days': 2,\n", 871 | " 'price_value': [\"It's slightly more expensive than the other leaf blowers out there, but I think it's worth it for the extra features.\"]}" 872 | ] 873 | }, 874 | "execution_count": 21, 875 | "metadata": {}, 876 | "output_type": "execute_result" 877 | } 878 | ], 879 | "source": [ 880 | "output_dict" 881 | ] 882 | }, 883 | { 884 | "cell_type": "code", 885 | "execution_count": null, 886 | "metadata": {}, 887 | "outputs": [ 888 | { 889 | "data": { 890 | "text/plain": [ 891 | "dict" 892 | ] 893 | }, 894 | "execution_count": 22, 895 | "metadata": {}, 896 | "output_type": "execute_result" 897 | } 898 | ], 899 | "source": [ 900 | "type(output_dict)" 901 | ] 902 | }, 903 | { 904 | "cell_type": "code", 905 | "execution_count": null, 906 | "metadata": {}, 907 | "outputs": [ 908 | { 909 | "data": { 910 | "text/plain": [ 911 | "2" 912 | ] 913 | }, 914 | "execution_count": 23, 915 | "metadata": {}, 916 | "output_type": "execute_result" 917 | } 918 | ], 919 | "source": [ 920 | "output_dict.get('delivery_days')" 921 | ] 922 | }, 923 | { 924 | "cell_type": "code", 925 | "execution_count": null, 926 | "metadata": {}, 927 | "outputs": [], 928 | "source": [] 929 | } 930 | ], 931 | "metadata": { 932 | "kernelspec": { 933 | "display_name": "Python 3", 934 | "language": "python", 935 | "name": "python3" 936 | }, 937 | "language_info": { 938 | "codemirror_mode": { 939 | "name": "ipython", 940 | "version": 3 941 | }, 942 | "file_extension": ".py", 943 | "mimetype": "text/x-python", 944 | "name": "python", 945 | "nbconvert_exporter": "python", 946 | "pygments_lexer": "ipython3", 947 | "version": "3.10.1" 948 | }, 949 | "orig_nbformat": 4 950 | }, 951 | "nbformat": 4, 952 | "nbformat_minor": 2 953 | } 954 | -------------------------------------------------------------------------------- /L2-memory.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "attachments": {}, 5 | "cell_type": "markdown", 6 | "metadata": {}, 7 | "source": [ 8 | "# LangChain: Memory\n", 9 | "\n", 10 | "## Outline\n", 11 | "* ConversationBufferMemory\n", 12 | "* ConversationBufferWindowMemory\n", 13 | "* ConversationTokenBufferMemory\n", 14 | "* ConversationSummaryMemory" 15 | ] 16 | }, 17 | { 18 | "attachments": {}, 19 | "cell_type": "markdown", 20 | "metadata": {}, 21 | "source": [ 22 | "## ConversationBufferMemory" 23 | ] 24 | }, 25 | { 26 | "cell_type": "code", 27 | "execution_count": 2, 28 | "metadata": {}, 29 | "outputs": [], 30 | "source": [ 31 | "import os\n", 32 | "\n", 33 | "from dotenv import load_dotenv, find_dotenv\n", 34 | "_ = load_dotenv(find_dotenv()) # read local .env file\n", 35 | "\n", 36 | "import warnings\n", 37 | "warnings.filterwarnings('ignore')" 38 | ] 39 | }, 40 | { 41 | "cell_type": "code", 42 | "execution_count": 3, 43 | "metadata": {}, 44 | "outputs": [], 45 | "source": [ 46 | "from langchain.chat_models import ChatOpenAI\n", 47 | "from langchain.chains import ConversationChain\n", 48 | "from langchain.memory import ConversationBufferMemory\n" 49 | ] 50 | }, 51 | { 52 | "cell_type": "code", 53 | "execution_count": 4, 54 | "metadata": {}, 55 | "outputs": [], 56 | "source": [ 57 | "llm = ChatOpenAI(temperature=0.0)\n", 58 | "memory = ConversationBufferMemory()\n", 59 | "conversation = ConversationChain(\n", 60 | " llm=llm, \n", 61 | " memory = memory,\n", 62 | " verbose=True\n", 63 | ")" 64 | ] 65 | }, 66 | { 67 | "cell_type": "code", 68 | "execution_count": 5, 69 | "metadata": {}, 70 | "outputs": [ 71 | { 72 | "name": "stdout", 73 | "output_type": "stream", 74 | "text": [ 75 | "\n", 76 | "\n", 77 | "\u001b[1m> Entering new ConversationChain chain...\u001b[0m\n", 78 | "Prompt after formatting:\n", 79 | "\u001b[32;1m\u001b[1;3mThe following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\n", 80 | "\n", 81 | "Current conversation:\n", 82 | "\n", 83 | "Human: Hi, my name is Andrew\n", 84 | "AI:\u001b[0m\n", 85 | "\n", 86 | "\u001b[1m> Finished chain.\u001b[0m\n" 87 | ] 88 | }, 89 | { 90 | "data": { 91 | "text/plain": [ 92 | "\"Hello Andrew, it's nice to meet you. My name is AI. How can I assist you today?\"" 93 | ] 94 | }, 95 | "execution_count": 5, 96 | "metadata": {}, 97 | "output_type": "execute_result" 98 | } 99 | ], 100 | "source": [ 101 | "conversation.predict(input=\"Hi, my name is Andrew\")" 102 | ] 103 | }, 104 | { 105 | "cell_type": "code", 106 | "execution_count": 6, 107 | "metadata": {}, 108 | "outputs": [ 109 | { 110 | "name": "stdout", 111 | "output_type": "stream", 112 | "text": [ 113 | "\n", 114 | "\n", 115 | "\u001b[1m> Entering new ConversationChain chain...\u001b[0m\n", 116 | "Prompt after formatting:\n", 117 | "\u001b[32;1m\u001b[1;3mThe following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\n", 118 | "\n", 119 | "Current conversation:\n", 120 | "Human: Hi, my name is Andrew\n", 121 | "AI: Hello Andrew, it's nice to meet you. My name is AI. How can I assist you today?\n", 122 | "Human: What is 1+1?\n", 123 | "AI:\u001b[0m\n", 124 | "\n", 125 | "\u001b[1m> Finished chain.\u001b[0m\n" 126 | ] 127 | }, 128 | { 129 | "data": { 130 | "text/plain": [ 131 | "'The answer to 1+1 is 2.'" 132 | ] 133 | }, 134 | "execution_count": 6, 135 | "metadata": {}, 136 | "output_type": "execute_result" 137 | } 138 | ], 139 | "source": [ 140 | "conversation.predict(input=\"What is 1+1?\")" 141 | ] 142 | }, 143 | { 144 | "cell_type": "code", 145 | "execution_count": 7, 146 | "metadata": {}, 147 | "outputs": [ 148 | { 149 | "name": "stdout", 150 | "output_type": "stream", 151 | "text": [ 152 | "\n", 153 | "\n", 154 | "\u001b[1m> Entering new ConversationChain chain...\u001b[0m\n", 155 | "Prompt after formatting:\n", 156 | "\u001b[32;1m\u001b[1;3mThe following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\n", 157 | "\n", 158 | "Current conversation:\n", 159 | "Human: Hi, my name is Andrew\n", 160 | "AI: Hello Andrew, it's nice to meet you. My name is AI. How can I assist you today?\n", 161 | "Human: What is 1+1?\n", 162 | "AI: The answer to 1+1 is 2.\n", 163 | "Human: What is my name?\n", 164 | "AI:\u001b[0m\n", 165 | "\n", 166 | "\u001b[1m> Finished chain.\u001b[0m\n" 167 | ] 168 | }, 169 | { 170 | "data": { 171 | "text/plain": [ 172 | "'Your name is Andrew, as you mentioned earlier.'" 173 | ] 174 | }, 175 | "execution_count": 7, 176 | "metadata": {}, 177 | "output_type": "execute_result" 178 | } 179 | ], 180 | "source": [ 181 | "conversation.predict(input=\"What is my name?\")" 182 | ] 183 | }, 184 | { 185 | "cell_type": "code", 186 | "execution_count": 8, 187 | "metadata": {}, 188 | "outputs": [ 189 | { 190 | "name": "stdout", 191 | "output_type": "stream", 192 | "text": [ 193 | "Human: Hi, my name is Andrew\n", 194 | "AI: Hello Andrew, it's nice to meet you. My name is AI. How can I assist you today?\n", 195 | "Human: What is 1+1?\n", 196 | "AI: The answer to 1+1 is 2.\n", 197 | "Human: What is my name?\n", 198 | "AI: Your name is Andrew, as you mentioned earlier.\n" 199 | ] 200 | } 201 | ], 202 | "source": [ 203 | "print(memory.buffer)" 204 | ] 205 | }, 206 | { 207 | "cell_type": "code", 208 | "execution_count": 9, 209 | "metadata": {}, 210 | "outputs": [ 211 | { 212 | "data": { 213 | "text/plain": [ 214 | "{'history': \"Human: Hi, my name is Andrew\\nAI: Hello Andrew, it's nice to meet you. My name is AI. How can I assist you today?\\nHuman: What is 1+1?\\nAI: The answer to 1+1 is 2.\\nHuman: What is my name?\\nAI: Your name is Andrew, as you mentioned earlier.\"}" 215 | ] 216 | }, 217 | "execution_count": 9, 218 | "metadata": {}, 219 | "output_type": "execute_result" 220 | } 221 | ], 222 | "source": [ 223 | "memory.load_memory_variables({})" 224 | ] 225 | }, 226 | { 227 | "cell_type": "code", 228 | "execution_count": 10, 229 | "metadata": {}, 230 | "outputs": [], 231 | "source": [ 232 | "memory = ConversationBufferMemory()" 233 | ] 234 | }, 235 | { 236 | "cell_type": "code", 237 | "execution_count": 11, 238 | "metadata": {}, 239 | "outputs": [], 240 | "source": [ 241 | "memory.save_context({\"input\": \"Hi\"}, \n", 242 | " {\"output\": \"What's up\"})" 243 | ] 244 | }, 245 | { 246 | "cell_type": "code", 247 | "execution_count": 12, 248 | "metadata": {}, 249 | "outputs": [ 250 | { 251 | "name": "stdout", 252 | "output_type": "stream", 253 | "text": [ 254 | "Human: Hi\n", 255 | "AI: What's up\n" 256 | ] 257 | } 258 | ], 259 | "source": [ 260 | "print(memory.buffer)" 261 | ] 262 | }, 263 | { 264 | "cell_type": "code", 265 | "execution_count": 13, 266 | "metadata": {}, 267 | "outputs": [ 268 | { 269 | "data": { 270 | "text/plain": [ 271 | "{'history': \"Human: Hi\\nAI: What's up\"}" 272 | ] 273 | }, 274 | "execution_count": 13, 275 | "metadata": {}, 276 | "output_type": "execute_result" 277 | } 278 | ], 279 | "source": [ 280 | "memory.load_memory_variables({})" 281 | ] 282 | }, 283 | { 284 | "cell_type": "code", 285 | "execution_count": 14, 286 | "metadata": {}, 287 | "outputs": [], 288 | "source": [ 289 | "memory.save_context({\"input\": \"Not much, just hanging\"}, \n", 290 | " {\"output\": \"Cool\"})" 291 | ] 292 | }, 293 | { 294 | "cell_type": "code", 295 | "execution_count": 15, 296 | "metadata": {}, 297 | "outputs": [ 298 | { 299 | "data": { 300 | "text/plain": [ 301 | "{'history': \"Human: Hi\\nAI: What's up\\nHuman: Not much, just hanging\\nAI: Cool\"}" 302 | ] 303 | }, 304 | "execution_count": 15, 305 | "metadata": {}, 306 | "output_type": "execute_result" 307 | } 308 | ], 309 | "source": [ 310 | "memory.load_memory_variables({})" 311 | ] 312 | }, 313 | { 314 | "attachments": {}, 315 | "cell_type": "markdown", 316 | "metadata": {}, 317 | "source": [ 318 | "## ConversationBufferWindowMemory" 319 | ] 320 | }, 321 | { 322 | "cell_type": "code", 323 | "execution_count": 16, 324 | "metadata": {}, 325 | "outputs": [], 326 | "source": [ 327 | "from langchain.memory import ConversationBufferWindowMemory" 328 | ] 329 | }, 330 | { 331 | "cell_type": "code", 332 | "execution_count": 17, 333 | "metadata": {}, 334 | "outputs": [], 335 | "source": [ 336 | "memory = ConversationBufferWindowMemory(k=1) " 337 | ] 338 | }, 339 | { 340 | "cell_type": "code", 341 | "execution_count": 18, 342 | "metadata": {}, 343 | "outputs": [], 344 | "source": [ 345 | "memory.save_context({\"input\": \"Hi\"},\n", 346 | " {\"output\": \"What's up\"})\n", 347 | "memory.save_context({\"input\": \"Not much, just hanging\"},\n", 348 | " {\"output\": \"Cool\"})\n" 349 | ] 350 | }, 351 | { 352 | "cell_type": "code", 353 | "execution_count": 19, 354 | "metadata": {}, 355 | "outputs": [ 356 | { 357 | "data": { 358 | "text/plain": [ 359 | "{'history': 'Human: Not much, just hanging\\nAI: Cool'}" 360 | ] 361 | }, 362 | "execution_count": 19, 363 | "metadata": {}, 364 | "output_type": "execute_result" 365 | } 366 | ], 367 | "source": [ 368 | "memory.load_memory_variables({})" 369 | ] 370 | }, 371 | { 372 | "cell_type": "code", 373 | "execution_count": 20, 374 | "metadata": {}, 375 | "outputs": [], 376 | "source": [ 377 | "llm = ChatOpenAI(temperature=0.0)\n", 378 | "memory = ConversationBufferWindowMemory(k=1)\n", 379 | "conversation = ConversationChain(\n", 380 | " llm=llm, \n", 381 | " memory = memory,\n", 382 | " verbose=False\n", 383 | ")" 384 | ] 385 | }, 386 | { 387 | "cell_type": "code", 388 | "execution_count": 21, 389 | "metadata": {}, 390 | "outputs": [ 391 | { 392 | "data": { 393 | "text/plain": [ 394 | "\"Hello Andrew, it's nice to meet you. My name is AI. How can I assist you today?\"" 395 | ] 396 | }, 397 | "execution_count": 21, 398 | "metadata": {}, 399 | "output_type": "execute_result" 400 | } 401 | ], 402 | "source": [ 403 | "conversation.predict(input=\"Hi, my name is Andrew\")" 404 | ] 405 | }, 406 | { 407 | "cell_type": "code", 408 | "execution_count": 22, 409 | "metadata": {}, 410 | "outputs": [ 411 | { 412 | "data": { 413 | "text/plain": [ 414 | "'The answer to 1+1 is 2.'" 415 | ] 416 | }, 417 | "execution_count": 22, 418 | "metadata": {}, 419 | "output_type": "execute_result" 420 | } 421 | ], 422 | "source": [ 423 | "conversation.predict(input=\"What is 1+1?\")" 424 | ] 425 | }, 426 | { 427 | "cell_type": "code", 428 | "execution_count": 23, 429 | "metadata": {}, 430 | "outputs": [ 431 | { 432 | "data": { 433 | "text/plain": [ 434 | "\"I'm sorry, I don't have access to that information. Could you please tell me your name?\"" 435 | ] 436 | }, 437 | "execution_count": 23, 438 | "metadata": {}, 439 | "output_type": "execute_result" 440 | } 441 | ], 442 | "source": [ 443 | "conversation.predict(input=\"What is my name?\")" 444 | ] 445 | }, 446 | { 447 | "attachments": {}, 448 | "cell_type": "markdown", 449 | "metadata": {}, 450 | "source": [ 451 | "## ConversationTokenBufferMemory" 452 | ] 453 | }, 454 | { 455 | "cell_type": "code", 456 | "execution_count": 24, 457 | "metadata": {}, 458 | "outputs": [], 459 | "source": [ 460 | "#!pip install tiktoken" 461 | ] 462 | }, 463 | { 464 | "cell_type": "code", 465 | "execution_count": 28, 466 | "metadata": {}, 467 | "outputs": [], 468 | "source": [ 469 | "from langchain.memory import ConversationTokenBufferMemory\n", 470 | "from langchain.llms import OpenAI\n", 471 | "llm = ChatOpenAI(temperature=0.0)" 472 | ] 473 | }, 474 | { 475 | "cell_type": "code", 476 | "execution_count": 29, 477 | "metadata": {}, 478 | "outputs": [], 479 | "source": [ 480 | "memory = ConversationTokenBufferMemory(llm=llm, max_token_limit=30)\n", 481 | "memory.save_context({\"input\": \"AI is what?!\"},\n", 482 | " {\"output\": \"Amazing!\"})\n", 483 | "memory.save_context({\"input\": \"Backpropagation is what?\"},\n", 484 | " {\"output\": \"Beautiful!\"})\n", 485 | "memory.save_context({\"input\": \"Chatbots are what?\"}, \n", 486 | " {\"output\": \"Charming!\"})" 487 | ] 488 | }, 489 | { 490 | "cell_type": "code", 491 | "execution_count": 30, 492 | "metadata": {}, 493 | "outputs": [ 494 | { 495 | "data": { 496 | "text/plain": [ 497 | "{'history': 'AI: Beautiful!\\nHuman: Chatbots are what?\\nAI: Charming!'}" 498 | ] 499 | }, 500 | "execution_count": 30, 501 | "metadata": {}, 502 | "output_type": "execute_result" 503 | } 504 | ], 505 | "source": [ 506 | "memory.load_memory_variables({})" 507 | ] 508 | }, 509 | { 510 | "attachments": {}, 511 | "cell_type": "markdown", 512 | "metadata": {}, 513 | "source": [ 514 | "## ConversationSummaryMemory" 515 | ] 516 | }, 517 | { 518 | "cell_type": "code", 519 | "execution_count": 31, 520 | "metadata": {}, 521 | "outputs": [], 522 | "source": [ 523 | "from langchain.memory import ConversationSummaryBufferMemory\n" 524 | ] 525 | }, 526 | { 527 | "cell_type": "code", 528 | "execution_count": 32, 529 | "metadata": {}, 530 | "outputs": [], 531 | "source": [ 532 | "# create a long string\n", 533 | "schedule = \"There is a meeting at 8am with your product team. \\\n", 534 | "You will need your powerpoint presentation prepared. \\\n", 535 | "9am-12pm have time to work on your LangChain \\\n", 536 | "project which will go quickly because Langchain is such a powerful tool. \\\n", 537 | "At Noon, lunch at the italian resturant with a customer who is driving \\\n", 538 | "from over an hour away to meet you to understand the latest in AI. \\\n", 539 | "Be sure to bring your laptop to show the latest LLM demo.\"\n", 540 | "\n", 541 | "memory = ConversationSummaryBufferMemory(llm=llm, max_token_limit=100)\n", 542 | "memory.save_context({\"input\": \"Hello\"}, {\"output\": \"What's up\"})\n", 543 | "memory.save_context({\"input\": \"Not much, just hanging\"},\n", 544 | " {\"output\": \"Cool\"})\n", 545 | "memory.save_context({\"input\": \"What is on the schedule today?\"}, \n", 546 | " {\"output\": f\"{schedule}\"})" 547 | ] 548 | }, 549 | { 550 | "cell_type": "code", 551 | "execution_count": 33, 552 | "metadata": {}, 553 | "outputs": [ 554 | { 555 | "data": { 556 | "text/plain": [ 557 | "{'history': \"System: The human and AI engage in small talk before discussing the day's schedule. The AI informs the human of a morning meeting with the product team, time to work on the LangChain project, and a lunch meeting with a customer interested in the latest AI developments.\"}" 558 | ] 559 | }, 560 | "execution_count": 33, 561 | "metadata": {}, 562 | "output_type": "execute_result" 563 | } 564 | ], 565 | "source": [ 566 | "memory.load_memory_variables({})" 567 | ] 568 | }, 569 | { 570 | "cell_type": "code", 571 | "execution_count": 34, 572 | "metadata": {}, 573 | "outputs": [], 574 | "source": [ 575 | "conversation = ConversationChain(\n", 576 | " llm=llm, \n", 577 | " memory = memory,\n", 578 | " verbose=True\n", 579 | ")" 580 | ] 581 | }, 582 | { 583 | "cell_type": "code", 584 | "execution_count": 35, 585 | "metadata": {}, 586 | "outputs": [ 587 | { 588 | "name": "stdout", 589 | "output_type": "stream", 590 | "text": [ 591 | "\n", 592 | "\n", 593 | "\u001b[1m> Entering new ConversationChain chain...\u001b[0m\n", 594 | "Prompt after formatting:\n", 595 | "\u001b[32;1m\u001b[1;3mThe following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\n", 596 | "\n", 597 | "Current conversation:\n", 598 | "System: The human and AI engage in small talk before discussing the day's schedule. The AI informs the human of a morning meeting with the product team, time to work on the LangChain project, and a lunch meeting with a customer interested in the latest AI developments.\n", 599 | "Human: What would be a good demo to show?\n", 600 | "AI:\u001b[0m\n", 601 | "\n", 602 | "\u001b[1m> Finished chain.\u001b[0m\n" 603 | ] 604 | }, 605 | { 606 | "data": { 607 | "text/plain": [ 608 | "\"Based on the customer's interest in AI developments, I would suggest showcasing our latest natural language processing capabilities. We could demonstrate how our AI can understand and respond to complex language queries, and even provide personalized recommendations based on the user's preferences. Additionally, we could highlight our machine learning algorithms and how they continuously improve the accuracy and efficiency of our AI. Would you like me to prepare a demo for the meeting?\"" 609 | ] 610 | }, 611 | "execution_count": 35, 612 | "metadata": {}, 613 | "output_type": "execute_result" 614 | } 615 | ], 616 | "source": [ 617 | "conversation.predict(input=\"What would be a good demo to show?\")" 618 | ] 619 | }, 620 | { 621 | "cell_type": "code", 622 | "execution_count": null, 623 | "metadata": {}, 624 | "outputs": [], 625 | "source": [] 626 | } 627 | ], 628 | "metadata": { 629 | "kernelspec": { 630 | "display_name": "Python 3", 631 | "language": "python", 632 | "name": "python3" 633 | }, 634 | "language_info": { 635 | "codemirror_mode": { 636 | "name": "ipython", 637 | "version": 3 638 | }, 639 | "file_extension": ".py", 640 | "mimetype": "text/x-python", 641 | "name": "python", 642 | "nbconvert_exporter": "python", 643 | "pygments_lexer": "ipython3", 644 | "version": "3.10.1" 645 | }, 646 | "orig_nbformat": 4 647 | }, 648 | "nbformat": 4, 649 | "nbformat_minor": 2 650 | } 651 | -------------------------------------------------------------------------------- /L3-chains.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "attachments": {}, 5 | "cell_type": "markdown", 6 | "metadata": {}, 7 | "source": [ 8 | "# Chains in LangChain\n", 9 | "\n", 10 | "## Outline\n", 11 | "\n", 12 | "* LLMChain\n", 13 | "* Sequential Chains\n", 14 | " * SimpleSequentialChain\n", 15 | " * SequentialChain\n", 16 | "* Router Chain" 17 | ] 18 | }, 19 | { 20 | "cell_type": "code", 21 | "execution_count": 5, 22 | "metadata": {}, 23 | "outputs": [], 24 | "source": [ 25 | "import warnings\n", 26 | "warnings.filterwarnings('ignore')" 27 | ] 28 | }, 29 | { 30 | "cell_type": "code", 31 | "execution_count": 6, 32 | "metadata": {}, 33 | "outputs": [], 34 | "source": [ 35 | "import os\n", 36 | "\n", 37 | "from dotenv import load_dotenv, find_dotenv\n", 38 | "_ = load_dotenv(find_dotenv()) # read local .env file" 39 | ] 40 | }, 41 | { 42 | "cell_type": "code", 43 | "execution_count": 7, 44 | "metadata": {}, 45 | "outputs": [], 46 | "source": [ 47 | "#!pip install pandas" 48 | ] 49 | }, 50 | { 51 | "cell_type": "code", 52 | "execution_count": 10, 53 | "metadata": {}, 54 | "outputs": [], 55 | "source": [ 56 | "import pandas as pd\n", 57 | "df = pd.read_csv('data.csv',delimiter=';')" 58 | ] 59 | }, 60 | { 61 | "cell_type": "code", 62 | "execution_count": 11, 63 | "metadata": {}, 64 | "outputs": [ 65 | { 66 | "data": { 67 | "text/html": [ 68 | "
\n", 69 | "\n", 82 | "\n", 83 | " \n", 84 | " \n", 85 | " \n", 86 | " \n", 87 | " \n", 88 | " \n", 89 | " \n", 90 | " \n", 91 | " \n", 92 | " \n", 93 | " \n", 94 | " \n", 95 | " \n", 96 | " \n", 97 | " \n", 98 | " \n", 99 | " \n", 100 | " \n", 101 | " \n", 102 | " \n", 103 | " \n", 104 | " \n", 105 | " \n", 106 | " \n", 107 | " \n", 108 | " \n", 109 | " \n", 110 | " \n", 111 | " \n", 112 | "
ProductReview
0Amazon Kindle E-Reader 6\" Wifi (8th Generation...I thought it would be as big as small paper bu...
1Amazon Kindle E-Reader 6\" Wifi (8th Generation...This kindle is light and easy to use especiall...
2Amazon Kindle E-Reader 6\" Wifi (8th Generation...Didnt know how much i'd use a kindle so went f...
3Amazon Kindle E-Reader 6\" Wifi (8th Generation...I am 100 happy with my purchase. I caught it o...
\n", 113 | "
" 114 | ], 115 | "text/plain": [ 116 | " Product \\\n", 117 | "0 Amazon Kindle E-Reader 6\" Wifi (8th Generation... \n", 118 | "1 Amazon Kindle E-Reader 6\" Wifi (8th Generation... \n", 119 | "2 Amazon Kindle E-Reader 6\" Wifi (8th Generation... \n", 120 | "3 Amazon Kindle E-Reader 6\" Wifi (8th Generation... \n", 121 | "\n", 122 | " Review \n", 123 | "0 I thought it would be as big as small paper bu... \n", 124 | "1 This kindle is light and easy to use especiall... \n", 125 | "2 Didnt know how much i'd use a kindle so went f... \n", 126 | "3 I am 100 happy with my purchase. I caught it o... " 127 | ] 128 | }, 129 | "execution_count": 11, 130 | "metadata": {}, 131 | "output_type": "execute_result" 132 | } 133 | ], 134 | "source": [ 135 | "df.head()" 136 | ] 137 | }, 138 | { 139 | "attachments": {}, 140 | "cell_type": "markdown", 141 | "metadata": {}, 142 | "source": [ 143 | "## LLMChain" 144 | ] 145 | }, 146 | { 147 | "cell_type": "code", 148 | "execution_count": 12, 149 | "metadata": {}, 150 | "outputs": [], 151 | "source": [ 152 | "from langchain.chat_models import ChatOpenAI\n", 153 | "from langchain.prompts import ChatPromptTemplate\n", 154 | "from langchain.chains import LLMChain" 155 | ] 156 | }, 157 | { 158 | "cell_type": "code", 159 | "execution_count": 13, 160 | "metadata": {}, 161 | "outputs": [], 162 | "source": [ 163 | "llm = ChatOpenAI(temperature=0.9)\n" 164 | ] 165 | }, 166 | { 167 | "cell_type": "code", 168 | "execution_count": 14, 169 | "metadata": {}, 170 | "outputs": [], 171 | "source": [ 172 | "prompt = ChatPromptTemplate.from_template(\n", 173 | " \"What is the best name to describe \\\n", 174 | " a company that makes {product}?\"\n", 175 | ")" 176 | ] 177 | }, 178 | { 179 | "cell_type": "code", 180 | "execution_count": 15, 181 | "metadata": {}, 182 | "outputs": [], 183 | "source": [ 184 | "\n", 185 | "chain = LLMChain(llm=llm, prompt=prompt)" 186 | ] 187 | }, 188 | { 189 | "cell_type": "code", 190 | "execution_count": 16, 191 | "metadata": {}, 192 | "outputs": [ 193 | { 194 | "data": { 195 | "text/plain": [ 196 | "'KindleGenius'" 197 | ] 198 | }, 199 | "execution_count": 16, 200 | "metadata": {}, 201 | "output_type": "execute_result" 202 | } 203 | ], 204 | "source": [ 205 | "product = \"Amazon Kindle\"\n", 206 | "chain.run(product)" 207 | ] 208 | }, 209 | { 210 | "attachments": {}, 211 | "cell_type": "markdown", 212 | "metadata": {}, 213 | "source": [ 214 | "## SimpleSequentialChain" 215 | ] 216 | }, 217 | { 218 | "cell_type": "code", 219 | "execution_count": 17, 220 | "metadata": {}, 221 | "outputs": [], 222 | "source": [ 223 | "from langchain.chains import SimpleSequentialChain" 224 | ] 225 | }, 226 | { 227 | "cell_type": "code", 228 | "execution_count": 18, 229 | "metadata": {}, 230 | "outputs": [], 231 | "source": [ 232 | "llm = ChatOpenAI(temperature=0.9)\n", 233 | "\n", 234 | "# prompt template 1\n", 235 | "first_prompt = ChatPromptTemplate.from_template(\n", 236 | " \"What is the best name to describe \\\n", 237 | " a company that makes {product}?\"\n", 238 | ")\n", 239 | "\n", 240 | "# Chain 1\n", 241 | "chain_one = LLMChain(llm=llm, prompt=first_prompt)" 242 | ] 243 | }, 244 | { 245 | "cell_type": "code", 246 | "execution_count": 19, 247 | "metadata": {}, 248 | "outputs": [], 249 | "source": [ 250 | "\n", 251 | "# prompt template 2\n", 252 | "second_prompt = ChatPromptTemplate.from_template(\n", 253 | " \"Write a 20 words description for the following \\\n", 254 | " company:{company_name}\"\n", 255 | ")\n", 256 | "# chain 2\n", 257 | "chain_two = LLMChain(llm=llm, prompt=second_prompt)" 258 | ] 259 | }, 260 | { 261 | "cell_type": "code", 262 | "execution_count": 20, 263 | "metadata": {}, 264 | "outputs": [], 265 | "source": [ 266 | "overall_simple_chain = SimpleSequentialChain(chains=[chain_one, chain_two],\n", 267 | " verbose=True\n", 268 | " )" 269 | ] 270 | }, 271 | { 272 | "cell_type": "code", 273 | "execution_count": 21, 274 | "metadata": {}, 275 | "outputs": [ 276 | { 277 | "name": "stdout", 278 | "output_type": "stream", 279 | "text": [ 280 | "\n", 281 | "\n", 282 | "\u001b[1m> Entering new SimpleSequentialChain chain...\u001b[0m\n", 283 | "\u001b[36;1m\u001b[1;3m\"KindleWorks\" or \"eReaderTech\" would be suitable names to describe a company that makes Amazon Kindle.\u001b[0m\n", 284 | "\u001b[33;1m\u001b[1;3m\"KindleWorks: A leading e-reader manufacturer designing and producing high-quality Amazon Kindle devices for an exceptional reading experience.\"\u001b[0m\n", 285 | "\n", 286 | "\u001b[1m> Finished chain.\u001b[0m\n" 287 | ] 288 | }, 289 | { 290 | "data": { 291 | "text/plain": [ 292 | "'\"KindleWorks: A leading e-reader manufacturer designing and producing high-quality Amazon Kindle devices for an exceptional reading experience.\"'" 293 | ] 294 | }, 295 | "execution_count": 21, 296 | "metadata": {}, 297 | "output_type": "execute_result" 298 | } 299 | ], 300 | "source": [ 301 | "overall_simple_chain.run(product)" 302 | ] 303 | }, 304 | { 305 | "attachments": {}, 306 | "cell_type": "markdown", 307 | "metadata": {}, 308 | "source": [ 309 | "## SequentialChain" 310 | ] 311 | }, 312 | { 313 | "cell_type": "code", 314 | "execution_count": 22, 315 | "metadata": {}, 316 | "outputs": [], 317 | "source": [ 318 | "from langchain.chains import SequentialChain" 319 | ] 320 | }, 321 | { 322 | "cell_type": "code", 323 | "execution_count": 23, 324 | "metadata": {}, 325 | "outputs": [], 326 | "source": [ 327 | "llm = ChatOpenAI(temperature=0.9)\n", 328 | "\n", 329 | "# prompt template 1: translate to english\n", 330 | "first_prompt = ChatPromptTemplate.from_template(\n", 331 | " \"Translate the following review to english:\"\n", 332 | " \"\\n\\n{Review}\"\n", 333 | ")\n", 334 | "# chain 1: input= Review and output= English_Review\n", 335 | "chain_one = LLMChain(llm=llm, prompt=first_prompt, \n", 336 | " output_key=\"English_Review\"\n", 337 | " )\n" 338 | ] 339 | }, 340 | { 341 | "cell_type": "code", 342 | "execution_count": 24, 343 | "metadata": {}, 344 | "outputs": [], 345 | "source": [ 346 | "second_prompt = ChatPromptTemplate.from_template(\n", 347 | " \"Can you summarize the following review in 1 sentence:\"\n", 348 | " \"\\n\\n{English_Review}\"\n", 349 | ")\n", 350 | "# chain 2: input= English_Review and output= summary\n", 351 | "chain_two = LLMChain(llm=llm, prompt=second_prompt, \n", 352 | " output_key=\"summary\"\n", 353 | " )\n" 354 | ] 355 | }, 356 | { 357 | "cell_type": "code", 358 | "execution_count": 25, 359 | "metadata": {}, 360 | "outputs": [], 361 | "source": [ 362 | "# prompt template 3: translate to english\n", 363 | "third_prompt = ChatPromptTemplate.from_template(\n", 364 | " \"What language is the following review:\\n\\n{Review}\"\n", 365 | ")\n", 366 | "# chain 3: input= Review and output= language\n", 367 | "chain_three = LLMChain(llm=llm, prompt=third_prompt,\n", 368 | " output_key=\"language\"\n", 369 | " )\n" 370 | ] 371 | }, 372 | { 373 | "cell_type": "code", 374 | "execution_count": 26, 375 | "metadata": {}, 376 | "outputs": [], 377 | "source": [ 378 | "\n", 379 | "# prompt template 4: follow up message\n", 380 | "fourth_prompt = ChatPromptTemplate.from_template(\n", 381 | " \"Write a follow up response to the following \"\n", 382 | " \"summary in the specified language:\"\n", 383 | " \"\\n\\nSummary: {summary}\\n\\nLanguage: {language}\"\n", 384 | ")\n", 385 | "# chain 4: input= summary, language and output= followup_message\n", 386 | "chain_four = LLMChain(llm=llm, prompt=fourth_prompt,\n", 387 | " output_key=\"followup_message\"\n", 388 | " )\n" 389 | ] 390 | }, 391 | { 392 | "cell_type": "code", 393 | "execution_count": 27, 394 | "metadata": {}, 395 | "outputs": [], 396 | "source": [ 397 | "# overall_chain: input= Review \n", 398 | "# and output= English_Review,summary, followup_message\n", 399 | "overall_chain = SequentialChain(\n", 400 | " chains=[chain_one, chain_two, chain_three, chain_four],\n", 401 | " input_variables=[\"Review\"],\n", 402 | " output_variables=[\"English_Review\", \"summary\",\"followup_message\"],\n", 403 | " verbose=True\n", 404 | ")" 405 | ] 406 | }, 407 | { 408 | "cell_type": "code", 409 | "execution_count": 30, 410 | "metadata": {}, 411 | "outputs": [ 412 | { 413 | "name": "stdout", 414 | "output_type": "stream", 415 | "text": [ 416 | "\n", 417 | "\n", 418 | "\u001b[1m> Entering new SequentialChain chain...\u001b[0m\n" 419 | ] 420 | }, 421 | { 422 | "name": "stderr", 423 | "output_type": "stream", 424 | "text": [ 425 | "Retrying langchain.chat_models.openai.ChatOpenAI.completion_with_retry.._completion_with_retry in 1.0 seconds as it raised RateLimitError: Rate limit reached for default-gpt-3.5-turbo in organization org-RTaSSDWLRLKfbx1k0mNjvZeD on requests per min. Limit: 3 / min. Please try again in 20s. Contact us through our help center at help.openai.com if you continue to have issues. Please add a payment method to your account to increase your rate limit. Visit https://platform.openai.com/account/billing to add a payment method..\n", 426 | "Retrying langchain.chat_models.openai.ChatOpenAI.completion_with_retry.._completion_with_retry in 2.0 seconds as it raised RateLimitError: Rate limit reached for default-gpt-3.5-turbo in organization org-RTaSSDWLRLKfbx1k0mNjvZeD on requests per min. Limit: 3 / min. Please try again in 20s. Contact us through our help center at help.openai.com if you continue to have issues. Please add a payment method to your account to increase your rate limit. Visit https://platform.openai.com/account/billing to add a payment method..\n", 427 | "Retrying langchain.chat_models.openai.ChatOpenAI.completion_with_retry.._completion_with_retry in 4.0 seconds as it raised RateLimitError: Rate limit reached for default-gpt-3.5-turbo in organization org-RTaSSDWLRLKfbx1k0mNjvZeD on requests per min. Limit: 3 / min. Please try again in 20s. Contact us through our help center at help.openai.com if you continue to have issues. Please add a payment method to your account to increase your rate limit. Visit https://platform.openai.com/account/billing to add a payment method..\n", 428 | "Retrying langchain.chat_models.openai.ChatOpenAI.completion_with_retry.._completion_with_retry in 8.0 seconds as it raised RateLimitError: Rate limit reached for default-gpt-3.5-turbo in organization org-RTaSSDWLRLKfbx1k0mNjvZeD on requests per min. Limit: 3 / min. Please try again in 20s. Contact us through our help center at help.openai.com if you continue to have issues. Please add a payment method to your account to increase your rate limit. Visit https://platform.openai.com/account/billing to add a payment method..\n" 429 | ] 430 | }, 431 | { 432 | "name": "stdout", 433 | "output_type": "stream", 434 | "text": [ 435 | "\n", 436 | "\u001b[1m> Finished chain.\u001b[0m\n" 437 | ] 438 | }, 439 | { 440 | "data": { 441 | "text/plain": [ 442 | "{'Review': \"I am 100 happy with my purchase. I caught it on sale at a really good price. I am normally a real book person, but I have a 1 year old who loves ripping up pages. The Kindle prevents that, it's extremely portable (it fits better in my purse than a giant book), and I have it loaded with lots of books. I finish one and start another, without having to go store. It serves all my needs. I picked this one over the Paperwhite because the price was unbeatable and the only difference that I could see was this one wasn't backlit. A simple book light from the Dollar tree solves that issue. This is my second Kindle (the first being the old Keyboard model, which I put down because I fell out of love with the keyboard. Lol) and it most likely won't be my last.\",\n", 443 | " 'English_Review': \"I am 100% happy with my purchase. I managed to buy it at a really good price during a sale. I am usually a fan of physical books, but I have a one-year-old who loves tearing pages apart. The Kindle prevents that from happening, plus it's extremely portable (it fits better in my purse than a huge book) and I have loaded it with many books. I finish one and start another without having to go to a store. It fulfills all my needs. I chose this model over the Paperwhite because the price was unbeatable and the only difference I could see was that this one is not backlit. However, I solved that issue by using a simple book light from the Dollar tree. This is my second Kindle (the first one being the old Keyboard model, which I stopped using because I lost interest in the keyboard. Lol) and it probably won't be my last.\",\n", 444 | " 'summary': 'The reviewer is extremely satisfied with their purchase of a Kindle due to its affordability, portability, and ability to prevent their one-year-old from tearing pages, and they have found a solution to the lack of backlight by using a book light.',\n", 445 | " 'followup_message': \"Thank you for your positive review of the Kindle! We are delighted to hear that you are extremely satisfied with your purchase. We understand the importance of affordability, portability, and durability, and we are glad that the Kindle meets your expectations in these areas.\\n\\nIt's fantastic that the Kindle helps prevent your one-year-old from tearing pages. We designed it with durability in mind to withstand even the most curious little hands. We hope it continues to be a great solution for you and your child.\\n\\nRegarding the lack of backlight, we appreciate your resourcefulness in finding a solution by using a book light. While the Kindle does not have a built-in backlight, the addition of a book light is indeed a great way to enjoy your reading in low-light conditions. We'll make sure to pass on your feedback regarding this feature to our team for future consideration.\\n\\nThank you once again for your positive feedback and for choosing the Kindle. If you have any further questions or require any assistance, please don't hesitate to reach out. Happy reading!\"}" 446 | ] 447 | }, 448 | "execution_count": 30, 449 | "metadata": {}, 450 | "output_type": "execute_result" 451 | } 452 | ], 453 | "source": [ 454 | "review = df.Review[3]\n", 455 | "overall_chain(review)" 456 | ] 457 | }, 458 | { 459 | "attachments": {}, 460 | "cell_type": "markdown", 461 | "metadata": {}, 462 | "source": [ 463 | "## Router Chain" 464 | ] 465 | }, 466 | { 467 | "cell_type": "code", 468 | "execution_count": 31, 469 | "metadata": {}, 470 | "outputs": [], 471 | "source": [ 472 | "physics_template = \"\"\"You are a very smart physics professor. \\\n", 473 | "You are great at answering questions about physics in a concise\\\n", 474 | "and easy to understand manner. \\\n", 475 | "When you don't know the answer to a question you admit\\\n", 476 | "that you don't know.\n", 477 | "\n", 478 | "Here is a question:\n", 479 | "{input}\"\"\"\n", 480 | "\n", 481 | "\n", 482 | "math_template = \"\"\"You are a very good mathematician. \\\n", 483 | "You are great at answering math questions. \\\n", 484 | "You are so good because you are able to break down \\\n", 485 | "hard problems into their component parts, \n", 486 | "answer the component parts, and then put them together\\\n", 487 | "to answer the broader question.\n", 488 | "\n", 489 | "Here is a question:\n", 490 | "{input}\"\"\"\n", 491 | "\n", 492 | "history_template = \"\"\"You are a very good historian. \\\n", 493 | "You have an excellent knowledge of and understanding of people,\\\n", 494 | "events and contexts from a range of historical periods. \\\n", 495 | "You have the ability to think, reflect, debate, discuss and \\\n", 496 | "evaluate the past. You have a respect for historical evidence\\\n", 497 | "and the ability to make use of it to support your explanations \\\n", 498 | "and judgements.\n", 499 | "\n", 500 | "Here is a question:\n", 501 | "{input}\"\"\"\n", 502 | "\n", 503 | "\n", 504 | "computerscience_template = \"\"\" You are a successful computer scientist.\\\n", 505 | "You have a passion for creativity, collaboration,\\\n", 506 | "forward-thinking, confidence, strong problem-solving capabilities,\\\n", 507 | "understanding of theories and algorithms, and excellent communication \\\n", 508 | "skills. You are great at answering coding questions. \\\n", 509 | "You are so good because you know how to solve a problem by \\\n", 510 | "describing the solution in imperative steps \\\n", 511 | "that a machine can easily interpret and you know how to \\\n", 512 | "choose a solution that has a good balance between \\\n", 513 | "time complexity and space complexity. \n", 514 | "\n", 515 | "Here is a question:\n", 516 | "{input}\"\"\"" 517 | ] 518 | }, 519 | { 520 | "cell_type": "code", 521 | "execution_count": 32, 522 | "metadata": {}, 523 | "outputs": [], 524 | "source": [ 525 | "prompt_infos = [\n", 526 | " {\n", 527 | " \"name\": \"physics\", \n", 528 | " \"description\": \"Good for answering questions about physics\", \n", 529 | " \"prompt_template\": physics_template\n", 530 | " },\n", 531 | " {\n", 532 | " \"name\": \"math\", \n", 533 | " \"description\": \"Good for answering math questions\", \n", 534 | " \"prompt_template\": math_template\n", 535 | " },\n", 536 | " {\n", 537 | " \"name\": \"History\", \n", 538 | " \"description\": \"Good for answering history questions\", \n", 539 | " \"prompt_template\": history_template\n", 540 | " },\n", 541 | " {\n", 542 | " \"name\": \"computer science\", \n", 543 | " \"description\": \"Good for answering computer science questions\", \n", 544 | " \"prompt_template\": computerscience_template\n", 545 | " }\n", 546 | "]" 547 | ] 548 | }, 549 | { 550 | "cell_type": "code", 551 | "execution_count": 33, 552 | "metadata": {}, 553 | "outputs": [], 554 | "source": [ 555 | "from langchain.chains.router import MultiPromptChain\n", 556 | "from langchain.chains.router.llm_router import LLMRouterChain,RouterOutputParser\n", 557 | "from langchain.prompts import PromptTemplate" 558 | ] 559 | }, 560 | { 561 | "cell_type": "code", 562 | "execution_count": 34, 563 | "metadata": {}, 564 | "outputs": [], 565 | "source": [ 566 | "llm = ChatOpenAI(temperature=0)" 567 | ] 568 | }, 569 | { 570 | "cell_type": "code", 571 | "execution_count": 35, 572 | "metadata": {}, 573 | "outputs": [], 574 | "source": [ 575 | "\n", 576 | "destination_chains = {}\n", 577 | "for p_info in prompt_infos:\n", 578 | " name = p_info[\"name\"]\n", 579 | " prompt_template = p_info[\"prompt_template\"]\n", 580 | " prompt = ChatPromptTemplate.from_template(template=prompt_template)\n", 581 | " chain = LLMChain(llm=llm, prompt=prompt)\n", 582 | " destination_chains[name] = chain \n", 583 | " \n", 584 | "destinations = [f\"{p['name']}: {p['description']}\" for p in prompt_infos]\n", 585 | "destinations_str = \"\\n\".join(destinations)" 586 | ] 587 | }, 588 | { 589 | "cell_type": "code", 590 | "execution_count": 36, 591 | "metadata": {}, 592 | "outputs": [], 593 | "source": [ 594 | "default_prompt = ChatPromptTemplate.from_template(\"{input}\")\n", 595 | "default_chain = LLMChain(llm=llm, prompt=default_prompt)" 596 | ] 597 | }, 598 | { 599 | "cell_type": "code", 600 | "execution_count": 37, 601 | "metadata": {}, 602 | "outputs": [], 603 | "source": [ 604 | "MULTI_PROMPT_ROUTER_TEMPLATE = \"\"\"Given a raw text input to a \\\n", 605 | "language model select the model prompt best suited for the input. \\\n", 606 | "You will be given the names of the available prompts and a \\\n", 607 | "description of what the prompt is best suited for. \\\n", 608 | "You may also revise the original input if you think that revising\\\n", 609 | "it will ultimately lead to a better response from the language model.\n", 610 | "\n", 611 | "<< FORMATTING >>\n", 612 | "Return a markdown code snippet with a JSON object formatted to look like:\n", 613 | "```json\n", 614 | "{{{{\n", 615 | " \"destination\": string \\ name of the prompt to use or \"DEFAULT\"\n", 616 | " \"next_inputs\": string \\ a potentially modified version of the original input\n", 617 | "}}}}\n", 618 | "```\n", 619 | "\n", 620 | "REMEMBER: \"destination\" MUST be one of the candidate prompt \\\n", 621 | "names specified below OR it can be \"DEFAULT\" if the input is not\\\n", 622 | "well suited for any of the candidate prompts.\n", 623 | "REMEMBER: \"next_inputs\" can just be the original input \\\n", 624 | "if you don't think any modifications are needed.\n", 625 | "\n", 626 | "<< CANDIDATE PROMPTS >>\n", 627 | "{destinations}\n", 628 | "\n", 629 | "<< INPUT >>\n", 630 | "{{input}}\n", 631 | "\n", 632 | "<< OUTPUT (remember to include the ```json)>>\"\"\"" 633 | ] 634 | }, 635 | { 636 | "cell_type": "code", 637 | "execution_count": 38, 638 | "metadata": {}, 639 | "outputs": [], 640 | "source": [ 641 | "router_template = MULTI_PROMPT_ROUTER_TEMPLATE.format(\n", 642 | " destinations=destinations_str\n", 643 | ")\n", 644 | "router_prompt = PromptTemplate(\n", 645 | " template=router_template,\n", 646 | " input_variables=[\"input\"],\n", 647 | " output_parser=RouterOutputParser(),\n", 648 | ")\n", 649 | "\n", 650 | "router_chain = LLMRouterChain.from_llm(llm, router_prompt)" 651 | ] 652 | }, 653 | { 654 | "cell_type": "code", 655 | "execution_count": 39, 656 | "metadata": {}, 657 | "outputs": [], 658 | "source": [ 659 | "chain = MultiPromptChain(router_chain=router_chain, \n", 660 | " destination_chains=destination_chains, \n", 661 | " default_chain=default_chain, verbose=True\n", 662 | " )" 663 | ] 664 | }, 665 | { 666 | "cell_type": "code", 667 | "execution_count": 40, 668 | "metadata": {}, 669 | "outputs": [ 670 | { 671 | "name": "stdout", 672 | "output_type": "stream", 673 | "text": [ 674 | "\n", 675 | "\n", 676 | "\u001b[1m> Entering new MultiPromptChain chain...\u001b[0m\n", 677 | "physics: {'input': 'What is black body radiation?'}\n", 678 | "\u001b[1m> Finished chain.\u001b[0m\n" 679 | ] 680 | }, 681 | { 682 | "data": { 683 | "text/plain": [ 684 | "'Black body radiation refers to the electromagnetic radiation emitted by an object that absorbs all incident radiation and reflects or transmits none. It is called \"black body\" because it absorbs all wavelengths of light, appearing black at room temperature. \\n\\nAccording to Planck\\'s law, black body radiation is characterized by a continuous spectrum of wavelengths and intensities, which depend on the temperature of the object. As the temperature increases, the peak intensity of the radiation shifts to shorter wavelengths, resulting in a change in color from red to orange, yellow, white, and eventually blue at very high temperatures.\\n\\nBlack body radiation is a fundamental concept in physics and has significant applications in various fields, including astrophysics, thermodynamics, and quantum mechanics. It played a crucial role in the development of quantum theory and understanding the behavior of light and matter.'" 685 | ] 686 | }, 687 | "execution_count": 40, 688 | "metadata": {}, 689 | "output_type": "execute_result" 690 | } 691 | ], 692 | "source": [ 693 | "chain.run(\"What is black body radiation?\")" 694 | ] 695 | }, 696 | { 697 | "cell_type": "code", 698 | "execution_count": 41, 699 | "metadata": {}, 700 | "outputs": [ 701 | { 702 | "name": "stdout", 703 | "output_type": "stream", 704 | "text": [ 705 | "\n", 706 | "\n", 707 | "\u001b[1m> Entering new MultiPromptChain chain...\u001b[0m\n" 708 | ] 709 | }, 710 | { 711 | "name": "stderr", 712 | "output_type": "stream", 713 | "text": [ 714 | "Retrying langchain.chat_models.openai.ChatOpenAI.completion_with_retry.._completion_with_retry in 1.0 seconds as it raised APIError: Bad gateway. {\"error\":{\"code\":502,\"message\":\"Bad gateway.\",\"param\":null,\"type\":\"cf_bad_gateway\"}} 502 {'error': {'code': 502, 'message': 'Bad gateway.', 'param': None, 'type': 'cf_bad_gateway'}} {'Date': 'Fri, 30 Jun 2023 19:10:18 GMT', 'Content-Type': 'application/json', 'Content-Length': '84', 'Connection': 'keep-alive', 'X-Frame-Options': 'SAMEORIGIN', 'Referrer-Policy': 'same-origin', 'Cache-Control': 'private, max-age=0, no-store, no-cache, must-revalidate, post-check=0, pre-check=0', 'Expires': 'Thu, 01 Jan 1970 00:00:01 GMT', 'Server': 'cloudflare', 'CF-RAY': '7df8adcaaf188275-IAD', 'alt-svc': 'h3=\":443\"; ma=86400'}.\n" 715 | ] 716 | }, 717 | { 718 | "name": "stdout", 719 | "output_type": "stream", 720 | "text": [ 721 | "math: {'input': 'what is 2 + 2'}\n", 722 | "\u001b[1m> Finished chain.\u001b[0m\n" 723 | ] 724 | }, 725 | { 726 | "data": { 727 | "text/plain": [ 728 | "'Thank you for your kind words! As a mathematician, I am happy to help with any math questions, no matter how simple or complex they may be.\\n\\nThe question you\\'ve asked is a basic addition problem: \"What is 2 + 2?\" To solve this, we can simply add the two numbers together:\\n\\n2 + 2 = 4\\n\\nTherefore, the answer to the question \"What is 2 + 2?\" is 4.'" 729 | ] 730 | }, 731 | "execution_count": 41, 732 | "metadata": {}, 733 | "output_type": "execute_result" 734 | } 735 | ], 736 | "source": [ 737 | "chain.run(\"what is 2 + 2\")" 738 | ] 739 | }, 740 | { 741 | "cell_type": "code", 742 | "execution_count": 42, 743 | "metadata": {}, 744 | "outputs": [ 745 | { 746 | "name": "stdout", 747 | "output_type": "stream", 748 | "text": [ 749 | "\n", 750 | "\n", 751 | "\u001b[1m> Entering new MultiPromptChain chain...\u001b[0m\n", 752 | "None: {'input': 'Why does every cell in our body contain DNA?'}\n", 753 | "\u001b[1m> Finished chain.\u001b[0m\n" 754 | ] 755 | }, 756 | { 757 | "data": { 758 | "text/plain": [ 759 | "'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 necessary for the synthesis of proteins, which are essential for the structure and function of cells. It serves as a blueprint for the production of specific proteins that determine the characteristics and traits of an organism. Additionally, DNA is responsible for the transmission of genetic information from one generation to the next during reproduction. Therefore, every cell in our body contains DNA to ensure the proper functioning and continuity of life.'" 760 | ] 761 | }, 762 | "execution_count": 42, 763 | "metadata": {}, 764 | "output_type": "execute_result" 765 | } 766 | ], 767 | "source": [ 768 | "chain.run(\"Why does every cell in our body contain DNA?\")" 769 | ] 770 | }, 771 | { 772 | "cell_type": "code", 773 | "execution_count": null, 774 | "metadata": {}, 775 | "outputs": [], 776 | "source": [] 777 | } 778 | ], 779 | "metadata": { 780 | "kernelspec": { 781 | "display_name": "Python 3", 782 | "language": "python", 783 | "name": "python3" 784 | }, 785 | "language_info": { 786 | "codemirror_mode": { 787 | "name": "ipython", 788 | "version": 3 789 | }, 790 | "file_extension": ".py", 791 | "mimetype": "text/x-python", 792 | "name": "python", 793 | "nbconvert_exporter": "python", 794 | "pygments_lexer": "ipython3", 795 | "version": "3.10.1" 796 | }, 797 | "orig_nbformat": 4 798 | }, 799 | "nbformat": 4, 800 | "nbformat_minor": 2 801 | } 802 | -------------------------------------------------------------------------------- /L4-QnA.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "attachments": {}, 5 | "cell_type": "markdown", 6 | "metadata": {}, 7 | "source": [ 8 | "# LangChain: Q&A over Documents\n", 9 | "\n", 10 | "An example might be a tool that would allow you to query a product catalog for items of interest." 11 | ] 12 | }, 13 | { 14 | "cell_type": "code", 15 | "execution_count": 8, 16 | "metadata": {}, 17 | "outputs": [], 18 | "source": [ 19 | "#pip install --upgrade langchain" 20 | ] 21 | }, 22 | { 23 | "cell_type": "code", 24 | "execution_count": 9, 25 | "metadata": {}, 26 | "outputs": [], 27 | "source": [ 28 | "import os\n", 29 | "\n", 30 | "from dotenv import load_dotenv, find_dotenv\n", 31 | "_ = load_dotenv(find_dotenv()) # read local .env file" 32 | ] 33 | }, 34 | { 35 | "cell_type": "code", 36 | "execution_count": 10, 37 | "metadata": {}, 38 | "outputs": [], 39 | "source": [ 40 | "from langchain.chains import RetrievalQA\n", 41 | "from langchain.chat_models import ChatOpenAI\n", 42 | "from langchain.document_loaders import CSVLoader\n", 43 | "from langchain.vectorstores import DocArrayInMemorySearch\n", 44 | "from IPython.display import display, Markdown" 45 | ] 46 | }, 47 | { 48 | "cell_type": "code", 49 | "execution_count": 15, 50 | "metadata": {}, 51 | "outputs": [], 52 | "source": [ 53 | "file = 'myntra_products_catalog.csv'\n", 54 | "loader = CSVLoader(file_path=file)" 55 | ] 56 | }, 57 | { 58 | "cell_type": "code", 59 | "execution_count": 16, 60 | "metadata": {}, 61 | "outputs": [], 62 | "source": [ 63 | "from langchain.indexes import VectorstoreIndexCreator" 64 | ] 65 | }, 66 | { 67 | "cell_type": "code", 68 | "execution_count": 17, 69 | "metadata": {}, 70 | "outputs": [], 71 | "source": [ 72 | "#pip install docarray" 73 | ] 74 | }, 75 | { 76 | "cell_type": "code", 77 | "execution_count": 18, 78 | "metadata": {}, 79 | "outputs": [], 80 | "source": [ 81 | "index = VectorstoreIndexCreator(\n", 82 | " vectorstore_cls=DocArrayInMemorySearch\n", 83 | ").from_loaders([loader])" 84 | ] 85 | }, 86 | { 87 | "cell_type": "code", 88 | "execution_count": 19, 89 | "metadata": {}, 90 | "outputs": [], 91 | "source": [ 92 | "import pandas as pd" 93 | ] 94 | }, 95 | { 96 | "cell_type": "code", 97 | "execution_count": 20, 98 | "metadata": {}, 99 | "outputs": [], 100 | "source": [ 101 | "df = pd.read_csv('myntra_products_catalog.csv')" 102 | ] 103 | }, 104 | { 105 | "cell_type": "code", 106 | "execution_count": 21, 107 | "metadata": {}, 108 | "outputs": [ 109 | { 110 | "data": { 111 | "text/html": [ 112 | "
\n", 113 | "\n", 126 | "\n", 127 | " \n", 128 | " \n", 129 | " \n", 130 | " \n", 131 | " \n", 132 | " \n", 133 | " \n", 134 | " \n", 135 | " \n", 136 | " \n", 137 | " \n", 138 | " \n", 139 | " \n", 140 | " \n", 141 | " \n", 142 | " \n", 143 | " \n", 144 | " \n", 145 | " \n", 146 | " \n", 147 | " \n", 148 | " \n", 149 | " \n", 150 | " \n", 151 | " \n", 152 | " \n", 153 | " \n", 154 | " \n", 155 | " \n", 156 | " \n", 157 | " \n", 158 | " \n", 159 | " \n", 160 | " \n", 161 | " \n", 162 | " \n", 163 | " \n", 164 | " \n", 165 | " \n", 166 | " \n", 167 | " \n", 168 | " \n", 169 | " \n", 170 | " \n", 171 | " \n", 172 | " \n", 173 | " \n", 174 | " \n", 175 | " \n", 176 | " \n", 177 | " \n", 178 | " \n", 179 | " \n", 180 | " \n", 181 | " \n", 182 | " \n", 183 | " \n", 184 | " \n", 185 | " \n", 186 | " \n", 187 | " \n", 188 | " \n", 189 | " \n", 190 | " \n", 191 | " \n", 192 | " \n", 193 | " \n", 194 | " \n", 195 | " \n", 196 | " \n", 197 | "
ProductIDProductNameProductBrandGenderPrice (INR)NumImagesDescriptionPrimaryColor
010017413DKNY Unisex Black & Grey Printed Medium Trolle...DKNYUnisex117457Black and grey printed medium trolley bag, sec...Black
110016283EthnoVogue Women Beige & Grey Made to Measure ...EthnoVogueWomen58107Beige & Grey made to measure kurta with churid...Beige
210009781SPYKAR Women Pink Alexa Super Skinny Fit High-...SPYKARWomen8997Pink coloured wash 5-pocket high-rise cropped ...Pink
310015921Raymond Men Blue Self-Design Single-Breasted B...RaymondMen55995Blue self-design bandhgala suitBlue self-desig...Blue
410017833Parx Men Brown & Off-White Slim Fit Printed Ca...ParxMen7595Brown and off-white printed casual shirt, has ...White
\n", 198 | "
" 199 | ], 200 | "text/plain": [ 201 | " ProductID ProductName ProductBrand \\\n", 202 | "0 10017413 DKNY Unisex Black & Grey Printed Medium Trolle... DKNY \n", 203 | "1 10016283 EthnoVogue Women Beige & Grey Made to Measure ... EthnoVogue \n", 204 | "2 10009781 SPYKAR Women Pink Alexa Super Skinny Fit High-... SPYKAR \n", 205 | "3 10015921 Raymond Men Blue Self-Design Single-Breasted B... Raymond \n", 206 | "4 10017833 Parx Men Brown & Off-White Slim Fit Printed Ca... Parx \n", 207 | "\n", 208 | " Gender Price (INR) NumImages \\\n", 209 | "0 Unisex 11745 7 \n", 210 | "1 Women 5810 7 \n", 211 | "2 Women 899 7 \n", 212 | "3 Men 5599 5 \n", 213 | "4 Men 759 5 \n", 214 | "\n", 215 | " Description PrimaryColor \n", 216 | "0 Black and grey printed medium trolley bag, sec... Black \n", 217 | "1 Beige & Grey made to measure kurta with churid... Beige \n", 218 | "2 Pink coloured wash 5-pocket high-rise cropped ... Pink \n", 219 | "3 Blue self-design bandhgala suitBlue self-desig... Blue \n", 220 | "4 Brown and off-white printed casual shirt, has ... White " 221 | ] 222 | }, 223 | "execution_count": 21, 224 | "metadata": {}, 225 | "output_type": "execute_result" 226 | } 227 | ], 228 | "source": [ 229 | "df.head()" 230 | ] 231 | }, 232 | { 233 | "cell_type": "code", 234 | "execution_count": 22, 235 | "metadata": {}, 236 | "outputs": [ 237 | { 238 | "data": { 239 | "text/plain": [ 240 | "Index(['ProductID', 'ProductName', 'ProductBrand', 'Gender', 'Price (INR)',\n", 241 | " 'NumImages', 'Description', 'PrimaryColor'],\n", 242 | " dtype='object')" 243 | ] 244 | }, 245 | "execution_count": 22, 246 | "metadata": {}, 247 | "output_type": "execute_result" 248 | } 249 | ], 250 | "source": [ 251 | "df.columns" 252 | ] 253 | }, 254 | { 255 | "cell_type": "code", 256 | "execution_count": 23, 257 | "metadata": {}, 258 | "outputs": [ 259 | { 260 | "data": { 261 | "text/plain": [ 262 | "ProductID int64\n", 263 | "ProductName object\n", 264 | "ProductBrand object\n", 265 | "Gender object\n", 266 | "Price (INR) int64\n", 267 | "NumImages int64\n", 268 | "Description object\n", 269 | "PrimaryColor object\n", 270 | "dtype: object" 271 | ] 272 | }, 273 | "execution_count": 23, 274 | "metadata": {}, 275 | "output_type": "execute_result" 276 | } 277 | ], 278 | "source": [ 279 | "df.dtypes" 280 | ] 281 | }, 282 | { 283 | "cell_type": "code", 284 | "execution_count": 24, 285 | "metadata": {}, 286 | "outputs": [ 287 | { 288 | "data": { 289 | "text/plain": [ 290 | "(12491, 8)" 291 | ] 292 | }, 293 | "execution_count": 24, 294 | "metadata": {}, 295 | "output_type": "execute_result" 296 | } 297 | ], 298 | "source": [ 299 | "df.shape" 300 | ] 301 | }, 302 | { 303 | "cell_type": "code", 304 | "execution_count": 26, 305 | "metadata": {}, 306 | "outputs": [ 307 | { 308 | "data": { 309 | "text/plain": [ 310 | "(11597, 8)" 311 | ] 312 | }, 313 | "execution_count": 26, 314 | "metadata": {}, 315 | "output_type": "execute_result" 316 | } 317 | ], 318 | "source": [ 319 | "df = df.dropna()\n", 320 | "df.shape" 321 | ] 322 | }, 323 | { 324 | "cell_type": "code", 325 | "execution_count": 27, 326 | "metadata": {}, 327 | "outputs": [ 328 | { 329 | "data": { 330 | "text/html": [ 331 | "
\n", 332 | "\n", 345 | "\n", 346 | " \n", 347 | " \n", 348 | " \n", 349 | " \n", 350 | " \n", 351 | " \n", 352 | " \n", 353 | " \n", 354 | " \n", 355 | " \n", 356 | " \n", 357 | " \n", 358 | " \n", 359 | " \n", 360 | " \n", 361 | " \n", 362 | " \n", 363 | " \n", 364 | " \n", 365 | " \n", 366 | " \n", 367 | " \n", 368 | " \n", 369 | " \n", 370 | " \n", 371 | " \n", 372 | " \n", 373 | " \n", 374 | " \n", 375 | " \n", 376 | " \n", 377 | " \n", 378 | " \n", 379 | " \n", 380 | " \n", 381 | " \n", 382 | " \n", 383 | " \n", 384 | " \n", 385 | " \n", 386 | " \n", 387 | " \n", 388 | " \n", 389 | " \n", 390 | " \n", 391 | " \n", 392 | " \n", 393 | " \n", 394 | "
countmeanstdmin25%50%75%max
ProductID11597.09.962030e+061.297211e+06101206.010063875.010155387.010215659.010275139.0
Price (INR)11597.01.460913e+032.159003e+03153.0649.0939.01499.063090.0
NumImages11597.04.967319e+001.063547e+001.05.05.05.010.0
\n", 395 | "
" 396 | ], 397 | "text/plain": [ 398 | " count mean std min 25% \\\n", 399 | "ProductID 11597.0 9.962030e+06 1.297211e+06 101206.0 10063875.0 \n", 400 | "Price (INR) 11597.0 1.460913e+03 2.159003e+03 153.0 649.0 \n", 401 | "NumImages 11597.0 4.967319e+00 1.063547e+00 1.0 5.0 \n", 402 | "\n", 403 | " 50% 75% max \n", 404 | "ProductID 10155387.0 10215659.0 10275139.0 \n", 405 | "Price (INR) 939.0 1499.0 63090.0 \n", 406 | "NumImages 5.0 5.0 10.0 " 407 | ] 408 | }, 409 | "execution_count": 27, 410 | "metadata": {}, 411 | "output_type": "execute_result" 412 | } 413 | ], 414 | "source": [ 415 | "df.describe().transpose()" 416 | ] 417 | }, 418 | { 419 | "cell_type": "code", 420 | "execution_count": 28, 421 | "metadata": {}, 422 | "outputs": [ 423 | { 424 | "data": { 425 | "text/plain": [ 426 | "0 Black and grey printed medium trolley bag, sec...\n", 427 | "1 Beige & Grey made to measure kurta with churid...\n", 428 | "2 Pink coloured wash 5-pocket high-rise cropped ...\n", 429 | "3 Blue self-design bandhgala suitBlue self-desig...\n", 430 | "4 Brown and off-white printed casual shirt, has ...\n", 431 | " ... \n", 432 | "12485 Black lace full-coverage Bralette bra Lightly ...\n", 433 | "12486 Black dark wash 5-pocket low-rise jeans, clean...\n", 434 | "12487 A pair of gold-toned open toe heels, has regul...\n", 435 | "12488 Navy Blue and White printed mid-rise denim sho...\n", 436 | "12490 Black and grey striped T-shirt, has a polo col...\n", 437 | "Name: Description, Length: 11597, dtype: object" 438 | ] 439 | }, 440 | "execution_count": 28, 441 | "metadata": {}, 442 | "output_type": "execute_result" 443 | } 444 | ], 445 | "source": [ 446 | "df['Description']" 447 | ] 448 | }, 449 | { 450 | "cell_type": "code", 451 | "execution_count": 29, 452 | "metadata": {}, 453 | "outputs": [], 454 | "source": [ 455 | "query =\"Please list all your shirts with sun protection \\\n", 456 | "in a table in markdown and summarize each one.\"" 457 | ] 458 | }, 459 | { 460 | "cell_type": "code", 461 | "execution_count": 30, 462 | "metadata": {}, 463 | "outputs": [], 464 | "source": [ 465 | "response = index.query(query)" 466 | ] 467 | }, 468 | { 469 | "cell_type": "code", 470 | "execution_count": 31, 471 | "metadata": {}, 472 | "outputs": [ 473 | { 474 | "data": { 475 | "text/markdown": [ 476 | " I don't know." 477 | ], 478 | "text/plain": [ 479 | "" 480 | ] 481 | }, 482 | "metadata": {}, 483 | "output_type": "display_data" 484 | } 485 | ], 486 | "source": [ 487 | "display(Markdown(response))" 488 | ] 489 | }, 490 | { 491 | "cell_type": "code", 492 | "execution_count": 32, 493 | "metadata": {}, 494 | "outputs": [], 495 | "source": [ 496 | "query =\"Please list all your shirts available in black \\\n", 497 | "in a table in markdown and summarize each one.\"" 498 | ] 499 | }, 500 | { 501 | "cell_type": "code", 502 | "execution_count": 33, 503 | "metadata": {}, 504 | "outputs": [], 505 | "source": [ 506 | "response = index.query(query)" 507 | ] 508 | }, 509 | { 510 | "cell_type": "code", 511 | "execution_count": 34, 512 | "metadata": {}, 513 | "outputs": [ 514 | { 515 | "data": { 516 | "text/markdown": [ 517 | "\n", 518 | "\n", 519 | "| ProductID | ProductName | Price (INR) |\n", 520 | "|-----------|------------|-------------|\n", 521 | "| 10245285 | Basics Men Black & Grey Slim Fit Striped Casual Shirt | 1469 |\n", 522 | "| 10245063 | Basics Men Black Slim Fit Solid Casual Shirt | 1424 |\n", 523 | "| 10201151 | Mufti Men Black Regular Fit Printed Casual Shirt | 999 |\n", 524 | "\n", 525 | "Basics Men Black & Grey Slim Fit Striped Casual Shirt: Black striped casual shirt, has a spread collar, long sleeves, button placket, and curved hem.\n", 526 | "\n", 527 | "Basics Men Black Slim Fit Solid Casual Shirt: Black solid casual shirt, has a spread collar, long sleeves, button placket, curved hem, and 1 patch pocket.\n", 528 | "\n", 529 | "Mufti Men Black Regular Fit Printed Casual Shirt: Black printed casual shirt, has a spread collar, long sleeves, button placket, curved hem, and 1 patch pocket." 530 | ], 531 | "text/plain": [ 532 | "" 533 | ] 534 | }, 535 | "metadata": {}, 536 | "output_type": "display_data" 537 | } 538 | ], 539 | "source": [ 540 | "display(Markdown(response))" 541 | ] 542 | }, 543 | { 544 | "cell_type": "code", 545 | "execution_count": 35, 546 | "metadata": {}, 547 | "outputs": [], 548 | "source": [ 549 | "loader = CSVLoader(file_path=file)" 550 | ] 551 | }, 552 | { 553 | "cell_type": "code", 554 | "execution_count": 36, 555 | "metadata": {}, 556 | "outputs": [], 557 | "source": [ 558 | "docs = loader.load()" 559 | ] 560 | }, 561 | { 562 | "cell_type": "code", 563 | "execution_count": 37, 564 | "metadata": {}, 565 | "outputs": [ 566 | { 567 | "data": { 568 | "text/plain": [ 569 | "Document(page_content='ProductID: 10017413\\nProductName: DKNY Unisex Black & Grey Printed Medium Trolley Bag\\nProductBrand: DKNY\\nGender: Unisex\\nPrice (INR): 11745\\nNumImages: 7\\nDescription: Black and grey printed medium trolley bag, secured with a TSA lockOne handle on the top and one on the side, has a trolley with a retractable handle on the top and four corner mounted inline skate wheelsOne main zip compartment, zip lining, two compression straps with click clasps, one zip compartment on the flap with three zip pocketsWarranty: 5 yearsWarranty provided by Brand Owner / Manufacturer\\nPrimaryColor: Black', metadata={'source': 'myntra_products_catalog.csv', 'row': 0})" 570 | ] 571 | }, 572 | "execution_count": 37, 573 | "metadata": {}, 574 | "output_type": "execute_result" 575 | } 576 | ], 577 | "source": [ 578 | "docs[0]" 579 | ] 580 | }, 581 | { 582 | "cell_type": "code", 583 | "execution_count": 38, 584 | "metadata": {}, 585 | "outputs": [], 586 | "source": [ 587 | "from langchain.embeddings import OpenAIEmbeddings\n", 588 | "embeddings = OpenAIEmbeddings()" 589 | ] 590 | }, 591 | { 592 | "cell_type": "code", 593 | "execution_count": 39, 594 | "metadata": {}, 595 | "outputs": [], 596 | "source": [ 597 | "embed = embeddings.embed_query(\"Hi my name is Harrison\")" 598 | ] 599 | }, 600 | { 601 | "cell_type": "code", 602 | "execution_count": 40, 603 | "metadata": {}, 604 | "outputs": [ 605 | { 606 | "name": "stdout", 607 | "output_type": "stream", 608 | "text": [ 609 | "1536\n" 610 | ] 611 | } 612 | ], 613 | "source": [ 614 | "print(len(embed))" 615 | ] 616 | }, 617 | { 618 | "cell_type": "code", 619 | "execution_count": 41, 620 | "metadata": {}, 621 | "outputs": [ 622 | { 623 | "name": "stdout", 624 | "output_type": "stream", 625 | "text": [ 626 | "[-0.021913960576057434, 0.006774206645786762, -0.018190348520874977, -0.039148248732089996, -0.014089343138039112]\n" 627 | ] 628 | } 629 | ], 630 | "source": [ 631 | "print(embed[:5])" 632 | ] 633 | }, 634 | { 635 | "cell_type": "code", 636 | "execution_count": 42, 637 | "metadata": {}, 638 | "outputs": [], 639 | "source": [ 640 | "db = DocArrayInMemorySearch.from_documents(\n", 641 | " docs, \n", 642 | " embeddings\n", 643 | ")" 644 | ] 645 | }, 646 | { 647 | "cell_type": "code", 648 | "execution_count": 43, 649 | "metadata": {}, 650 | "outputs": [], 651 | "source": [ 652 | "query = \"Please suggest a cotton shirt in black\"" 653 | ] 654 | }, 655 | { 656 | "cell_type": "code", 657 | "execution_count": 44, 658 | "metadata": {}, 659 | "outputs": [], 660 | "source": [ 661 | "docs = db.similarity_search(query)" 662 | ] 663 | }, 664 | { 665 | "cell_type": "code", 666 | "execution_count": 45, 667 | "metadata": {}, 668 | "outputs": [ 669 | { 670 | "data": { 671 | "text/plain": [ 672 | "4" 673 | ] 674 | }, 675 | "execution_count": 45, 676 | "metadata": {}, 677 | "output_type": "execute_result" 678 | } 679 | ], 680 | "source": [ 681 | "len(docs)" 682 | ] 683 | }, 684 | { 685 | "cell_type": "code", 686 | "execution_count": 46, 687 | "metadata": {}, 688 | "outputs": [ 689 | { 690 | "data": { 691 | "text/plain": [ 692 | "Document(page_content='ProductID: 10201151\\nProductName: Mufti Men Black Regular Fit Printed Casual Shirt\\nProductBrand: Mufti\\nGender: Men\\nPrice (INR): 999\\nNumImages: 5\\nDescription: Black printed casual shirt, has a spread collar, long sleeves, button placket, curved hem, and 1 patch pocket\\nPrimaryColor: Black', metadata={'source': 'myntra_products_catalog.csv', 'row': 8738})" 693 | ] 694 | }, 695 | "execution_count": 46, 696 | "metadata": {}, 697 | "output_type": "execute_result" 698 | } 699 | ], 700 | "source": [ 701 | "docs[0]" 702 | ] 703 | }, 704 | { 705 | "cell_type": "code", 706 | "execution_count": 47, 707 | "metadata": {}, 708 | "outputs": [], 709 | "source": [ 710 | "retriever = db.as_retriever()" 711 | ] 712 | }, 713 | { 714 | "cell_type": "code", 715 | "execution_count": 48, 716 | "metadata": {}, 717 | "outputs": [], 718 | "source": [ 719 | "llm = ChatOpenAI(temperature = 0.0)\n" 720 | ] 721 | }, 722 | { 723 | "cell_type": "code", 724 | "execution_count": 49, 725 | "metadata": {}, 726 | "outputs": [], 727 | "source": [ 728 | "qdocs = \"\".join([docs[i].page_content for i in range(len(docs))])\n" 729 | ] 730 | }, 731 | { 732 | "cell_type": "code", 733 | "execution_count": 50, 734 | "metadata": {}, 735 | "outputs": [], 736 | "source": [ 737 | "response = llm.call_as_llm(f\"{qdocs} Question: Please list all your \\\n", 738 | "shirts with sun protection in a table in markdown and summarize each one.\") \n" 739 | ] 740 | }, 741 | { 742 | "cell_type": "code", 743 | "execution_count": 51, 744 | "metadata": {}, 745 | "outputs": [ 746 | { 747 | "data": { 748 | "text/markdown": [ 749 | "| ProductID | ProductName | ProductBrand | Gender | Price (INR) | NumImages | Description | PrimaryColor |\n", 750 | "|------------|------------------------------------------------------------|----------------|--------|-------------|-----------|------------------------------------------------------------------------------------------------------|--------------|\n", 751 | "| 10201151 | Mufti Men Black Regular Fit Printed Casual Shirt | Mufti | Men | 999 | 5 | Black printed casual shirt, has a spread collar, long sleeves, button placket, curved hem, and 1 patch pocket | Black |\n", 752 | "| 10038579 | IVOC Men Black Regular Fit Printed Casual Shirt | IVOC | Men | 461 | 5 | Black printed casual shirt, has a spread collar, short sleeves, button placket, and curved hem | Black |\n", 753 | "| 10153269 | Indian Terrain Men Black Slim Fit Printed Pure Cotton Shirt | Indian Terrain | Men | 989 | 6 | Black printed casual shirt, has a spread collar, long sleeves, button placket, curved hem, and 1 patch pocket | Black |\n", 754 | "| 10201137 | Mufti Men Black & White Regular Fit Printed Casual Shirt | Mufti | Men | 1074 | 5 | Black and White printed casual shirt, has a spread collar, long sleeves, button placket, curved hem, and 1 patch pocket | Black |\n", 755 | "\n", 756 | "Summary:\n", 757 | "1. Mufti Men Black Regular Fit Printed Casual Shirt: This shirt is from the brand Mufti and is designed for men. It is priced at INR 999 and comes in a black color. It has a spread collar, long sleeves, button placket, curved hem, and 1 patch pocket.\n", 758 | "\n", 759 | "2. IVOC Men Black Regular Fit Printed Casual Shirt: This shirt is from the brand IVOC and is designed for men. It is priced at INR 461 and comes in a black color. It has a spread collar, short sleeves, button placket, and curved hem.\n", 760 | "\n", 761 | "3. Indian Terrain Men Black Slim Fit Printed Pure Cotton Shirt: This shirt is from the brand Indian Terrain and is designed for men. It is priced at INR 989 and comes in a black color. It has a spread collar, long sleeves, button placket, curved hem, and 1 patch pocket.\n", 762 | "\n", 763 | "4. Mufti Men Black & White Regular Fit Printed Casual Shirt: This shirt is from the brand Mufti and is designed for men. It is priced at INR 1074 and comes in a black and white color. It has a spread collar, long sleeves, button placket, curved hem, and 1 patch pocket." 764 | ], 765 | "text/plain": [ 766 | "" 767 | ] 768 | }, 769 | "metadata": {}, 770 | "output_type": "display_data" 771 | } 772 | ], 773 | "source": [ 774 | "display(Markdown(response))" 775 | ] 776 | }, 777 | { 778 | "cell_type": "code", 779 | "execution_count": 52, 780 | "metadata": {}, 781 | "outputs": [], 782 | "source": [ 783 | "qa_stuff = RetrievalQA.from_chain_type(\n", 784 | " llm=llm, \n", 785 | " chain_type=\"stuff\", \n", 786 | " retriever=retriever, \n", 787 | " verbose=True\n", 788 | ")" 789 | ] 790 | }, 791 | { 792 | "cell_type": "code", 793 | "execution_count": 53, 794 | "metadata": {}, 795 | "outputs": [], 796 | "source": [ 797 | "query = \"Please list all your shirts with sun protection in a table \\\n", 798 | "in markdown and summarize each one.\"" 799 | ] 800 | }, 801 | { 802 | "cell_type": "code", 803 | "execution_count": 54, 804 | "metadata": {}, 805 | "outputs": [ 806 | { 807 | "name": "stdout", 808 | "output_type": "stream", 809 | "text": [ 810 | "\n", 811 | "\n", 812 | "\u001b[1m> Entering new RetrievalQA chain...\u001b[0m\n", 813 | "\n", 814 | "\u001b[1m> Finished chain.\u001b[0m\n" 815 | ] 816 | } 817 | ], 818 | "source": [ 819 | "response = qa_stuff.run(query)" 820 | ] 821 | }, 822 | { 823 | "cell_type": "code", 824 | "execution_count": 55, 825 | "metadata": {}, 826 | "outputs": [ 827 | { 828 | "data": { 829 | "text/markdown": [ 830 | "I'm sorry, but I don't have access to the information about sun protection for the shirts." 831 | ], 832 | "text/plain": [ 833 | "" 834 | ] 835 | }, 836 | "metadata": {}, 837 | "output_type": "display_data" 838 | } 839 | ], 840 | "source": [ 841 | "display(Markdown(response))" 842 | ] 843 | }, 844 | { 845 | "cell_type": "code", 846 | "execution_count": 57, 847 | "metadata": {}, 848 | "outputs": [], 849 | "source": [ 850 | "query = \"Please list all your black cotton shirts in a table \\\n", 851 | "in markdown and summarize each one.\"" 852 | ] 853 | }, 854 | { 855 | "cell_type": "code", 856 | "execution_count": 58, 857 | "metadata": {}, 858 | "outputs": [ 859 | { 860 | "name": "stdout", 861 | "output_type": "stream", 862 | "text": [ 863 | "\n", 864 | "\n", 865 | "\u001b[1m> Entering new RetrievalQA chain...\u001b[0m\n", 866 | "\n", 867 | "\u001b[1m> Finished chain.\u001b[0m\n" 868 | ] 869 | } 870 | ], 871 | "source": [ 872 | "response = qa_stuff.run(query)" 873 | ] 874 | }, 875 | { 876 | "cell_type": "code", 877 | "execution_count": 59, 878 | "metadata": {}, 879 | "outputs": [ 880 | { 881 | "data": { 882 | "text/markdown": [ 883 | "| ProductID | ProductName | ProductBrand | Gender | Price (INR) | NumImages | Description | PrimaryColor |\n", 884 | "|------------|--------------------------------------------------------------|---------------------|--------|-------------|-----------|----------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------|\n", 885 | "| 10245285 | Basics Men Black & Grey Slim Fit Striped Casual Shirt | Basics | Men | 1469 | 5 | Black striped casual shirt, has a spread collar, long sleeves, button placket, and curved hem | Black |\n", 886 | "| 10074235 | Black coffee Men White & Blue Slim Fit Checked Formal Shirt | Black coffee | Men | 1599 | 5 | White and Blue checked formal shirt, has a spread collar, long sleeves, button placket, straight hem, and 1 patch pocket | Blue |\n", 887 | "| 10201151 | Mufti Men Black Regular Fit Printed Casual Shirt | Mufti | Men | 999 | 5 | Black printed casual shirt, has a spread collar, long sleeves, button placket, curved hem, and 1 patch pocket | Black |\n", 888 | "| 10267633 | Calvin Klein Jeans Men White & Black Colourblocked T-shirt | Calvin Klein Jeans | Men | 1799 | 6 | White and black Tshirt for men Colourblocked Regular length Round neck Short, regular sleeves Knitted cotton fabric The monochromatic trend is all about wearing the same hue in different textures for an overall tonal look. It allows you to add dimension and depth to your style affordably and has the power to accentuate or down-play certain body parts, making it the right fit for all. | Black |\n", 889 | "\n", 890 | "Summary:\n", 891 | "1. Basics Men Black & Grey Slim Fit Striped Casual Shirt: A black striped casual shirt with a spread collar, long sleeves, button placket, and curved hem.\n", 892 | "2. Black coffee Men White & Blue Slim Fit Checked Formal Shirt: A white and blue checked formal shirt with a spread collar, long sleeves, button placket, straight hem, and 1 patch pocket.\n", 893 | "3. Mufti Men Black Regular Fit Printed Casual Shirt: A black printed casual shirt with a spread collar, long sleeves, button placket, curved hem, and 1 patch pocket.\n", 894 | "4. Calvin Klein Jeans Men White & Black Colourblocked T-shirt: A white and black T-shirt for men with a colourblocked design, regular length, round neck, short regular sleeves, and knitted cotton fabric. The monochromatic trend allows for an overall tonal look and adds dimension and depth to your style." 895 | ], 896 | "text/plain": [ 897 | "" 898 | ] 899 | }, 900 | "metadata": {}, 901 | "output_type": "display_data" 902 | } 903 | ], 904 | "source": [ 905 | "display(Markdown(response))" 906 | ] 907 | }, 908 | { 909 | "cell_type": "code", 910 | "execution_count": 60, 911 | "metadata": {}, 912 | "outputs": [], 913 | "source": [ 914 | "response = index.query(query, llm=llm)" 915 | ] 916 | }, 917 | { 918 | "cell_type": "code", 919 | "execution_count": 61, 920 | "metadata": {}, 921 | "outputs": [], 922 | "source": [ 923 | "index = VectorstoreIndexCreator(\n", 924 | " vectorstore_cls=DocArrayInMemorySearch,\n", 925 | " embedding=embeddings,\n", 926 | ").from_loaders([loader])" 927 | ] 928 | }, 929 | { 930 | "cell_type": "code", 931 | "execution_count": null, 932 | "metadata": {}, 933 | "outputs": [], 934 | "source": [] 935 | } 936 | ], 937 | "metadata": { 938 | "kernelspec": { 939 | "display_name": "Python 3", 940 | "language": "python", 941 | "name": "python3" 942 | }, 943 | "language_info": { 944 | "codemirror_mode": { 945 | "name": "ipython", 946 | "version": 3 947 | }, 948 | "file_extension": ".py", 949 | "mimetype": "text/x-python", 950 | "name": "python", 951 | "nbconvert_exporter": "python", 952 | "pygments_lexer": "ipython3", 953 | "version": "3.10.1" 954 | }, 955 | "orig_nbformat": 4 956 | }, 957 | "nbformat": 4, 958 | "nbformat_minor": 2 959 | } 960 | -------------------------------------------------------------------------------- /L5-Evaluation.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "attachments": {}, 5 | "cell_type": "markdown", 6 | "metadata": {}, 7 | "source": [ 8 | "# LangChain: Evaluation\n", 9 | "\n", 10 | "## Outline:\n", 11 | "\n", 12 | "* Example generation\n", 13 | "* Manual evaluation (and debuging)\n", 14 | "* LLM-assisted evaluation" 15 | ] 16 | }, 17 | { 18 | "cell_type": "code", 19 | "execution_count": null, 20 | "metadata": {}, 21 | "outputs": [], 22 | "source": [ 23 | "import os\n", 24 | "\n", 25 | "from dotenv import load_dotenv, find_dotenv\n", 26 | "_ = load_dotenv(find_dotenv()) # read local .env file" 27 | ] 28 | }, 29 | { 30 | "attachments": {}, 31 | "cell_type": "markdown", 32 | "metadata": {}, 33 | "source": [ 34 | "## Create our QandA application" 35 | ] 36 | }, 37 | { 38 | "cell_type": "code", 39 | "execution_count": 1, 40 | "metadata": {}, 41 | "outputs": [], 42 | "source": [ 43 | "from langchain.chains import RetrievalQA\n", 44 | "from langchain.chat_models import ChatOpenAI\n", 45 | "from langchain.document_loaders import CSVLoader\n", 46 | "from langchain.indexes import VectorstoreIndexCreator\n", 47 | "from langchain.vectorstores import DocArrayInMemorySearch" 48 | ] 49 | }, 50 | { 51 | "cell_type": "code", 52 | "execution_count": 2, 53 | "metadata": {}, 54 | "outputs": [], 55 | "source": [ 56 | "file = 'myntra_products_catalog.csv'\n", 57 | "loader = CSVLoader(file_path=file)\n", 58 | "data = loader.load()" 59 | ] 60 | }, 61 | { 62 | "cell_type": "code", 63 | "execution_count": 3, 64 | "metadata": {}, 65 | "outputs": [], 66 | "source": [ 67 | "index = VectorstoreIndexCreator(\n", 68 | " vectorstore_cls=DocArrayInMemorySearch\n", 69 | ").from_loaders([loader])" 70 | ] 71 | }, 72 | { 73 | "cell_type": "code", 74 | "execution_count": 4, 75 | "metadata": {}, 76 | "outputs": [], 77 | "source": [ 78 | "llm = ChatOpenAI(temperature = 0.0)\n", 79 | "qa = RetrievalQA.from_chain_type(\n", 80 | " llm=llm, \n", 81 | " chain_type=\"stuff\", \n", 82 | " retriever=index.vectorstore.as_retriever(), \n", 83 | " verbose=True,\n", 84 | " chain_type_kwargs = {\n", 85 | " \"document_separator\": \"<<<<>>>>>\"\n", 86 | " }\n", 87 | ")" 88 | ] 89 | }, 90 | { 91 | "cell_type": "code", 92 | "execution_count": 5, 93 | "metadata": {}, 94 | "outputs": [ 95 | { 96 | "data": { 97 | "text/plain": [ 98 | "Document(page_content='ProductID: 10000911\\nProductName: Kenneth Cole Women Navy Blue Solid Backpack\\nProductBrand: Kenneth Cole\\nGender: Women\\nPrice (INR): 2463\\nNumImages: 5\\nDescription: Navy Blue backpackNon-Padded haul loop1 main compartment with zip closurePadded backZip PocketPadded shoulder strap: PaddedWater-resistance: No\\nPrimaryColor: Blue', metadata={'source': 'myntra_products_catalog.csv', 'row': 10})" 99 | ] 100 | }, 101 | "execution_count": 5, 102 | "metadata": {}, 103 | "output_type": "execute_result" 104 | } 105 | ], 106 | "source": [ 107 | "data[10]" 108 | ] 109 | }, 110 | { 111 | "cell_type": "code", 112 | "execution_count": 6, 113 | "metadata": {}, 114 | "outputs": [ 115 | { 116 | "data": { 117 | "text/plain": [ 118 | "Document(page_content='ProductID: 10000245\\nProductName: Parx Men Green Printed Polo Collar T-shirt\\nProductBrand: Parx\\nGender: Men\\nPrice (INR): 629\\nNumImages: 5\\nDescription: Green printed T-shirt, has a polo collar, and short sleeves\\nPrimaryColor: Green', metadata={'source': 'myntra_products_catalog.csv', 'row': 11})" 119 | ] 120 | }, 121 | "execution_count": 6, 122 | "metadata": {}, 123 | "output_type": "execute_result" 124 | } 125 | ], 126 | "source": [ 127 | "data[11]" 128 | ] 129 | }, 130 | { 131 | "attachments": {}, 132 | "cell_type": "markdown", 133 | "metadata": {}, 134 | "source": [ 135 | "### Hard-coded examples" 136 | ] 137 | }, 138 | { 139 | "cell_type": "code", 140 | "execution_count": 20, 141 | "metadata": {}, 142 | "outputs": [], 143 | "source": [ 144 | "examples = [\n", 145 | " {\n", 146 | " \"query\": \"Does the CKenneth Cole Women Navy Blue Solid Backpack\\\n", 147 | " have pockets?\",\n", 148 | " \"answer\": \"Yes\"\n", 149 | " },\n", 150 | " {\n", 151 | " \"query\": \"Does the Parx Men Green Printed Polo Collar T-shirt \\\n", 152 | " have a collar?\",\n", 153 | " \"answer\": \"Yes\"\n", 154 | " }\n", 155 | "]" 156 | ] 157 | }, 158 | { 159 | "attachments": {}, 160 | "cell_type": "markdown", 161 | "metadata": {}, 162 | "source": [ 163 | "### LLM-Generated examples" 164 | ] 165 | }, 166 | { 167 | "cell_type": "code", 168 | "execution_count": 8, 169 | "metadata": {}, 170 | "outputs": [], 171 | "source": [ 172 | "from langchain.evaluation.qa import QAGenerateChain\n" 173 | ] 174 | }, 175 | { 176 | "cell_type": "code", 177 | "execution_count": 9, 178 | "metadata": {}, 179 | "outputs": [], 180 | "source": [ 181 | "example_gen_chain = QAGenerateChain.from_llm(ChatOpenAI())" 182 | ] 183 | }, 184 | { 185 | "cell_type": "code", 186 | "execution_count": 10, 187 | "metadata": {}, 188 | "outputs": [ 189 | { 190 | "name": "stderr", 191 | "output_type": "stream", 192 | "text": [ 193 | "/Users/alexbonilla/.pyenv/versions/3.10.1/lib/python3.10/site-packages/langchain/chains/llm.py:303: UserWarning: The apply_and_parse method is deprecated, instead pass an output parser directly to LLMChain.\n", 194 | " warnings.warn(\n" 195 | ] 196 | } 197 | ], 198 | "source": [ 199 | "new_examples = example_gen_chain.apply_and_parse(\n", 200 | " [{\"doc\": t} for t in data[:5]]\n", 201 | ")" 202 | ] 203 | }, 204 | { 205 | "cell_type": "code", 206 | "execution_count": 11, 207 | "metadata": {}, 208 | "outputs": [ 209 | { 210 | "data": { 211 | "text/plain": [ 212 | "{'query': 'What is the product ID of the DKNY Unisex Black & Grey Printed Medium Trolley Bag?',\n", 213 | " 'answer': 'The product ID of the DKNY Unisex Black & Grey Printed Medium Trolley Bag is 10017413.'}" 214 | ] 215 | }, 216 | "execution_count": 11, 217 | "metadata": {}, 218 | "output_type": "execute_result" 219 | } 220 | ], 221 | "source": [ 222 | "new_examples[0]" 223 | ] 224 | }, 225 | { 226 | "cell_type": "code", 227 | "execution_count": 12, 228 | "metadata": {}, 229 | "outputs": [ 230 | { 231 | "data": { 232 | "text/plain": [ 233 | "Document(page_content='ProductID: 10017413\\nProductName: DKNY Unisex Black & Grey Printed Medium Trolley Bag\\nProductBrand: DKNY\\nGender: Unisex\\nPrice (INR): 11745\\nNumImages: 7\\nDescription: Black and grey printed medium trolley bag, secured with a TSA lockOne handle on the top and one on the side, has a trolley with a retractable handle on the top and four corner mounted inline skate wheelsOne main zip compartment, zip lining, two compression straps with click clasps, one zip compartment on the flap with three zip pocketsWarranty: 5 yearsWarranty provided by Brand Owner / Manufacturer\\nPrimaryColor: Black', metadata={'source': 'myntra_products_catalog.csv', 'row': 0})" 234 | ] 235 | }, 236 | "execution_count": 12, 237 | "metadata": {}, 238 | "output_type": "execute_result" 239 | } 240 | ], 241 | "source": [ 242 | "data[0]" 243 | ] 244 | }, 245 | { 246 | "cell_type": "code", 247 | "execution_count": 13, 248 | "metadata": {}, 249 | "outputs": [ 250 | { 251 | "data": { 252 | "text/plain": [ 253 | "5" 254 | ] 255 | }, 256 | "execution_count": 13, 257 | "metadata": {}, 258 | "output_type": "execute_result" 259 | } 260 | ], 261 | "source": [ 262 | "len(new_examples)" 263 | ] 264 | }, 265 | { 266 | "cell_type": "code", 267 | "execution_count": 14, 268 | "metadata": {}, 269 | "outputs": [ 270 | { 271 | "data": { 272 | "text/plain": [ 273 | "{'query': 'What is the price of the Parx Men Brown & Off-White Slim Fit Printed Casual Shirt?',\n", 274 | " 'answer': 'The price of the Parx Men Brown & Off-White Slim Fit Printed Casual Shirt is INR 759.'}" 275 | ] 276 | }, 277 | "execution_count": 14, 278 | "metadata": {}, 279 | "output_type": "execute_result" 280 | } 281 | ], 282 | "source": [ 283 | "new_examples[4]" 284 | ] 285 | }, 286 | { 287 | "cell_type": "code", 288 | "execution_count": 15, 289 | "metadata": {}, 290 | "outputs": [ 291 | { 292 | "data": { 293 | "text/plain": [ 294 | "Document(page_content='ProductID: 10017833\\nProductName: Parx Men Brown & Off-White Slim Fit Printed Casual Shirt\\nProductBrand: Parx\\nGender: Men\\nPrice (INR): 759\\nNumImages: 5\\nDescription: Brown and off-white printed casual shirt, has a spread collar, long sleeves, button placket, curved hem, one patch pocket\\nPrimaryColor: White', metadata={'source': 'myntra_products_catalog.csv', 'row': 4})" 295 | ] 296 | }, 297 | "execution_count": 15, 298 | "metadata": {}, 299 | "output_type": "execute_result" 300 | } 301 | ], 302 | "source": [ 303 | "data[4]" 304 | ] 305 | }, 306 | { 307 | "attachments": {}, 308 | "cell_type": "markdown", 309 | "metadata": {}, 310 | "source": [ 311 | "### Combine examples" 312 | ] 313 | }, 314 | { 315 | "cell_type": "code", 316 | "execution_count": 21, 317 | "metadata": {}, 318 | "outputs": [], 319 | "source": [ 320 | "examples += new_examples" 321 | ] 322 | }, 323 | { 324 | "cell_type": "code", 325 | "execution_count": 26, 326 | "metadata": {}, 327 | "outputs": [ 328 | { 329 | "name": "stdout", 330 | "output_type": "stream", 331 | "text": [ 332 | "\n", 333 | "\n", 334 | "\u001b[1m> Entering new RetrievalQA chain...\u001b[0m\n", 335 | "\n", 336 | "\u001b[1m> Finished chain.\u001b[0m\n" 337 | ] 338 | }, 339 | { 340 | "data": { 341 | "text/plain": [ 342 | "'Based on the provided information, the Kenneth Cole Women Navy Blue Solid Backpack has a zip pocket.'" 343 | ] 344 | }, 345 | "execution_count": 26, 346 | "metadata": {}, 347 | "output_type": "execute_result" 348 | } 349 | ], 350 | "source": [ 351 | "qa.run(examples[0][\"query\"])" 352 | ] 353 | }, 354 | { 355 | "attachments": {}, 356 | "cell_type": "markdown", 357 | "metadata": {}, 358 | "source": [ 359 | "## Manual Evaluation" 360 | ] 361 | }, 362 | { 363 | "cell_type": "code", 364 | "execution_count": 27, 365 | "metadata": {}, 366 | "outputs": [], 367 | "source": [ 368 | "import langchain\n", 369 | "langchain.debug = True" 370 | ] 371 | }, 372 | { 373 | "cell_type": "code", 374 | "execution_count": 24, 375 | "metadata": {}, 376 | "outputs": [ 377 | { 378 | "name": "stdout", 379 | "output_type": "stream", 380 | "text": [ 381 | "\u001b[32;1m\u001b[1;3m[chain/start]\u001b[0m \u001b[1m[1:chain:RetrievalQA] Entering Chain run with input:\n", 382 | "\u001b[0m{\n", 383 | " \"query\": \"Does the CKenneth Cole Women Navy Blue Solid Backpack have pockets?\"\n", 384 | "}\n", 385 | "\u001b[32;1m\u001b[1;3m[chain/start]\u001b[0m \u001b[1m[1:chain:RetrievalQA > 3:chain:StuffDocumentsChain] Entering Chain run with input:\n", 386 | "\u001b[0m[inputs]\n", 387 | "\u001b[32;1m\u001b[1;3m[chain/start]\u001b[0m \u001b[1m[1:chain:RetrievalQA > 3:chain:StuffDocumentsChain > 4:chain:LLMChain] Entering Chain run with input:\n", 388 | "\u001b[0m{\n", 389 | " \"question\": \"Does the CKenneth Cole Women Navy Blue Solid Backpack have pockets?\",\n", 390 | " \"context\": \"ProductID: 10000911\\nProductName: Kenneth Cole Women Navy Blue Solid Backpack\\nProductBrand: Kenneth Cole\\nGender: Women\\nPrice (INR): 2463\\nNumImages: 5\\nDescription: Navy Blue backpackNon-Padded haul loop1 main compartment with zip closurePadded backZip PocketPadded shoulder strap: PaddedWater-resistance: No\\nPrimaryColor: Blue<<<<>>>>>ProductID: 10000915\\nProductName: Kenneth Cole Women Brown Solid Backpack\\nProductBrand: Kenneth Cole\\nGender: Women\\nPrice (INR): 2274\\nNumImages: 5\\nDescription: Brown solid backpackNon-Padded haul loop1 main compartment with zip closurePadded backPadded shoulder strap: Non-Padded\\nPrimaryColor: Brown<<<<>>>>>ProductID: 10000921\\nProductName: Kenneth Cole Women Pink Solid Backpack\\nProductBrand: Kenneth Cole\\nGender: Women\\nPrice (INR): 2463\\nNumImages: 5\\nDescription: Pink solid backpackNon-Padded haul loop1 main compartment with zip closureNon-Padded backPadded shoulder strap: Non-Padded\\nPrimaryColor: Pink<<<<>>>>>ProductID: 10143543\\nProductName: Calvin Klein Jeans Men Navy Blue Solid Laptop Backpack\\nProductBrand: Calvin Klein Jeans\\nGender: Men\\nPrice (INR): 8449\\nNumImages: 6\\nDescription: Navy blue solid laptop backpackNon-Padded haul loop1 main compartment with zip closureLightly Padded back2 internal pocket, 1 external pocketZip PocketPadded shoulder strap: Non-PaddedWater-resistance: NoWarranty: 6 months Warranty provided by brand/manufacturer\\nPrimaryColor: Blue\"\n", 391 | "}\n", 392 | "\u001b[32;1m\u001b[1;3m[llm/start]\u001b[0m \u001b[1m[1:chain:RetrievalQA > 3:chain:StuffDocumentsChain > 4:chain:LLMChain > 5:llm:ChatOpenAI] Entering LLM run with input:\n", 393 | "\u001b[0m{\n", 394 | " \"prompts\": [\n", 395 | " \"System: Use the following pieces of context to answer the users question. \\nIf you don't know the answer, just say that you don't know, don't try to make up an answer.\\n----------------\\nProductID: 10000911\\nProductName: Kenneth Cole Women Navy Blue Solid Backpack\\nProductBrand: Kenneth Cole\\nGender: Women\\nPrice (INR): 2463\\nNumImages: 5\\nDescription: Navy Blue backpackNon-Padded haul loop1 main compartment with zip closurePadded backZip PocketPadded shoulder strap: PaddedWater-resistance: No\\nPrimaryColor: Blue<<<<>>>>>ProductID: 10000915\\nProductName: Kenneth Cole Women Brown Solid Backpack\\nProductBrand: Kenneth Cole\\nGender: Women\\nPrice (INR): 2274\\nNumImages: 5\\nDescription: Brown solid backpackNon-Padded haul loop1 main compartment with zip closurePadded backPadded shoulder strap: Non-Padded\\nPrimaryColor: Brown<<<<>>>>>ProductID: 10000921\\nProductName: Kenneth Cole Women Pink Solid Backpack\\nProductBrand: Kenneth Cole\\nGender: Women\\nPrice (INR): 2463\\nNumImages: 5\\nDescription: Pink solid backpackNon-Padded haul loop1 main compartment with zip closureNon-Padded backPadded shoulder strap: Non-Padded\\nPrimaryColor: Pink<<<<>>>>>ProductID: 10143543\\nProductName: Calvin Klein Jeans Men Navy Blue Solid Laptop Backpack\\nProductBrand: Calvin Klein Jeans\\nGender: Men\\nPrice (INR): 8449\\nNumImages: 6\\nDescription: Navy blue solid laptop backpackNon-Padded haul loop1 main compartment with zip closureLightly Padded back2 internal pocket, 1 external pocketZip PocketPadded shoulder strap: Non-PaddedWater-resistance: NoWarranty: 6 months Warranty provided by brand/manufacturer\\nPrimaryColor: Blue\\nHuman: Does the CKenneth Cole Women Navy Blue Solid Backpack have pockets?\"\n", 396 | " ]\n", 397 | "}\n", 398 | "\u001b[36;1m\u001b[1;3m[llm/end]\u001b[0m \u001b[1m[1:chain:RetrievalQA > 3:chain:StuffDocumentsChain > 4:chain:LLMChain > 5:llm:ChatOpenAI] [1.31s] Exiting LLM run with output:\n", 399 | "\u001b[0m{\n", 400 | " \"generations\": [\n", 401 | " [\n", 402 | " {\n", 403 | " \"text\": \"Based on the provided information, the Kenneth Cole Women Navy Blue Solid Backpack has a zip pocket.\",\n", 404 | " \"generation_info\": {\n", 405 | " \"finish_reason\": \"stop\"\n", 406 | " },\n", 407 | " \"message\": {\n", 408 | " \"lc\": 1,\n", 409 | " \"type\": \"constructor\",\n", 410 | " \"id\": [\n", 411 | " \"langchain\",\n", 412 | " \"schema\",\n", 413 | " \"messages\",\n", 414 | " \"AIMessage\"\n", 415 | " ],\n", 416 | " \"kwargs\": {\n", 417 | " \"content\": \"Based on the provided information, the Kenneth Cole Women Navy Blue Solid Backpack has a zip pocket.\",\n", 418 | " \"additional_kwargs\": {}\n", 419 | " }\n", 420 | " }\n", 421 | " }\n", 422 | " ]\n", 423 | " ],\n", 424 | " \"llm_output\": {\n", 425 | " \"token_usage\": {\n", 426 | " \"prompt_tokens\": 416,\n", 427 | " \"completion_tokens\": 19,\n", 428 | " \"total_tokens\": 435\n", 429 | " },\n", 430 | " \"model_name\": \"gpt-3.5-turbo\"\n", 431 | " },\n", 432 | " \"run\": null\n", 433 | "}\n", 434 | "\u001b[36;1m\u001b[1;3m[chain/end]\u001b[0m \u001b[1m[1:chain:RetrievalQA > 3:chain:StuffDocumentsChain > 4:chain:LLMChain] [1.32s] Exiting Chain run with output:\n", 435 | "\u001b[0m{\n", 436 | " \"text\": \"Based on the provided information, the Kenneth Cole Women Navy Blue Solid Backpack has a zip pocket.\"\n", 437 | "}\n", 438 | "\u001b[36;1m\u001b[1;3m[chain/end]\u001b[0m \u001b[1m[1:chain:RetrievalQA > 3:chain:StuffDocumentsChain] [1.33s] Exiting Chain run with output:\n", 439 | "\u001b[0m{\n", 440 | " \"output_text\": \"Based on the provided information, the Kenneth Cole Women Navy Blue Solid Backpack has a zip pocket.\"\n", 441 | "}\n", 442 | "\u001b[36;1m\u001b[1;3m[chain/end]\u001b[0m \u001b[1m[1:chain:RetrievalQA] [1.83s] Exiting Chain run with output:\n", 443 | "\u001b[0m{\n", 444 | " \"result\": \"Based on the provided information, the Kenneth Cole Women Navy Blue Solid Backpack has a zip pocket.\"\n", 445 | "}\n" 446 | ] 447 | }, 448 | { 449 | "data": { 450 | "text/plain": [ 451 | "'Based on the provided information, the Kenneth Cole Women Navy Blue Solid Backpack has a zip pocket.'" 452 | ] 453 | }, 454 | "execution_count": 24, 455 | "metadata": {}, 456 | "output_type": "execute_result" 457 | } 458 | ], 459 | "source": [ 460 | "qa.run(examples[0][\"query\"])" 461 | ] 462 | }, 463 | { 464 | "cell_type": "code", 465 | "execution_count": 28, 466 | "metadata": {}, 467 | "outputs": [], 468 | "source": [ 469 | "# Turn off the debug mode\n", 470 | "langchain.debug = False" 471 | ] 472 | }, 473 | { 474 | "attachments": {}, 475 | "cell_type": "markdown", 476 | "metadata": {}, 477 | "source": [ 478 | "## LLM assisted evaluation\n" 479 | ] 480 | }, 481 | { 482 | "cell_type": "code", 483 | "execution_count": 29, 484 | "metadata": {}, 485 | "outputs": [ 486 | { 487 | "name": "stdout", 488 | "output_type": "stream", 489 | "text": [ 490 | "\n", 491 | "\n", 492 | "\u001b[1m> Entering new RetrievalQA chain...\u001b[0m\n", 493 | "\n", 494 | "\u001b[1m> Finished chain.\u001b[0m\n", 495 | "\n", 496 | "\n", 497 | "\u001b[1m> Entering new RetrievalQA chain...\u001b[0m\n", 498 | "\n", 499 | "\u001b[1m> Finished chain.\u001b[0m\n", 500 | "\n", 501 | "\n", 502 | "\u001b[1m> Entering new RetrievalQA chain...\u001b[0m\n", 503 | "\n", 504 | "\u001b[1m> Finished chain.\u001b[0m\n", 505 | "\n", 506 | "\n", 507 | "\u001b[1m> Entering new RetrievalQA chain...\u001b[0m\n", 508 | "\n", 509 | "\u001b[1m> Finished chain.\u001b[0m\n", 510 | "\n", 511 | "\n", 512 | "\u001b[1m> Entering new RetrievalQA chain...\u001b[0m\n", 513 | "\n", 514 | "\u001b[1m> Finished chain.\u001b[0m\n", 515 | "\n", 516 | "\n", 517 | "\u001b[1m> Entering new RetrievalQA chain...\u001b[0m\n", 518 | "\n", 519 | "\u001b[1m> Finished chain.\u001b[0m\n", 520 | "\n", 521 | "\n", 522 | "\u001b[1m> Entering new RetrievalQA chain...\u001b[0m\n", 523 | "\n", 524 | "\u001b[1m> Finished chain.\u001b[0m\n" 525 | ] 526 | } 527 | ], 528 | "source": [ 529 | "predictions = qa.apply(examples)" 530 | ] 531 | }, 532 | { 533 | "cell_type": "code", 534 | "execution_count": 30, 535 | "metadata": {}, 536 | "outputs": [], 537 | "source": [ 538 | "from langchain.evaluation.qa import QAEvalChain" 539 | ] 540 | }, 541 | { 542 | "cell_type": "code", 543 | "execution_count": 31, 544 | "metadata": {}, 545 | "outputs": [], 546 | "source": [ 547 | "llm = ChatOpenAI(temperature=0)\n", 548 | "eval_chain = QAEvalChain.from_llm(llm)" 549 | ] 550 | }, 551 | { 552 | "cell_type": "code", 553 | "execution_count": 32, 554 | "metadata": {}, 555 | "outputs": [ 556 | { 557 | "name": "stderr", 558 | "output_type": "stream", 559 | "text": [ 560 | "Retrying langchain.chat_models.openai.ChatOpenAI.completion_with_retry.._completion_with_retry in 1.0 seconds as it raised APIError: Bad gateway. {\"error\":{\"code\":502,\"message\":\"Bad gateway.\",\"param\":null,\"type\":\"cf_bad_gateway\"}} 502 {'error': {'code': 502, 'message': 'Bad gateway.', 'param': None, 'type': 'cf_bad_gateway'}} {'Date': 'Tue, 18 Jul 2023 18:59:01 GMT', 'Content-Type': 'application/json', 'Content-Length': '84', 'Connection': 'keep-alive', 'X-Frame-Options': 'SAMEORIGIN', 'Referrer-Policy': 'same-origin', 'Cache-Control': 'private, max-age=0, no-store, no-cache, must-revalidate, post-check=0, pre-check=0', 'Expires': 'Thu, 01 Jan 1970 00:00:01 GMT', 'Server': 'cloudflare', 'CF-RAY': '7e8ced527a493ae4-IAD', 'alt-svc': 'h3=\":443\"; ma=86400'}.\n" 561 | ] 562 | } 563 | ], 564 | "source": [ 565 | "graded_outputs = eval_chain.evaluate(examples, predictions)" 566 | ] 567 | }, 568 | { 569 | "cell_type": "code", 570 | "execution_count": 37, 571 | "metadata": {}, 572 | "outputs": [ 573 | { 574 | "name": "stdout", 575 | "output_type": "stream", 576 | "text": [ 577 | "Example 0:\n", 578 | "Question: Does the CKenneth Cole Women Navy Blue Solid Backpack have pockets?\n", 579 | "Real Answer: Yes\n", 580 | "Predicted Answer: Based on the provided information, the Kenneth Cole Women Navy Blue Solid Backpack has a zip pocket.\n", 581 | "Predicted Grade: CORRECT\n", 582 | "\n", 583 | "Example 1:\n", 584 | "Question: Does the Parx Men Green Printed Polo Collar T-shirt have a collar?\n", 585 | "Real Answer: Yes\n", 586 | "Predicted Answer: Yes, the Parx Men Green Printed Polo Collar T-shirt does have a collar.\n", 587 | "Predicted Grade: CORRECT\n", 588 | "\n", 589 | "Example 2:\n", 590 | "Question: What is the product ID of the DKNY Unisex Black & Grey Printed Medium Trolley Bag?\n", 591 | "Real Answer: The product ID of the DKNY Unisex Black & Grey Printed Medium Trolley Bag is 10017413.\n", 592 | "Predicted Answer: The product ID of the DKNY Unisex Black & Grey Printed Medium Trolley Bag is 10017413.\n", 593 | "Predicted Grade: CORRECT\n", 594 | "\n", 595 | "Example 3:\n", 596 | "Question: What is the product name and brand of the kurta set described in the document?\n", 597 | "Real Answer: The product name is \"EthnoVogue Women Beige & Grey Made to Measure Custom Made Kurta Set with Jacket\" and the brand is \"EthnoVogue\".\n", 598 | "Predicted Answer: The product name is \"BownBee Girls Purple & Mustard Yellow Embellished Kurta Set\" and the brand is \"BownBee\".\n", 599 | "Predicted Grade: INCORRECT\n", 600 | "\n", 601 | "Example 4:\n", 602 | "Question: What is the product name and brand of the jeans mentioned in the document?\n", 603 | "Real Answer: The product name is \"SPYKAR Women Pink Alexa Super Skinny Fit High-Rise Clean Look Stretchable Cropped Jeans\" and the brand is \"SPYKAR\".\n", 604 | "Predicted Answer: The product name and brand of the jeans mentioned in the document are as follows:\n", 605 | "\n", 606 | "1. ProductID: 10144961\n", 607 | " ProductName: GAP Girls Blue Girlfriend Jeans\n", 608 | " ProductBrand: GAP\n", 609 | "\n", 610 | "2. ProductID: 10180489\n", 611 | " ProductName: GAP Boys Superdenim Slim Jeans with Fantastiflex\n", 612 | " ProductBrand: GAP\n", 613 | "\n", 614 | "3. ProductID: 1009547\n", 615 | " ProductName: Slub Blue Washed Slim Jeans\n", 616 | " ProductBrand: Slub\n", 617 | "\n", 618 | "4. ProductID: 10145033\n", 619 | " ProductName: GAP Girls Superdenim Jeggings with Fantastiflex\n", 620 | " ProductBrand: GAP\n", 621 | "Predicted Grade: INCORRECT\n", 622 | "\n", 623 | "Example 5:\n", 624 | "Question: What is the product name of the suit mentioned in the document?\n", 625 | "Real Answer: The product name of the suit mentioned in the document is \"Raymond Men Blue Self-Design Single-Breasted Bandhgala Suit\".\n", 626 | "Predicted Answer: There are multiple suits mentioned in the document. The product names are:\n", 627 | "\n", 628 | "1. SUITLTD Grey Waistcoat\n", 629 | "2. Raymond Men Blue Solid Regular-Fit Tuxedo Suit\n", 630 | "3. Park Avenue Men Blue Single-Breasted Formal Slim Fit Suit\n", 631 | "4. SUITLTD Black Single-Breasted Blazer\n", 632 | "Predicted Grade: CORRECT\n", 633 | "\n", 634 | "Example 6:\n", 635 | "Question: What is the price of the Parx Men Brown & Off-White Slim Fit Printed Casual Shirt?\n", 636 | "Real Answer: The price of the Parx Men Brown & Off-White Slim Fit Printed Casual Shirt is INR 759.\n", 637 | "Predicted Answer: The price of the Parx Men Brown & Off-White Slim Fit Printed Casual Shirt is INR 759.\n", 638 | "Predicted Grade: CORRECT\n", 639 | "\n" 640 | ] 641 | } 642 | ], 643 | "source": [ 644 | "for i, eg in enumerate(examples):\n", 645 | " print(f\"Example {i}:\")\n", 646 | " print(\"Question: \" + predictions[i]['query'])\n", 647 | " print(\"Real Answer: \" + predictions[i]['answer'])\n", 648 | " print(\"Predicted Answer: \" + predictions[i]['result'])\n", 649 | " print(\"Predicted Grade: \" + graded_outputs[i]['results'])\n", 650 | " print()" 651 | ] 652 | }, 653 | { 654 | "cell_type": "code", 655 | "execution_count": null, 656 | "metadata": {}, 657 | "outputs": [], 658 | "source": [] 659 | }, 660 | { 661 | "cell_type": "code", 662 | "execution_count": null, 663 | "metadata": {}, 664 | "outputs": [], 665 | "source": [] 666 | }, 667 | { 668 | "cell_type": "code", 669 | "execution_count": null, 670 | "metadata": {}, 671 | "outputs": [], 672 | "source": [] 673 | }, 674 | { 675 | "cell_type": "code", 676 | "execution_count": null, 677 | "metadata": {}, 678 | "outputs": [], 679 | "source": [] 680 | } 681 | ], 682 | "metadata": { 683 | "kernelspec": { 684 | "display_name": "Python 3", 685 | "language": "python", 686 | "name": "python3" 687 | }, 688 | "language_info": { 689 | "codemirror_mode": { 690 | "name": "ipython", 691 | "version": 3 692 | }, 693 | "file_extension": ".py", 694 | "mimetype": "text/x-python", 695 | "name": "python", 696 | "nbconvert_exporter": "python", 697 | "pygments_lexer": "ipython3", 698 | "version": "3.10.1" 699 | }, 700 | "orig_nbformat": 4 701 | }, 702 | "nbformat": 4, 703 | "nbformat_minor": 2 704 | } 705 | -------------------------------------------------------------------------------- /L6-Agents.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "attachments": {}, 5 | "cell_type": "markdown", 6 | "metadata": {}, 7 | "source": [ 8 | "# LangChain: Agents\n", 9 | "\n", 10 | "## Outline:\n", 11 | "\n", 12 | "* Using built in LangChain tools: DuckDuckGo search and Wikipedia\n", 13 | "* Defining your own tools" 14 | ] 15 | }, 16 | { 17 | "cell_type": "code", 18 | "execution_count": 1, 19 | "metadata": {}, 20 | "outputs": [], 21 | "source": [ 22 | "import os\n", 23 | "\n", 24 | "from dotenv import load_dotenv, find_dotenv\n", 25 | "_ = load_dotenv(find_dotenv()) # read local .env file\n", 26 | "\n", 27 | "import warnings\n", 28 | "warnings.filterwarnings(\"ignore\")" 29 | ] 30 | }, 31 | { 32 | "attachments": {}, 33 | "cell_type": "markdown", 34 | "metadata": {}, 35 | "source": [ 36 | "## Built-in LangChain tools" 37 | ] 38 | }, 39 | { 40 | "cell_type": "code", 41 | "execution_count": 1, 42 | "metadata": {}, 43 | "outputs": [], 44 | "source": [ 45 | "#!pip install -U wikipedia" 46 | ] 47 | }, 48 | { 49 | "cell_type": "code", 50 | "execution_count": 2, 51 | "metadata": {}, 52 | "outputs": [], 53 | "source": [ 54 | "from langchain.agents.agent_toolkits import create_python_agent\n", 55 | "from langchain.agents import load_tools, initialize_agent\n", 56 | "from langchain.agents import AgentType\n", 57 | "from langchain.tools.python.tool import PythonREPLTool\n", 58 | "from langchain.python import PythonREPL\n", 59 | "from langchain.chat_models import ChatOpenAI" 60 | ] 61 | }, 62 | { 63 | "cell_type": "code", 64 | "execution_count": 3, 65 | "metadata": {}, 66 | "outputs": [], 67 | "source": [ 68 | "llm = ChatOpenAI(temperature=0)" 69 | ] 70 | }, 71 | { 72 | "cell_type": "code", 73 | "execution_count": 4, 74 | "metadata": {}, 75 | "outputs": [], 76 | "source": [ 77 | "tools = load_tools([\"llm-math\",\"wikipedia\"], llm=llm)" 78 | ] 79 | }, 80 | { 81 | "cell_type": "code", 82 | "execution_count": 5, 83 | "metadata": {}, 84 | "outputs": [], 85 | "source": [ 86 | "agent= initialize_agent(\n", 87 | " tools, \n", 88 | " llm, \n", 89 | " agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION,\n", 90 | " handle_parsing_errors=True,\n", 91 | " verbose = True)" 92 | ] 93 | }, 94 | { 95 | "cell_type": "code", 96 | "execution_count": 6, 97 | "metadata": {}, 98 | "outputs": [ 99 | { 100 | "name": "stdout", 101 | "output_type": "stream", 102 | "text": [ 103 | "\n", 104 | "\n", 105 | "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n", 106 | "\u001b[32;1m\u001b[1;3mI can use the calculator tool to find the answer to this question.\n", 107 | "\n", 108 | "Action:\n", 109 | "```json\n", 110 | "{\n", 111 | " \"action\": \"Calculator\",\n", 112 | " \"action_input\": \"25% of 300\"\n", 113 | "}\n", 114 | "```\u001b[0m\n", 115 | "Observation: \u001b[36;1m\u001b[1;3mAnswer: 75.0\u001b[0m\n", 116 | "Thought:\u001b[32;1m\u001b[1;3mThe answer is 75.0.\n", 117 | "Final Answer: 75.0\u001b[0m\n", 118 | "\n", 119 | "\u001b[1m> Finished chain.\u001b[0m\n" 120 | ] 121 | }, 122 | { 123 | "data": { 124 | "text/plain": [ 125 | "{'input': 'What is the 25% of 300?', 'output': '75.0'}" 126 | ] 127 | }, 128 | "execution_count": 6, 129 | "metadata": {}, 130 | "output_type": "execute_result" 131 | } 132 | ], 133 | "source": [ 134 | "agent(\"What is the 25% of 300?\")" 135 | ] 136 | }, 137 | { 138 | "cell_type": "code", 139 | "execution_count": 7, 140 | "metadata": {}, 141 | "outputs": [ 142 | { 143 | "name": "stdout", 144 | "output_type": "stream", 145 | "text": [ 146 | "\n", 147 | "\n", 148 | "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n", 149 | "\u001b[32;1m\u001b[1;3mThought: I can use Wikipedia to find out what book Tom M. Mitchell wrote.\n", 150 | "\n", 151 | "Action:\n", 152 | "```json\n", 153 | "{\n", 154 | " \"action\": \"Wikipedia\",\n", 155 | " \"action_input\": \"Tom M. Mitchell\"\n", 156 | "}\n", 157 | "```\u001b[0m" 158 | ] 159 | }, 160 | { 161 | "name": "stderr", 162 | "output_type": "stream", 163 | "text": [ 164 | "/Users/alexbonilla/.pyenv/versions/3.10.1/lib/python3.10/site-packages/wikipedia/wikipedia.py:389: GuessedAtParserWarning: No parser was explicitly specified, so I'm using the best available HTML parser for this system (\"html.parser\"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently.\n", 165 | "\n", 166 | "The code that caused this warning is on line 389 of the file /Users/alexbonilla/.pyenv/versions/3.10.1/lib/python3.10/site-packages/wikipedia/wikipedia.py. To get rid of this warning, pass the additional argument 'features=\"html.parser\"' to the BeautifulSoup constructor.\n", 167 | "\n", 168 | " lis = BeautifulSoup(html).find_all('li')\n" 169 | ] 170 | }, 171 | { 172 | "name": "stdout", 173 | "output_type": "stream", 174 | "text": [ 175 | "\n", 176 | "Observation: \u001b[33;1m\u001b[1;3mPage: Tom M. Mitchell\n", 177 | "Summary: Tom Michael Mitchell (born August 9, 1951) is an American computer scientist and the Founders University Professor at Carnegie Mellon University (CMU). He is a founder and former Chair of the Machine Learning Department at CMU. Mitchell is known for his contributions to the advancement of machine learning, artificial intelligence, and cognitive neuroscience and is the author of the textbook Machine Learning. He is a member of the United States National Academy of Engineering since 2010. He is also a Fellow of the American Academy of Arts and Sciences, the American Association for the Advancement of Science and a Fellow and past President of the Association for the Advancement of Artificial Intelligence. In October 2018, Mitchell was appointed as the Interim Dean of the School of Computer Science at Carnegie Mellon.\n", 178 | "\n", 179 | "Page: Tom Mitchell (Australian footballer)\n", 180 | "Summary: Thomas Mitchell (born 31 May 1993) is a professional Australian rules footballer playing for the Collingwood Football Club in the Australian Football League (AFL). He previously played for the Sydney Swans from 2012 to 2016, and the Hawthorn Football Club between 2017 and 2022. Mitchell won the Brownlow Medal as the league's best and fairest player in 2018 and set the record for the most disposals in a VFL/AFL match, accruing 54 in a game against Collingwood during that season.\n", 181 | "\n", 182 | "\u001b[0m\n", 183 | "Thought:\u001b[32;1m\u001b[1;3mThe book that Tom M. Mitchell wrote is \"Machine Learning\".\n", 184 | "Final Answer: Machine Learning\u001b[0m\n", 185 | "\n", 186 | "\u001b[1m> Finished chain.\u001b[0m\n" 187 | ] 188 | } 189 | ], 190 | "source": [ 191 | "question = \"Tom M. Mitchell is an American computer scientist \\\n", 192 | "and the Founders University Professor at Carnegie Mellon University (CMU)\\\n", 193 | "what book did he write?\"\n", 194 | "result = agent(question) " 195 | ] 196 | }, 197 | { 198 | "attachments": {}, 199 | "cell_type": "markdown", 200 | "metadata": {}, 201 | "source": [ 202 | "## Python Agent" 203 | ] 204 | }, 205 | { 206 | "cell_type": "code", 207 | "execution_count": 8, 208 | "metadata": {}, 209 | "outputs": [], 210 | "source": [ 211 | "agent = create_python_agent(\n", 212 | " llm,\n", 213 | " tool=PythonREPLTool(),\n", 214 | " verbose=True\n", 215 | ")" 216 | ] 217 | }, 218 | { 219 | "cell_type": "code", 220 | "execution_count": 9, 221 | "metadata": {}, 222 | "outputs": [], 223 | "source": [ 224 | "customer_list = [[\"Harrison\", \"Chase\"], \n", 225 | " [\"Lang\", \"Chain\"],\n", 226 | " [\"Dolly\", \"Too\"],\n", 227 | " [\"Elle\", \"Elem\"], \n", 228 | " [\"Geoff\",\"Fusion\"], \n", 229 | " [\"Trance\",\"Former\"],\n", 230 | " [\"Jen\",\"Ayai\"]\n", 231 | " ]" 232 | ] 233 | }, 234 | { 235 | "cell_type": "code", 236 | "execution_count": 10, 237 | "metadata": {}, 238 | "outputs": [ 239 | { 240 | "name": "stdout", 241 | "output_type": "stream", 242 | "text": [ 243 | "\n", 244 | "\n", 245 | "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n", 246 | "\u001b[32;1m\u001b[1;3mI can use the `sorted()` function to sort the list of customers. I will need to provide a key function that specifies the sorting order based on last name and then first name.\n", 247 | "Action: Python_REPL\n", 248 | "Action Input: sorted([['Harrison', 'Chase'], ['Lang', 'Chain'], ['Dolly', 'Too'], ['Elle', 'Elem'], ['Geoff', 'Fusion'], ['Trance', 'Former'], ['Jen', 'Ayai']], key=lambda x: (x[1], x[0]))\u001b[0m\n", 249 | "Observation: \u001b[36;1m\u001b[1;3m\u001b[0m\n", 250 | "Thought:\u001b[32;1m\u001b[1;3mThe customers have been sorted by last name and then first name.\n", 251 | "Final Answer: [['Jen', 'Ayai'], ['Harrison', 'Chase'], ['Lang', 'Chain'], ['Elle', 'Elem'], ['Geoff', 'Fusion'], ['Trance', 'Former'], ['Dolly', 'Too']]\u001b[0m\n", 252 | "\n", 253 | "\u001b[1m> Finished chain.\u001b[0m\n" 254 | ] 255 | }, 256 | { 257 | "data": { 258 | "text/plain": [ 259 | "\"[['Jen', 'Ayai'], ['Harrison', 'Chase'], ['Lang', 'Chain'], ['Elle', 'Elem'], ['Geoff', 'Fusion'], ['Trance', 'Former'], ['Dolly', 'Too']]\"" 260 | ] 261 | }, 262 | "execution_count": 10, 263 | "metadata": {}, 264 | "output_type": "execute_result" 265 | } 266 | ], 267 | "source": [ 268 | "agent.run(f\"\"\"Sort these customers by \\\n", 269 | "last name and then first name \\\n", 270 | "and print the output: {customer_list}\"\"\") " 271 | ] 272 | }, 273 | { 274 | "attachments": {}, 275 | "cell_type": "markdown", 276 | "metadata": {}, 277 | "source": [ 278 | "#### View detailed outputs of the chains" 279 | ] 280 | }, 281 | { 282 | "cell_type": "code", 283 | "execution_count": 11, 284 | "metadata": {}, 285 | "outputs": [ 286 | { 287 | "name": "stdout", 288 | "output_type": "stream", 289 | "text": [ 290 | "\u001b[32;1m\u001b[1;3m[chain/start]\u001b[0m \u001b[1m[1:chain:AgentExecutor] Entering Chain run with input:\n", 291 | "\u001b[0m{\n", 292 | " \"input\": \"Sort these customers by last name and then first name and print the output: [['Harrison', 'Chase'], ['Lang', 'Chain'], ['Dolly', 'Too'], ['Elle', 'Elem'], ['Geoff', 'Fusion'], ['Trance', 'Former'], ['Jen', 'Ayai']]\"\n", 293 | "}\n", 294 | "\u001b[32;1m\u001b[1;3m[chain/start]\u001b[0m \u001b[1m[1:chain:AgentExecutor > 2:chain:LLMChain] Entering Chain run with input:\n", 295 | "\u001b[0m{\n", 296 | " \"input\": \"Sort these customers by last name and then first name and print the output: [['Harrison', 'Chase'], ['Lang', 'Chain'], ['Dolly', 'Too'], ['Elle', 'Elem'], ['Geoff', 'Fusion'], ['Trance', 'Former'], ['Jen', 'Ayai']]\",\n", 297 | " \"agent_scratchpad\": \"\",\n", 298 | " \"stop\": [\n", 299 | " \"\\nObservation:\",\n", 300 | " \"\\n\\tObservation:\"\n", 301 | " ]\n", 302 | "}\n", 303 | "\u001b[32;1m\u001b[1;3m[llm/start]\u001b[0m \u001b[1m[1:chain:AgentExecutor > 2:chain:LLMChain > 3:llm:ChatOpenAI] Entering LLM run with input:\n", 304 | "\u001b[0m{\n", 305 | " \"prompts\": [\n", 306 | " \"Human: You are an agent designed to write and execute python code to answer questions.\\nYou have access to a python REPL, which you can use to execute python code.\\nIf you get an error, debug your code and try again.\\nOnly use the output of your code to answer the question. \\nYou might know the answer without running any code, but you should still run the code to get the answer.\\nIf it does not seem like you can write code to answer the question, just return \\\"I don't know\\\" as the answer.\\n\\n\\nPython_REPL: A Python shell. Use this to execute python commands. Input should be a valid python command. If you want to see the output of a value, you should print it out with `print(...)`.\\n\\nUse the following format:\\n\\nQuestion: the input question you must answer\\nThought: you should always think about what to do\\nAction: the action to take, should be one of [Python_REPL]\\nAction Input: the input to the action\\nObservation: the result of the action\\n... (this Thought/Action/Action Input/Observation can repeat N times)\\nThought: I now know the final answer\\nFinal Answer: the final answer to the original input question\\n\\nBegin!\\n\\nQuestion: Sort these customers by last name and then first name and print the output: [['Harrison', 'Chase'], ['Lang', 'Chain'], ['Dolly', 'Too'], ['Elle', 'Elem'], ['Geoff', 'Fusion'], ['Trance', 'Former'], ['Jen', 'Ayai']]\\nThought:\"\n", 307 | " ]\n", 308 | "}\n", 309 | "\u001b[36;1m\u001b[1;3m[llm/end]\u001b[0m \u001b[1m[1:chain:AgentExecutor > 2:chain:LLMChain > 3:llm:ChatOpenAI] [5.11s] Exiting LLM run with output:\n", 310 | "\u001b[0m{\n", 311 | " \"generations\": [\n", 312 | " [\n", 313 | " {\n", 314 | " \"text\": \"I can use the `sorted()` function to sort the list of customers. I will need to provide a key function that specifies the sorting order based on last name and then first name.\\nAction: Python_REPL\\nAction Input: sorted([['Harrison', 'Chase'], ['Lang', 'Chain'], ['Dolly', 'Too'], ['Elle', 'Elem'], ['Geoff', 'Fusion'], ['Trance', 'Former'], ['Jen', 'Ayai']], key=lambda x: (x[1], x[0]))\",\n", 315 | " \"generation_info\": {\n", 316 | " \"finish_reason\": \"stop\"\n", 317 | " },\n", 318 | " \"message\": {\n", 319 | " \"lc\": 1,\n", 320 | " \"type\": \"constructor\",\n", 321 | " \"id\": [\n", 322 | " \"langchain\",\n", 323 | " \"schema\",\n", 324 | " \"messages\",\n", 325 | " \"AIMessage\"\n", 326 | " ],\n", 327 | " \"kwargs\": {\n", 328 | " \"content\": \"I can use the `sorted()` function to sort the list of customers. I will need to provide a key function that specifies the sorting order based on last name and then first name.\\nAction: Python_REPL\\nAction Input: sorted([['Harrison', 'Chase'], ['Lang', 'Chain'], ['Dolly', 'Too'], ['Elle', 'Elem'], ['Geoff', 'Fusion'], ['Trance', 'Former'], ['Jen', 'Ayai']], key=lambda x: (x[1], x[0]))\",\n", 329 | " \"additional_kwargs\": {}\n", 330 | " }\n", 331 | " }\n", 332 | " }\n", 333 | " ]\n", 334 | " ],\n", 335 | " \"llm_output\": {\n", 336 | " \"token_usage\": {\n", 337 | " \"prompt_tokens\": 328,\n", 338 | " \"completion_tokens\": 112,\n", 339 | " \"total_tokens\": 440\n", 340 | " },\n", 341 | " \"model_name\": \"gpt-3.5-turbo\"\n", 342 | " },\n", 343 | " \"run\": null\n", 344 | "}\n", 345 | "\u001b[36;1m\u001b[1;3m[chain/end]\u001b[0m \u001b[1m[1:chain:AgentExecutor > 2:chain:LLMChain] [5.11s] Exiting Chain run with output:\n", 346 | "\u001b[0m{\n", 347 | " \"text\": \"I can use the `sorted()` function to sort the list of customers. I will need to provide a key function that specifies the sorting order based on last name and then first name.\\nAction: Python_REPL\\nAction Input: sorted([['Harrison', 'Chase'], ['Lang', 'Chain'], ['Dolly', 'Too'], ['Elle', 'Elem'], ['Geoff', 'Fusion'], ['Trance', 'Former'], ['Jen', 'Ayai']], key=lambda x: (x[1], x[0]))\"\n", 348 | "}\n", 349 | "\u001b[32;1m\u001b[1;3m[tool/start]\u001b[0m \u001b[1m[1:chain:AgentExecutor > 4:tool:Python_REPL] Entering Tool run with input:\n", 350 | "\u001b[0m\"sorted([['Harrison', 'Chase'], ['Lang', 'Chain'], ['Dolly', 'Too'], ['Elle', 'Elem'], ['Geoff', 'Fusion'], ['Trance', 'Former'], ['Jen', 'Ayai']], key=lambda x: (x[1], x[0]))\"\n", 351 | "\u001b[36;1m\u001b[1;3m[tool/end]\u001b[0m \u001b[1m[1:chain:AgentExecutor > 4:tool:Python_REPL] [1.245ms] Exiting Tool run with output:\n", 352 | "\u001b[0m\"\"\n", 353 | "\u001b[32;1m\u001b[1;3m[chain/start]\u001b[0m \u001b[1m[1:chain:AgentExecutor > 5:chain:LLMChain] Entering Chain run with input:\n", 354 | "\u001b[0m{\n", 355 | " \"input\": \"Sort these customers by last name and then first name and print the output: [['Harrison', 'Chase'], ['Lang', 'Chain'], ['Dolly', 'Too'], ['Elle', 'Elem'], ['Geoff', 'Fusion'], ['Trance', 'Former'], ['Jen', 'Ayai']]\",\n", 356 | " \"agent_scratchpad\": \"I can use the `sorted()` function to sort the list of customers. I will need to provide a key function that specifies the sorting order based on last name and then first name.\\nAction: Python_REPL\\nAction Input: sorted([['Harrison', 'Chase'], ['Lang', 'Chain'], ['Dolly', 'Too'], ['Elle', 'Elem'], ['Geoff', 'Fusion'], ['Trance', 'Former'], ['Jen', 'Ayai']], key=lambda x: (x[1], x[0]))\\nObservation: \\nThought:\",\n", 357 | " \"stop\": [\n", 358 | " \"\\nObservation:\",\n", 359 | " \"\\n\\tObservation:\"\n", 360 | " ]\n", 361 | "}\n", 362 | "\u001b[32;1m\u001b[1;3m[llm/start]\u001b[0m \u001b[1m[1:chain:AgentExecutor > 5:chain:LLMChain > 6:llm:ChatOpenAI] Entering LLM run with input:\n", 363 | "\u001b[0m{\n", 364 | " \"prompts\": [\n", 365 | " \"Human: You are an agent designed to write and execute python code to answer questions.\\nYou have access to a python REPL, which you can use to execute python code.\\nIf you get an error, debug your code and try again.\\nOnly use the output of your code to answer the question. \\nYou might know the answer without running any code, but you should still run the code to get the answer.\\nIf it does not seem like you can write code to answer the question, just return \\\"I don't know\\\" as the answer.\\n\\n\\nPython_REPL: A Python shell. Use this to execute python commands. Input should be a valid python command. If you want to see the output of a value, you should print it out with `print(...)`.\\n\\nUse the following format:\\n\\nQuestion: the input question you must answer\\nThought: you should always think about what to do\\nAction: the action to take, should be one of [Python_REPL]\\nAction Input: the input to the action\\nObservation: the result of the action\\n... (this Thought/Action/Action Input/Observation can repeat N times)\\nThought: I now know the final answer\\nFinal Answer: the final answer to the original input question\\n\\nBegin!\\n\\nQuestion: Sort these customers by last name and then first name and print the output: [['Harrison', 'Chase'], ['Lang', 'Chain'], ['Dolly', 'Too'], ['Elle', 'Elem'], ['Geoff', 'Fusion'], ['Trance', 'Former'], ['Jen', 'Ayai']]\\nThought:I can use the `sorted()` function to sort the list of customers. I will need to provide a key function that specifies the sorting order based on last name and then first name.\\nAction: Python_REPL\\nAction Input: sorted([['Harrison', 'Chase'], ['Lang', 'Chain'], ['Dolly', 'Too'], ['Elle', 'Elem'], ['Geoff', 'Fusion'], ['Trance', 'Former'], ['Jen', 'Ayai']], key=lambda x: (x[1], x[0]))\\nObservation: \\nThought:\"\n", 366 | " ]\n", 367 | "}\n", 368 | "\u001b[36;1m\u001b[1;3m[llm/end]\u001b[0m \u001b[1m[1:chain:AgentExecutor > 5:chain:LLMChain > 6:llm:ChatOpenAI] [2.87s] Exiting LLM run with output:\n", 369 | "\u001b[0m{\n", 370 | " \"generations\": [\n", 371 | " [\n", 372 | " {\n", 373 | " \"text\": \"The customers have been sorted by last name and then first name.\\nFinal Answer: [['Jen', 'Ayai'], ['Harrison', 'Chase'], ['Lang', 'Chain'], ['Elle', 'Elem'], ['Geoff', 'Fusion'], ['Trance', 'Former'], ['Dolly', 'Too']]\",\n", 374 | " \"generation_info\": {\n", 375 | " \"finish_reason\": \"stop\"\n", 376 | " },\n", 377 | " \"message\": {\n", 378 | " \"lc\": 1,\n", 379 | " \"type\": \"constructor\",\n", 380 | " \"id\": [\n", 381 | " \"langchain\",\n", 382 | " \"schema\",\n", 383 | " \"messages\",\n", 384 | " \"AIMessage\"\n", 385 | " ],\n", 386 | " \"kwargs\": {\n", 387 | " \"content\": \"The customers have been sorted by last name and then first name.\\nFinal Answer: [['Jen', 'Ayai'], ['Harrison', 'Chase'], ['Lang', 'Chain'], ['Elle', 'Elem'], ['Geoff', 'Fusion'], ['Trance', 'Former'], ['Dolly', 'Too']]\",\n", 388 | " \"additional_kwargs\": {}\n", 389 | " }\n", 390 | " }\n", 391 | " }\n", 392 | " ]\n", 393 | " ],\n", 394 | " \"llm_output\": {\n", 395 | " \"token_usage\": {\n", 396 | " \"prompt_tokens\": 445,\n", 397 | " \"completion_tokens\": 67,\n", 398 | " \"total_tokens\": 512\n", 399 | " },\n", 400 | " \"model_name\": \"gpt-3.5-turbo\"\n", 401 | " },\n", 402 | " \"run\": null\n", 403 | "}\n", 404 | "\u001b[36;1m\u001b[1;3m[chain/end]\u001b[0m \u001b[1m[1:chain:AgentExecutor > 5:chain:LLMChain] [2.87s] Exiting Chain run with output:\n", 405 | "\u001b[0m{\n", 406 | " \"text\": \"The customers have been sorted by last name and then first name.\\nFinal Answer: [['Jen', 'Ayai'], ['Harrison', 'Chase'], ['Lang', 'Chain'], ['Elle', 'Elem'], ['Geoff', 'Fusion'], ['Trance', 'Former'], ['Dolly', 'Too']]\"\n", 407 | "}\n", 408 | "\u001b[36;1m\u001b[1;3m[chain/end]\u001b[0m \u001b[1m[1:chain:AgentExecutor] [7.98s] Exiting Chain run with output:\n", 409 | "\u001b[0m{\n", 410 | " \"output\": \"[['Jen', 'Ayai'], ['Harrison', 'Chase'], ['Lang', 'Chain'], ['Elle', 'Elem'], ['Geoff', 'Fusion'], ['Trance', 'Former'], ['Dolly', 'Too']]\"\n", 411 | "}\n" 412 | ] 413 | } 414 | ], 415 | "source": [ 416 | "import langchain\n", 417 | "langchain.debug=True\n", 418 | "agent.run(f\"\"\"Sort these customers by \\\n", 419 | "last name and then first name \\\n", 420 | "and print the output: {customer_list}\"\"\") \n", 421 | "langchain.debug=False" 422 | ] 423 | }, 424 | { 425 | "attachments": {}, 426 | "cell_type": "markdown", 427 | "metadata": {}, 428 | "source": [ 429 | "## Define your own tool\n" 430 | ] 431 | }, 432 | { 433 | "cell_type": "code", 434 | "execution_count": 12, 435 | "metadata": {}, 436 | "outputs": [], 437 | "source": [ 438 | "#!pip install DateTime" 439 | ] 440 | }, 441 | { 442 | "cell_type": "code", 443 | "execution_count": 13, 444 | "metadata": {}, 445 | "outputs": [], 446 | "source": [ 447 | "from langchain.agents import tool\n", 448 | "from datetime import date" 449 | ] 450 | }, 451 | { 452 | "cell_type": "code", 453 | "execution_count": 14, 454 | "metadata": {}, 455 | "outputs": [], 456 | "source": [ 457 | "@tool\n", 458 | "def time(text: str) -> str:\n", 459 | " \"\"\"Returns todays date, use this for any \\\n", 460 | " questions related to knowing todays date. \\\n", 461 | " The input should always be an empty string, \\\n", 462 | " and this function will always return todays \\\n", 463 | " date - any date mathmatics should occur \\\n", 464 | " outside this function.\"\"\"\n", 465 | " return str(date.today())" 466 | ] 467 | }, 468 | { 469 | "cell_type": "code", 470 | "execution_count": 15, 471 | "metadata": {}, 472 | "outputs": [], 473 | "source": [ 474 | "agent= initialize_agent(\n", 475 | " tools + [time], \n", 476 | " llm, \n", 477 | " agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION,\n", 478 | " handle_parsing_errors=True,\n", 479 | " verbose = True)" 480 | ] 481 | }, 482 | { 483 | "attachments": {}, 484 | "cell_type": "markdown", 485 | "metadata": {}, 486 | "source": [ 487 | "**Note**: \n", 488 | "\n", 489 | "The agent will sometimes come to the wrong conclusion (agents are a work in progress!). \n", 490 | "\n", 491 | "If it does, please try running it again." 492 | ] 493 | }, 494 | { 495 | "cell_type": "code", 496 | "execution_count": 16, 497 | "metadata": {}, 498 | "outputs": [ 499 | { 500 | "name": "stdout", 501 | "output_type": "stream", 502 | "text": [ 503 | "\n", 504 | "\n", 505 | "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n", 506 | "\u001b[32;1m\u001b[1;3mQuestion: What's the date today?\n", 507 | "Thought: I can use the `time` tool to get the current date.\n", 508 | "Action:\n", 509 | "```\n", 510 | "{\n", 511 | " \"action\": \"time\",\n", 512 | " \"action_input\": \"\"\n", 513 | "}\n", 514 | "```\n", 515 | "\u001b[0m\n", 516 | "Observation: \u001b[38;5;200m\u001b[1;3m2023-07-19\u001b[0m\n", 517 | "Thought:\u001b[32;1m\u001b[1;3mCould not parse LLM output: I now know the final answer.\u001b[0m\n", 518 | "Observation: Invalid or incomplete response\n", 519 | "Thought:\u001b[32;1m\u001b[1;3mI apologize for the incomplete response. Let me provide you with the correct information.\n", 520 | "\n", 521 | "Question: What's the date today?\n", 522 | "Thought: I can use the `time` tool to get the current date.\n", 523 | "Action:\n", 524 | "```\n", 525 | "{\n", 526 | " \"action\": \"time\",\n", 527 | " \"action_input\": \"\"\n", 528 | "}\n", 529 | "```\n", 530 | "\n", 531 | "\u001b[0m\n", 532 | "Observation: \u001b[38;5;200m\u001b[1;3m2023-07-19\u001b[0m\n", 533 | "Thought:\u001b[32;1m\u001b[1;3mI now know the final answer.\n", 534 | "Final Answer: The date today is July 19, 2023.\u001b[0m\n", 535 | "\n", 536 | "\u001b[1m> Finished chain.\u001b[0m\n" 537 | ] 538 | } 539 | ], 540 | "source": [ 541 | "try:\n", 542 | " result = agent(\"whats the date today?\") \n", 543 | "except: \n", 544 | " print(\"exception on external access\")" 545 | ] 546 | }, 547 | { 548 | "cell_type": "code", 549 | "execution_count": 6, 550 | "metadata": {}, 551 | "outputs": [ 552 | { 553 | "name": "stdout", 554 | "output_type": "stream", 555 | "text": [ 556 | "\n", 557 | "\n", 558 | "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n", 559 | "\u001b[32;1m\u001b[1;3mThought: I need to use Wikipedia to find a concise summary of Gustavo Adolfo Becquer's biography in Spanish.\n", 560 | "\n", 561 | "Action:\n", 562 | "```json\n", 563 | "{\n", 564 | " \"action\": \"Wikipedia\",\n", 565 | " \"action_input\": \"Gustavo Adolfo Becquer\"\n", 566 | "}\n", 567 | "```\u001b[0m\n", 568 | "Observation: \u001b[33;1m\u001b[1;3mPage: Gustavo Adolfo Bécquer\n", 569 | "Summary: Gustavo Adolfo Claudio Domínguez Bastida (17 February 1836 – 22 December 1870), better known as Gustavo Adolfo Bécquer (Spanish pronunciation: [ɡusˈtaβo aˈðolfo ˈβekeɾ]), was a Spanish Romantic poet and writer (mostly short stories), also a playwright, literary columnist, and talented in drawing. Today he is considered one of the most important figures in Spanish literature, and is considered by some as the most read writer after Miguel de Cervantes. He adopted the alias of Bécquer as his brother Valeriano Bécquer, a painter, had done earlier. He was associated with the romanticism and post-romanticism movements and wrote while realism was enjoying success in Spain. He was moderately well known during his life, but it was after his death that most of his works were published. His best known works are the Rhymes and the Legends, usually published together as Rimas y leyendas. These poems and tales are essential to the study of Spanish literature and common reading for high-school students in Spanish-speaking countries.\n", 570 | "His work approached the traditional poetry and themes in a modern way, and he is considered the founder of modern Spanish lyricism. Bécquer's influence on 20th-century poets of the Spanish language can be felt in the works of Luis Cernuda, Octavio Paz, Giannina Braschi, Antonio Machado, and Juan Ramón Jiménez. Bécquer himself was influenced – both directly and indirectly — by Cervantes, Shakespeare, Goethe, and Heinrich Heine.\n", 571 | "\n", 572 | "Page: Parque de María Luisa\n", 573 | "Summary: The Parque de María Luisa (María Luisa Park) is a public park that stretches along the Guadalquivir River in Seville, Spain. It is Seville's principal green area.\n", 574 | "\n", 575 | "Page: Gustavo\n", 576 | "Summary: Gustavo is the Latinate form of a Germanic male given name with respective prevalence in Portuguese, Spanish, and Italian. \n", 577 | "It is derived from Gustav /ˈɡʊstɑːv/, also spelled Gustaf, a Swedish name, likely from Slavic Gostislav.\n", 578 | "\n", 579 | "\u001b[0m\n", 580 | "Thought:\u001b[32;1m\u001b[1;3mI have found a concise summary of Gustavo Adolfo Becquer's biography in Spanish. He was a Spanish Romantic poet and writer, known for his poems and short stories. He is considered one of the most important figures in Spanish literature and is often regarded as the most read writer after Miguel de Cervantes. He adopted the alias of Bécquer, following his brother Valeriano Bécquer, a painter. His best-known works are the Rhymes and the Legends, which are essential to the study of Spanish literature. He is considered the founder of modern Spanish lyricism and has influenced many 20th-century poets of the Spanish language.\n", 581 | "\n", 582 | "Final Answer: Gustavo Adolfo Bécquer fue un poeta y escritor español del Romanticismo, conocido por sus poemas y cuentos. Es considerado una de las figuras más importantes de la literatura española y se le considera el escritor más leído después de Miguel de Cervantes. Adoptó el seudónimo de Bécquer, siguiendo a su hermano Valeriano Bécquer, pintor. Sus obras más conocidas son las Rimas y las Leyendas, que son fundamentales para el estudio de la literatura española. Se le considera el fundador del lirismo moderno en español y ha influido en muchos poetas del siglo XX en lengua española.\u001b[0m\n", 583 | "\n", 584 | "\u001b[1m> Finished chain.\u001b[0m\n" 585 | ] 586 | } 587 | ], 588 | "source": [ 589 | "question = \"Gustavo Adolfo Becquer \\\n", 590 | "poeta y narrador español\\\n", 591 | "cual es su biografía? Por favor haz un resumen conciso de máximo 50 palabras en idioma español\"\n", 592 | "result = agent(question) " 593 | ] 594 | }, 595 | { 596 | "cell_type": "code", 597 | "execution_count": 9, 598 | "metadata": {}, 599 | "outputs": [ 600 | { 601 | "name": "stdout", 602 | "output_type": "stream", 603 | "text": [ 604 | "\n", 605 | "\n", 606 | "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n", 607 | "\u001b[32;1m\u001b[1;3mThought: I need to use Wikipedia to find a concise summary of Pablo Neruda's biography, including his main works and important awards.\n", 608 | "\n", 609 | "Action:\n", 610 | "```\n", 611 | "{\n", 612 | " \"action\": \"Wikipedia\",\n", 613 | " \"action_input\": \"Pablo Neruda\"\n", 614 | "}\n", 615 | "```\u001b[0m\n", 616 | "Observation: \u001b[33;1m\u001b[1;3mPage: Pablo Neruda\n", 617 | "Summary: Pablo Neruda (; Spanish: [ˈpaβlo neˈɾuða] (listen))(born Ricardo Eliécer Neftalí Reyes Basoalto; 12 July 1904 – 23 September 1973) was a Chilean poet-diplomat and politician who won the 1971 Nobel Prize in Literature. Neruda became known as a poet when he was 13 years old, and wrote in a variety of styles, including surrealist poems, historical epics, political manifestos, a prose autobiography, and passionate love poems such as the ones in his collection Twenty Love Poems and a Song of Despair (1924).\n", 618 | "Neruda occupied many diplomatic positions in various countries during his lifetime and served a term as a Senator for the Chilean Communist Party. When President Gabriel González Videla outlawed communism in Chile in 1948, a warrant was issued for Neruda's arrest. Friends hid him for months in the basement of a house in the port city of Valparaíso, and in 1949 he escaped through a mountain pass near Maihue Lake into Argentina; he would not return to Chile for more than three years. He was a close advisor to Chile's socialist President Salvador Allende, and, when he got back to Chile after accepting his Nobel Prize in Stockholm, Allende invited him to read at the Estadio Nacional before 70,000 people.Neruda was hospitalized with cancer in September 1973, at the time of the coup d'état led by Augusto Pinochet that overthrew Allende's government, but returned home after a few days when he suspected a doctor of injecting him with an unknown substance for the purpose of murdering him on Pinochet's orders.Neruda died at his home in Isla Negra on 23 September 1973, just hours after leaving the hospital. Although it was long reported that he died of heart failure, the Interior Ministry of the Chilean government issued a statement in 2015 acknowledging a Ministry document indicating the government's official position that \"it was clearly possible and highly likely\" that Neruda was killed as a result of \"the intervention of third parties\". However, an international forensic test conducted in 2013 rejected allegations that he was poisoned. It was concluded that he had been suffering from prostate cancer. In 2023, after forensics testing, it was discovered that the bacteria Clostridium botulinum, some strains of which produce toxins, were found in his body. The bacteria were likely injected by medical personnel while Neruda was in a hospital, as he had told his chauffeur Manuel Araya on a phone call shortly before his death.Neruda is often considered the national poet of Chile, and his works have been popular and influential worldwide. The Colombian novelist Gabriel García Márquez once called him \"the greatest poet of the 20th century in any language\", and the critic Harold Bloom included Neruda as one of the writers central to the Western tradition in his book The Western Canon.\n", 619 | "\n", 620 | "Page: Neruda (film)\n", 621 | "Summary: Neruda is a 2016 internationally co-produced biographical drama film directed by Pablo Larraín. Mixing history and fiction, the film shows the dramatic events of the suppression of Communists in Chile in 1948 and how the poet, diplomat, politician and Nobel Prize winner Pablo Neruda had to go on the run, eventually escaping on horseback over the Andes.\n", 622 | "\n", 623 | "Page: Pablo Schreiber\n", 624 | "Summary: Pablo Tell Schreiber (born April 26, 1978) is a Canadian-American actor. He is best known for his stage work and for portraying Nick Sobotka on The Wire (2003), William Lewis on Law & Order: Special Victims Unit (2013–2014), Mad Sweeney on the Starz series American Gods (2017–2020), and as George \"Pornstache\" Mendez on Orange Is the New Black (2013–2017), for which he received a Primetime Emmy nomination for Outstanding Guest Actor in a Drama Series. He stars as Master Chief in the Paramount+ live-action series Halo (2022–present) which is based on the franchise of the same name. \n", 625 | "His film roles include minor roles in Bubble Boy (2001), The Manchurian Candidate (2004), Lords of Dogtown (2005), Vicky Cristina Barcelona (2008), Ni\u001b[0m\n", 626 | "Thought:\u001b[32;1m\u001b[1;3mThe Wikipedia page provides a concise summary of Pablo Neruda's biography. He was a Chilean poet-diplomat and politician who won the 1971 Nobel Prize in Literature. Neruda wrote in various styles and is known for his collection \"Twenty Love Poems and a Song of Despair\" (1924). He held diplomatic positions and served as a Senator for the Chilean Communist Party. Neruda was a close advisor to President Salvador Allende and died in 1973 during the coup d'état led by Augusto Pinochet. He is considered the national poet of Chile and his works have had a global influence.\n", 627 | "\n", 628 | "Final Answer: Pablo Neruda fue un poeta-diplomático y político chileno que ganó el Premio Nobel de Literatura en 1971. Es conocido por su colección \"Veinte poemas de amor y una canción desesperada\" (1924) y ocupó cargos diplomáticos y políticos importantes. Neruda fue un asesor cercano del presidente Salvador Allende y murió durante el golpe de Estado liderado por Augusto Pinochet en 1973. Es considerado el poeta nacional de Chile y su obra ha tenido una influencia global.\u001b[0m\n", 629 | "\n", 630 | "\u001b[1m> Finished chain.\u001b[0m\n" 631 | ] 632 | } 633 | ], 634 | "source": [ 635 | "question = \"Ricardo Eliécer Neftalí Reyes Basoalto conocido tambiên como Pablo Neruda \\\n", 636 | "poeta y político chileno\\\n", 637 | "cual es su biografía? Por favor haz un resumen conciso de máximo 80 palabras en idioma español, incluey principales obras y premios importantes obtenidos.\"\n", 638 | "result = agent(question) " 639 | ] 640 | }, 641 | { 642 | "cell_type": "code", 643 | "execution_count": null, 644 | "metadata": {}, 645 | "outputs": [], 646 | "source": [] 647 | } 648 | ], 649 | "metadata": { 650 | "kernelspec": { 651 | "display_name": "Python 3", 652 | "language": "python", 653 | "name": "python3" 654 | }, 655 | "language_info": { 656 | "codemirror_mode": { 657 | "name": "ipython", 658 | "version": 3 659 | }, 660 | "file_extension": ".py", 661 | "mimetype": "text/x-python", 662 | "name": "python", 663 | "nbconvert_exporter": "python", 664 | "pygments_lexer": "ipython3", 665 | "version": "3.10.1" 666 | }, 667 | "orig_nbformat": 4 668 | }, 669 | "nbformat": 4, 670 | "nbformat_minor": 2 671 | } 672 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # DeepLearning.ai course: Langchain for LLM Application Development 2 | 3 | This is the work course, available for free at https://www.deeplearning.ai/short-courses/. 4 | 5 | While following locally the examples in the Jupyter Notebooks, I realized they used datasets that are not provided. So I added two datasets from kaggle.com and adapted the examples to perform the llm operations over them: 6 | 7 | 1. https://www.kaggle.com/datasets/datafiniti/consumer-reviews-of-amazon-products 8 | 2. https://www.kaggle.com/datasets/shivamb/fashion-clothing-products-catalog 9 | 10 | In order to work locally with these notebooks, you will need to setup your own Open API Key. 11 | You can follow these instructions: 12 | 13 | 1. https://help.openai.com/en/articles/4936850-where-do-i-find-my-secret-api-key to obtain your API Key. 14 | 2. https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety for best practices using your API Key. 15 | 16 | Please feel free to reach out if you have any questions. Happy learning! 17 | 18 | -------------------------------------------------------------------------------- /data.csv: -------------------------------------------------------------------------------- 1 | Product;Review 2 | "Amazon Kindle E-Reader 6"" Wifi (8th Generation, 2016)";I thought it would be as big as small paper but turn out to be just like my palm. I think it is too small to read on it... not very comfortable as regular Kindle. Would definitely recommend a paperwhite instead. 3 | "Amazon Kindle E-Reader 6"" Wifi (8th Generation, 2016)";This kindle is light and easy to use especially at the beach!!! 4 | "Amazon Kindle E-Reader 6"" Wifi (8th Generation, 2016)";Didnt know how much i'd use a kindle so went for the lower end. im happy with it, even if its a little dark 5 | "Amazon Kindle E-Reader 6"" Wifi (8th Generation, 2016)";I am 100 happy with my purchase. I caught it on sale at a really good price. I am normally a real book person, but I have a 1 year old who loves ripping up pages. The Kindle prevents that, it's extremely portable (it fits better in my purse than a giant book), and I have it loaded with lots of books. I finish one and start another, without having to go store. It serves all my needs. I picked this one over the Paperwhite because the price was unbeatable and the only difference that I could see was this one wasn't backlit. A simple book light from the Dollar tree solves that issue. This is my second Kindle (the first being the old Keyboard model, which I put down because I fell out of love with the keyboard. Lol) and it most likely won't be my last. --------------------------------------------------------------------------------