Spaces:
Running
Running
File size: 32,733 Bytes
adaea7c 59c68f8 adaea7c 59c68f8 adaea7c 59c68f8 adaea7c 59c68f8 adaea7c 59c68f8 adaea7c 59c68f8 adaea7c 59c68f8 adaea7c 59c68f8 adaea7c 59c68f8 adaea7c 59c68f8 adaea7c 59c68f8 adaea7c 59c68f8 adaea7c 59c68f8 adaea7c 59c68f8 adaea7c 59c68f8 adaea7c 59c68f8 adaea7c 59c68f8 adaea7c 59c68f8 adaea7c 59c68f8 adaea7c 59c68f8 adaea7c 59c68f8 adaea7c 59c68f8 adaea7c 59c68f8 adaea7c 59c68f8 adaea7c 59c68f8 adaea7c 59c68f8 adaea7c 59c68f8 adaea7c 59c68f8 adaea7c 59c68f8 adaea7c 59c68f8 adaea7c 59c68f8 adaea7c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 |
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# lchain_tool\n",
"\n",
"> Exploring Langchain Tool capabilities"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#| default_exp lchain_tool"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#| hide\n",
"from nbdev.showdoc import *"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#| export\n",
"import os\n",
"\n",
"from IPython.display import Image\n",
"from langchain.agents import AgentType, Tool, initialize_agent, load_tools, tool\n",
"from langchain.agents.agent_toolkits import create_python_agent\n",
"from langchain.chat_models import ChatOpenAI\n",
"from langchain.python import PythonREPL\n",
"from langchain.tools.python.tool import PythonREPLTool\n",
"from langchain.utilities import GoogleSerperAPIWrapper, SerpAPIWrapper\n",
"from serpapi import GoogleSearch"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from dotenv import load_dotenv"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": null,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"load_dotenv()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"llm = ChatOpenAI(temperature=0)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"tools = load_tools([\"llm-math\"], llm=llm)\n",
"agent = initialize_agent(\n",
" tools,\n",
" llm,\n",
" agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION,\n",
" handle_parsing_errors=True,\n",
" verbose=True,\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3mWe can calculate this using the Calculator tool.\n",
"\n",
"Action:\n",
"```\n",
"{\n",
" \"action\": \"Calculator\",\n",
" \"action_input\": \"0.03 * 300 * 30\"\n",
"}\n",
"```\n",
"\n",
"\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3mAnswer: 270.0\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3mCould not parse LLM output: This is the correct answer to the question.\u001b[0m\n",
"Observation: Invalid or incomplete response\n",
"Thought:\u001b[32;1m\u001b[1;3mLet me try the same action again.\n",
"\n",
"Action:\n",
"```\n",
"{\n",
" \"action\": \"Calculator\",\n",
" \"action_input\": \"0.03 * 300 * 30\"\n",
"}\n",
"```\n",
"\n",
"\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3mAnswer: 270.0\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3mCould not parse LLM output: The tool gave the same answer, so I can be confident that it is correct.\n",
"\u001b[0m\n",
"Observation: Invalid or incomplete response\n",
"Thought:\u001b[32;1m\u001b[1;3mThere seems to be an issue with the LLM response. Let me try a different way to calculate the answer.\n",
"\n",
"Action:\n",
"```\n",
"{\n",
" \"action\": \"Calculator\",\n",
" \"action_input\": \"300 * 30 * 0.03\"\n",
"}\n",
"```\n",
"\n",
"\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3mAnswer: 270.0\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3mI have successfully calculated the answer to the question using the calculator tool.\n",
"\n",
"Final Answer: 270.0\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n"
]
},
{
"data": {
"text/plain": [
"{'input': 'What is the 3% of of 300 * 30?', 'output': '270.0'}"
]
},
"execution_count": null,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"agent(\"What is the 3% of of 300 * 30?\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[SerpAPI Google Images](https://python.langchain.com/en/latest/modules/agents/tools/examples/google_serper.html#searching-for-google-images)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[{'title': 'Easy Tofu Pad Thai',\n",
" 'link': 'https://minimalistbaker.com/easy-tofu-pad-thai/',\n",
" 'source': 'Minimalist Baker',\n",
" 'rating': 4.9,\n",
" 'reviews': 117,\n",
" 'total_time': '30 min',\n",
" 'ingredients': ['Pad thai rice',\n",
" 'peanut sauce',\n",
" 'thai red',\n",
" 'soy sauce',\n",
" 'bean sprouts']},\n",
" {'title': 'Vegan Pad Thai',\n",
" 'link': 'https://www.noracooks.com/vegan-pad-thai/',\n",
" 'source': 'Nora Cooks',\n",
" 'rating': 5.0,\n",
" 'reviews': 53,\n",
" 'total_time': '30 min',\n",
" 'ingredients': ['Stir fry rice',\n",
" 'mung bean sprouts',\n",
" 'soy sauce',\n",
" 'maple syrup',\n",
" 'sriracha hot sauce']},\n",
" {'title': 'Vegan Pad Thai',\n",
" 'link': 'https://www.pickuplimes.com/recipe/speedy-vegan-pad-thai-116',\n",
" 'source': 'Pick Up Limes',\n",
" 'rating': 5.0,\n",
" 'reviews': 34,\n",
" 'total_time': '30 min',\n",
" 'ingredients': ['Brown rice noodles',\n",
" 'red hot',\n",
" 'soy sauce',\n",
" 'bean sprouts',\n",
" 'sriracha hot sauce']}]"
]
},
"execution_count": null,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"params = {\n",
" \"q\": \"Vegan pad thai recipes\",\n",
" \"location\": \"United States\",\n",
" \"hl\": \"en\",\n",
" \"gl\": \"us\",\n",
" \"api_key\": os.environ[\"SERPAPI_API_KEY\"],\n",
"}\n",
"\n",
"search = GoogleSearch(params)\n",
"results = search.get_dict()\n",
"recipes_results = results[\"recipes_results\"]\n",
"recipes_results"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [
{
"data": {
"text/markdown": [
"---\n",
"\n",
"### SerpAPIWrapper\n",
"\n",
"> SerpAPIWrapper (search_engine:Any=None, params:dict={'engine': 'google',\n",
"> 'google_domain': 'google.com', 'gl': 'us', 'hl': 'en'},\n",
"> serpapi_api_key:Optional[str]=None,\n",
"> aiosession:Optional[aiohttp.client.ClientSession]=None)\n",
"\n",
"Wrapper around SerpAPI.\n",
"\n",
"To use, you should have the ``google-search-results`` python package installed,\n",
"and the environment variable ``SERPAPI_API_KEY`` set with your API key, or pass\n",
"`serpapi_api_key` as a named parameter to the constructor.\n",
"\n",
"Example:\n",
" .. code-block:: python\n",
"\n",
" from langchain import SerpAPIWrapper\n",
" serpapi = SerpAPIWrapper()"
],
"text/plain": [
"---\n",
"\n",
"### SerpAPIWrapper\n",
"\n",
"> SerpAPIWrapper (search_engine:Any=None, params:dict={'engine': 'google',\n",
"> 'google_domain': 'google.com', 'gl': 'us', 'hl': 'en'},\n",
"> serpapi_api_key:Optional[str]=None,\n",
"> aiosession:Optional[aiohttp.client.ClientSession]=None)\n",
"\n",
"Wrapper around SerpAPI.\n",
"\n",
"To use, you should have the ``google-search-results`` python package installed,\n",
"and the environment variable ``SERPAPI_API_KEY`` set with your API key, or pass\n",
"`serpapi_api_key` as a named parameter to the constructor.\n",
"\n",
"Example:\n",
" .. code-block:: python\n",
"\n",
" from langchain import SerpAPIWrapper\n",
" serpapi = SerpAPIWrapper()"
]
},
"execution_count": null,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"show_doc(SerpAPIWrapper)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#| export\n",
"class RecipeSerpAPIWrapper(SerpAPIWrapper):\n",
" @staticmethod\n",
" def _process_response(res: dict) -> str:\n",
" \"\"\"Process response from SerpAPI.\"\"\"\n",
" if \"error\" in res.keys():\n",
" raise ValueError(f\"Got error from SerpAPI: {res['error']}\")\n",
" if \"recipes_results\" in res.keys():\n",
" return res[\"recipes_results\"]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"params = {\n",
" \"location\": \"United States\",\n",
" \"hl\": \"en\",\n",
" \"gl\": \"us\",\n",
"}\n",
"search = RecipeSerpAPIWrapper(params=params)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[{'title': 'Easy Vegan Fried Rice',\n",
" 'link': 'https://minimalistbaker.com/easy-vegan-fried-rice/',\n",
" 'source': 'Minimalist Baker',\n",
" 'rating': 4.8,\n",
" 'reviews': 457,\n",
" 'total_time': '1 hr 15 min',\n",
" 'ingredients': ['Peanut butter',\n",
" 'grain brown rice',\n",
" 'soy sauce',\n",
" 'maple syrup',\n",
" 'chili garlic sauce']},\n",
" {'title': 'The Best Vegan Fried Rice',\n",
" 'link': 'https://shortgirltallorder.com/best-vegan-fried-rice',\n",
" 'source': 'Short Girl Tall Order',\n",
" 'rating': 4.8,\n",
" 'reviews': 65,\n",
" 'total_time': '28 min',\n",
" 'ingredients': ['Soy sauce',\n",
" 'white rice',\n",
" 'rice wine vinegar',\n",
" 'sugar',\n",
" 'fresh peas']},\n",
" {'title': 'Vegan Fried Rice',\n",
" 'link': 'https://www.noracooks.com/vegan-fried-rice/',\n",
" 'source': 'Nora Cooks',\n",
" 'rating': 5.0,\n",
" 'reviews': 15,\n",
" 'total_time': '20 min',\n",
" 'ingredients': ['Gluten free',\n",
" 'nutritional yeast',\n",
" 'toasted sesame oil',\n",
" 'carrots',\n",
" 'olive oil']}]"
]
},
"execution_count": null,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"vegan_recipes = search.run(\"Vegan fried rice recipes\")\n",
"vegan_recipes[0:3]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"params = {\n",
" \"engine\": \"google_images\",\n",
" \"q\": \"Vegan pad thai recipes\",\n",
" \"location\": \"United States\",\n",
" \"api_key\": os.environ[\"SERPAPI_API_KEY\"],\n",
"}\n",
"\n",
"search = GoogleSearch(params)\n",
"results = search.get_dict()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'Easy Tofu Pad Thai (Vegan) | Minimalist Baker Recipes'"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/plain": [
"'https://minimalistbaker.com/easy-tofu-pad-thai/'"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
"<img src=\"https://serpapi.com/searches/6480db18c56d93170a8e715f/images/6f34b4708ae4dd36a28ca4ca4a3abf6af168f575eef7bd2e8f81a12e175fcf53.jpeg\"/>"
],
"text/plain": [
"<IPython.core.display.Image object>"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/plain": [
"'Healthier vegan pad thai - Lazy Cat Kitchen'"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/plain": [
"'https://www.lazycatkitchen.com/healthier-vegan-pad-thai/'"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
"<img src=\"https://serpapi.com/searches/6480db18c56d93170a8e715f/images/6f34b4708ae4dd36dee6fed89369c822a79ad529f726d1a65fdd09459c0a0b6a.jpeg\"/>"
],
"text/plain": [
"<IPython.core.display.Image object>"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/plain": [
"'The Best Vegan Pad Thai - Full of Plants'"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/plain": [
"'https://fullofplants.com/the-best-vegan-pad-thai/'"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
"<img src=\"https://serpapi.com/searches/6480db18c56d93170a8e715f/images/6f34b4708ae4dd3695828a207980e4280bb4e14cdccb84ebf5350f19237416f8.jpeg\"/>"
],
"text/plain": [
"<IPython.core.display.Image object>"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/plain": [
"'Easy Vegan Pad Thai - Oh My Veggies'"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/plain": [
"'https://ohmyveggies.com/easy-vegan-pad-thai/'"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
"<img src=\"https://serpapi.com/searches/6480db18c56d93170a8e715f/images/6f34b4708ae4dd36885ca51553e15b434e41039ef307ecbb4869522eeeefcfa5.jpeg\"/>"
],
"text/plain": [
"<IPython.core.display.Image object>"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/plain": [
"'Easy Vegan Pad Thai - My Darling Vegan'"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/plain": [
"'https://www.mydarlingvegan.com/vegan-pad-thai/'"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
"<img src=\"https://serpapi.com/searches/6480db18c56d93170a8e715f/images/6f34b4708ae4dd36a554bfded8055a9df50470d25fe62e19b9de5f16e262497f.jpeg\"/>"
],
"text/plain": [
"<IPython.core.display.Image object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"for r in results[\"images_results\"][0:5]:\n",
" display(r[\"title\"], r[\"link\"], Image(url=r[\"thumbnail\"]))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [
{
"data": {
"text/markdown": [
"---\n",
"\n",
"### load_tools\n",
"\n",
"> load_tools (tool_names:List[str],\n",
"> llm:Optional[langchain.base_language.BaseLanguageModel]=None,\n",
"> callbacks:Union[List[langchain.callbacks.base.BaseCallbackHan\n",
"> dler],langchain.callbacks.base.BaseCallbackManager,NoneType]=\n",
"> None, **kwargs:Any)\n",
"\n",
"Load tools based on their name.\n",
"\n",
"Args:\n",
" tool_names: name of tools to load.\n",
" llm: Optional language model, may be needed to initialize certain tools.\n",
" callbacks: Optional callback manager or list of callback handlers.\n",
" If not provided, default global callback manager will be used.\n",
"\n",
"Returns:\n",
" List of tools."
],
"text/plain": [
"---\n",
"\n",
"### load_tools\n",
"\n",
"> load_tools (tool_names:List[str],\n",
"> llm:Optional[langchain.base_language.BaseLanguageModel]=None,\n",
"> callbacks:Union[List[langchain.callbacks.base.BaseCallbackHan\n",
"> dler],langchain.callbacks.base.BaseCallbackManager,NoneType]=\n",
"> None, **kwargs:Any)\n",
"\n",
"Load tools based on their name.\n",
"\n",
"Args:\n",
" tool_names: name of tools to load.\n",
" llm: Optional language model, may be needed to initialize certain tools.\n",
" callbacks: Optional callback manager or list of callback handlers.\n",
" If not provided, default global callback manager will be used.\n",
"\n",
"Returns:\n",
" List of tools."
]
},
"execution_count": null,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"show_doc(load_tools)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here is the SerpAPIWrapper tool implementation"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from langchain.agents.load_tools import _get_serpapi"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"\u001b[0;31mSignature:\u001b[0m \u001b[0m_get_serpapi\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0mAny\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;34m->\u001b[0m \u001b[0mlangchain\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mtools\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mbase\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mBaseTool\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;31mDocstring:\u001b[0m <no docstring>\n",
"\u001b[0;31mSource:\u001b[0m \n",
"\u001b[0;32mdef\u001b[0m \u001b[0m_get_serpapi\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0mAny\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;34m->\u001b[0m \u001b[0mBaseTool\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mTool\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mname\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;34m\"Search\"\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mdescription\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;34m\"A search engine. Useful for when you need to answer questions about current events. Input should be a search query.\"\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mfunc\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mSerpAPIWrapper\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mrun\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0mcoroutine\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mSerpAPIWrapper\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0marun\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\n",
"\u001b[0;34m\u001b[0m \u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;31mFile:\u001b[0m ~/AnimalEquality/lv-recipe-chatbot/env/lib/python3.10/site-packages/langchain/agents/load_tools.py\n",
"\u001b[0;31mType:\u001b[0m function"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"??_get_serpapi"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's use that for inspiration for our recipe version of the tool"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"params = {\n",
" \"location\": \"United States\",\n",
" \"hl\": \"en\",\n",
" \"gl\": \"us\",\n",
"}\n",
"search = RecipeSerpAPIWrapper(params=params)\n",
"serpapi_recipe_tool = Tool(\n",
" name=\"Vegan Recipe Search\",\n",
" description=\"A search engine. Useful for when you need to fetch existing vetted vegan recipes. Input should be a vegan recipe search query.\",\n",
" func=search.run,\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"@tool\n",
"def time(text: str) -> str:\n",
" \"\"\"Returns todays date, use this for any\n",
" questions related to knowing todays date.\n",
" The input should always be an empty string,\n",
" and this function will always return todays\n",
" date - any date mathmatics should occur\n",
" outside this function.\"\"\"\n",
" return str(date.today())"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"agent = initialize_agent(\n",
" [time],\n",
" llm,\n",
" agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION,\n",
" handle_parsing_errors=True,\n",
" verbose=True,\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"@tool\n",
"def vegan_recipe_search_serpapi(text: str) -> str:\n",
" \"\"\"Returns a JSON/Python list of dictionaries of recipe data with keys in format:\n",
" ```\n",
" 'title': str,\n",
" 'link': str,\n",
" 'source': str,\n",
" 'rating': int,\n",
" 'reviews': int,\n",
" 'total_time': str,\n",
" 'ingredients': [\n",
" str,\n",
" str,\n",
" ```\n",
" The input must be the name of a vegan recipe \\\n",
" or query parameters such as ingredients to include, prep time, cuisine region. \\\n",
" Only execute the search for vegan recipes and ingredients. \\\n",
" If the SerpAPI request errors or recipes are not found, \\\n",
" an explanation message will be returned instead of the recipe JSON.\"\"\"\n",
" params = {\n",
" \"q\": text,\n",
" \"location\": \"United States\",\n",
" \"hl\": \"en\",\n",
" \"gl\": \"us\",\n",
" \"api_key\": os.environ[\"SERPAPI_API_KEY\"],\n",
" }\n",
"\n",
" search = GoogleSearch(params)\n",
" results = search.get_dict()\n",
" if \"error\" in results.keys():\n",
" return f\"Received an error from SerpAPI: {results['error']}\\n Query: {text}\"\n",
"\n",
" if \"recipes_results\" in results.keys():\n",
" return str(results[\"recipes_results\"])\n",
"\n",
" return \"No recipes found for that query\""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Create an agent with the tool"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"agent = initialize_agent(\n",
" tools=[vegan_recipe_serpapi_search],\n",
" llm=llm,\n",
" agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION,\n",
" handle_parsing_errors=True,\n",
" verbose=True,\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3mThought: I can use the `vegan_recipe_serpapi_search` tool to search for vegan pad thai recipes.\n",
"\n",
"Action:\n",
"```\n",
"{\n",
" \"action\": \"vegan_recipe_serpapi_search\",\n",
" \"action_input\": \"vegan pad thai\"\n",
"}\n",
"```\n",
"\n",
"\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3m[{'title': 'Vegan Pad Thai', 'link': 'https://www.noracooks.com/vegan-pad-thai/', 'source': 'Nora Cooks', 'rating': 5.0, 'reviews': 53, 'total_time': '30 min', 'ingredients': ['Stir fry rice', 'mung bean sprouts', 'soy sauce', 'maple syrup', 'sriracha hot sauce']}, {'title': 'Easy Tofu Pad Thai', 'link': 'https://minimalistbaker.com/easy-tofu-pad-thai/', 'source': 'Minimalist Baker', 'rating': 4.9, 'reviews': 117, 'total_time': '30 min', 'ingredients': ['Pad thai rice', 'peanut sauce', 'thai red', 'soy sauce', 'bean sprouts']}, {'title': 'Vegan Pad Thai', 'link': 'https://www.pickuplimes.com/recipe/speedy-vegan-pad-thai-116', 'source': 'Pick Up Limes', 'rating': 5.0, 'reviews': 34, 'total_time': '30 min', 'ingredients': ['Brown rice noodles', 'red hot', 'soy sauce', 'bean sprouts', 'sriracha hot sauce']}]\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3mCould not parse LLM output: The `vegan_recipe_serpapi_search` tool returned a list of three vegan pad thai recipes with their titles, links, sources, ratings, reviews, total time, and ingredients.\u001b[0m\n",
"Observation: Invalid or incomplete response\n",
"Thought:\u001b[32;1m\u001b[1;3mI will try running the `vegan_recipe_serpapi_search` tool again with the input \"vegan pad thai\".\n",
"\n",
"Action:\n",
"```\n",
"{\n",
" \"action\": \"vegan_recipe_serpapi_search\",\n",
" \"action_input\": \"vegan pad thai\"\n",
"}\n",
"```\n",
"\n",
"\n",
"\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3m[{'title': 'Vegan Pad Thai', 'link': 'https://www.noracooks.com/vegan-pad-thai/', 'source': 'Nora Cooks', 'rating': 5.0, 'reviews': 53, 'total_time': '30 min', 'ingredients': ['Stir fry rice', 'mung bean sprouts', 'soy sauce', 'maple syrup', 'sriracha hot sauce']}, {'title': 'Easy Tofu Pad Thai', 'link': 'https://minimalistbaker.com/easy-tofu-pad-thai/', 'source': 'Minimalist Baker', 'rating': 4.9, 'reviews': 117, 'total_time': '30 min', 'ingredients': ['Pad thai rice', 'peanut sauce', 'thai red', 'soy sauce', 'bean sprouts']}, {'title': 'Vegan Pad Thai', 'link': 'https://www.pickuplimes.com/recipe/speedy-vegan-pad-thai-116', 'source': 'Pick Up Limes', 'rating': 5.0, 'reviews': 34, 'total_time': '30 min', 'ingredients': ['Brown rice noodles', 'red hot', 'soy sauce', 'bean sprouts', 'sriracha hot sauce']}]\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3mCould not parse LLM output: The `vegan_recipe_serpapi_search` tool returned a list of three vegan pad thai recipes with their titles, links, sources, ratings, reviews, total time, and ingredients.\n",
"\u001b[0m\n",
"Observation: Invalid or incomplete response\n",
"Thought:\u001b[32;1m\u001b[1;3mI will try running the `vegan_recipe_serpapi_search` tool again with the input \"vegan pad thai recipes\".\n",
"\n",
"Action:\n",
"```\n",
"{\n",
" \"action\": \"vegan_recipe_serpapi_search\",\n",
" \"action_input\": \"vegan pad thai recipes\"\n",
"}\n",
"```\n",
"\n",
"\n",
"\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3m[{'title': 'Easy Tofu Pad Thai', 'link': 'https://minimalistbaker.com/easy-tofu-pad-thai/', 'source': 'Minimalist Baker', 'rating': 4.9, 'reviews': 117, 'total_time': '30 min', 'ingredients': ['Pad thai rice', 'peanut sauce', 'thai red', 'soy sauce', 'bean sprouts']}, {'title': 'Vegan Pad Thai', 'link': 'https://www.noracooks.com/vegan-pad-thai/', 'source': 'Nora Cooks', 'rating': 5.0, 'reviews': 53, 'total_time': '30 min', 'ingredients': ['Stir fry rice', 'mung bean sprouts', 'soy sauce', 'maple syrup', 'sriracha hot sauce']}, {'title': 'Vegan Pad Thai', 'link': 'https://www.pickuplimes.com/recipe/speedy-vegan-pad-thai-116', 'source': 'Pick Up Limes', 'rating': 5.0, 'reviews': 34, 'total_time': '30 min', 'ingredients': ['Brown rice noodles', 'red hot', 'soy sauce', 'bean sprouts', 'sriracha hot sauce']}]\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3mCould not parse LLM output: I have successfully used the `vegan_recipe_serpapi_search` tool to search for vegan pad thai recipes. The tool returned a list of three vegan pad thai recipes with their titles, links, sources, ratings, reviews, total time, and ingredients.\n",
"\n",
"\u001b[0m\n",
"Observation: Invalid or incomplete response\n",
"Thought:\u001b[32;1m\u001b[1;3mI will try running the `vegan_recipe_serpapi_search` tool again with the input \"vegan pad thai recipe\".\n",
"\n",
"Action:\n",
"```\n",
"{\n",
" \"action\": \"vegan_recipe_serpapi_search\",\n",
" \"action_input\": \"vegan pad thai recipe\"\n",
"}\n",
"```\n",
"\n",
"\n",
"\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3m[{'title': 'Easy Tofu Pad Thai', 'link': 'https://minimalistbaker.com/easy-tofu-pad-thai/', 'source': 'Minimalist Baker', 'rating': 4.9, 'reviews': 117, 'total_time': '30 min', 'ingredients': ['Pad thai rice', 'peanut sauce', 'thai red', 'soy sauce', 'bean sprouts']}, {'title': 'Vegan Pad Thai', 'link': 'https://www.noracooks.com/vegan-pad-thai/', 'source': 'Nora Cooks', 'rating': 5.0, 'reviews': 53, 'total_time': '30 min', 'ingredients': ['Stir fry rice', 'mung bean sprouts', 'soy sauce', 'maple syrup', 'sriracha hot sauce']}, {'title': 'Vegan Pad Thai', 'link': 'https://www.pickuplimes.com/recipe/speedy-vegan-pad-thai-116', 'source': 'Pick Up Limes', 'rating': 5.0, 'reviews': 34, 'total_time': '30 min', 'ingredients': ['Brown rice noodles', 'red hot', 'soy sauce', 'bean sprouts', 'sriracha hot sauce']}]\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3mCould not parse LLM output: I have successfully used the `vegan_recipe_serpapi_search` tool to search for vegan pad thai recipes. The tool returned a list of three vegan pad thai recipes with their titles, links, sources, ratings, reviews, total time, and ingredients. \n",
"\n",
"Final Answer: Here are three vegan pad thai recipes: \n",
"1. Easy Tofu Pad Thai from Minimalist Baker\n",
"2. Vegan Pad Thai from Nora Cooks\n",
"3. Vegan Pad Thai from Pick Up Limes.\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n"
]
},
{
"data": {
"text/plain": [
"'Here are three vegan pad thai recipes: \\n1. Easy Tofu Pad Thai from Minimalist Baker\\n2. Vegan Pad Thai from Nora Cooks\\n3. Vegan Pad Thai from Pick Up Limes.'"
]
},
"execution_count": null,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"agent.run(\"Search vegan pad thai recipes\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This doc should be corrected [LangChain serpapi doc could be updated](https://python.langchain.com/en/latest/modules/agents/tools/examples/serpapi.html)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"search = GoogleSerperAPIWrapper(type=\"search\")\n",
"results = search.results(\"Lion\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[edamam](https://www.edamam.com/)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#| hide\n",
"import nbdev\n",
"\n",
"nbdev.nbdev_export()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "python3",
"language": "python",
"name": "python3"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
|