File size: 44,647 Bytes
fc341bd |
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 |
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "72ef7057",
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"/Users/harshitsundriyal/Library/Python/3.9/lib/python/site-packages/urllib3/__init__.py:35: NotOpenSSLWarning: urllib3 v2 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with 'LibreSSL 2.8.3'. See: https://github.com/urllib3/urllib3/issues/3020\n",
" warnings.warn(\n"
]
}
],
"source": [
"import os\n",
"from dotenv import load_dotenv\n",
"from langchain_groq import ChatGroq\n",
"from langchain.prompts import PromptTemplate"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "11b5a125",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from langgraph.graph import START, StateGraph, MessagesState\n",
"from langgraph.prebuilt import (tools_condition,\n",
" ToolNode)\n",
"from langchain_groq import ChatGroq\n",
"from langchain_huggingface import HuggingFaceEmbeddings, ChatHuggingFace, HuggingFaceEndpoint\n",
"from langchain_community.tools.tavily_search import TavilySearchResults\n",
"from langchain_core.messages import SystemMessage, HumanMessage\n",
"from langchain.tools import tool\n",
"from langchain_community.document_loaders import (\n",
" WikipediaLoader,\n",
" GoogleDriveLoader,\n",
" ArxivLoader)\n",
"\n",
"\n",
"load_dotenv()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "f55a2a45",
"metadata": {},
"outputs": [],
"source": [
"llm = ChatGroq(\n",
" temperature=0,\n",
" model_name=\"qwen-qwq-32b\", # Updated to working model\n",
" groq_api_key=os.getenv(\"GROQ_API_KEY\")\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "5d9243b4",
"metadata": {},
"outputs": [],
"source": [
"# Initialize Tavily tool\n",
"search_tool = TavilySearchResults()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "b4c2d3fb",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Tavily Search Results:\n",
"[{'title': 'What is the capital of India? States and union territories explained.', 'url': 'https://www.usatoday.com/story/news/world/2023/05/24/what-is-the-capital-of-india/70195720007/', 'content': 'Want to learn more about the soon-to-be most populous country? Here’s some interesting information about how India is organized.\\n\\nWhat is the capital of India?\\n\\nThe capital of India is New Delhi, located in the north-central part of the country to the west of the Yamuna River.\\n\\nCalcutta (now Kolkata, the capital of West Bengal) was the country’s capital until 1911 when King George V declared Delhi the new capital and construction of New Delhi began. [...] When the national government achieved independence in 1947, New Delhi became the capital.\\n\\nMumbai, the state capital of Maharashtra, is often considered the financial capital of India because of its role in the national and international economy.\\n\\nHow many states are in India?\\n\\nIndia is home to 28 states, each with its own capital and run by a Governor who represents the President:\\n\\nIndia also has eight union territories, governed by an Administrator appointed by the President: [...] What state is New Delhi in?\\n\\nNew Delhi is part of one of India’s union territories, the National Capital Territory of Dehli. Old Delhi, now a historic city, is north of New Delhi in the same union territory.', 'score': 0.942385}, {'title': 'List of capitals of India - Wikipedia', 'url': 'https://en.wikipedia.org/wiki/List_of_capitals_of_India', 'content': 'Find sources:\\xa0\"List of capitals of India\"\\xa0–\\xa0news\\xa0· newspapers\\xa0· books\\xa0· scholar\\xa0· JSTOR (September 2012) (Learn how and when to remove this message)\\nThis is a list of locations which have served as capital cities in India. The current capital city is New Delhi, which replaced Calcutta in 1911.\\nAncient period[edit]\\nRajgir: Initial capital of the Magadha Empire from 6th century BCE to 460 BCE, called Girivraj at the time. [1] [...] In 1858, Allahabad (now Prayagraj) became the capital of India for a day when it also served as the capital of North-Western Provinces.[3]\\nDuring the British Raj, until 1911, Calcutta was the capital of India.[4]\\nBy the latter half of the 19th century, Shimla had become the summer capital.[5] [...] King George V proclaimed the transfer of the capital from Calcutta to Delhi at the climax of the 1911 Delhi Durbar on 12 December 1911. The buildings housing the Viceroy, government, and parliament were inaugurated in early 1931.\\nReferences[edit]\\n^ \"Rajgir: On Hallowed Ground\". 3 September 2017. Retrieved 22 July 2020. between the 6th and 5th centuries BCE, all roads led to the great city of Rajgir', 'score': 0.90869105}, {'title': 'Which City became the capital of India for a day, Check here', 'url': 'https://www.jagranjosh.com/general-knowledge/which-city-became-the-capital-of-india-for-a-day-1731421925-1', 'content': 'one day capital of India\\nIf someone asks you what is the capital of India, you will answer that it is New Delhi, which the British established. In Indian history, the capital of the country changed many times and different cities got the honour of becoming the capital of the country. [...] Which City became the Capital of India for a Day, Check Here\\nIf you are asked what the capital of India is, your answer will be New Delhi, which was settled by the British. Do you know that once in Indian history, a district was made the capital of the country? However, this incident lasted only for a day, after which it was recorded in the pages of history forever. This article will introduce you to one such district in India.\\n\\nByKishan Kumar\\nNov 12, 2024, 20:03 IST [...] After making Kolkata its capital, on 12 December 1912, New Delhi was declared as the capital of the country in the presence of George V. Since then, the name of New Delhi has been associated with the capital of the country.\\nAbout the Author', 'score': 0.9047265}, {'title': 'Capital of India - Definition, Meaning & Synonyms - Vocabulary.com', 'url': 'https://www.vocabulary.com/dictionary/capital%20of%20India', 'content': 'Capital of India - Definition, Meaning & Synonyms | Vocabulary.com\\nSKIP TO CONTENT\\n\\n\\nDictionary\\nVocabulary Lists\\nVocabTrainer™\\n\\ncapital of India\\nOther forms: capitals of India\\nDefinitions of capital of India\\n\\n\\nnoun\\nthe capital of India is a division of the old city of Delhi\\nsynonyms: Indian capital, New Delhi\\nsee moresee less\\nexample of:\\nnational capital\\nthe capital city of a nation\\n\\n\\nCite this entry\\nStyle:\\nMLA\\n\\nMLA\\nAPA\\nChicago', 'score': 0.8533396}, {'title': 'Which is the Capital of India? #capitalofindia #delhi #newdelhi', 'url': 'https://www.youtube.com/watch?v=Gj9rOLe4CZU', 'content': 'Enroll Now https://chahalacademy.com/offers Follow Us For Regular Updates: Instagram: https://www.instagram.com/chahalacademy Telegram:', 'score': 0.8399576}]\n"
]
}
],
"source": [
"# Run a test query\n",
"query = \"What is the capital of India?\"\n",
"results = search_tool.run(query)\n",
"\n",
"# Print results\n",
"print(\"Tavily Search Results:\")\n",
"print(results)"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "26e31bb4",
"metadata": {},
"outputs": [],
"source": [
"@tool\n",
"def get_weather(location: str) -> str:\n",
" \"\"\"Fetch the current weather information for a given location using Tavily search.\"\"\"\n",
" query = f\"current weather in {location}\"\n",
" results = search_tool.run(query)\n",
" return results"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "b98961af",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[{'title': 'Weather in Delhi',\n",
" 'url': 'https://www.weatherapi.com/',\n",
" 'content': \"{'location': {'name': 'Delhi', 'region': 'Ontario', 'country': 'Canada', 'lat': 42.85, 'lon': -80.5, 'tz_id': 'America/Toronto', 'localtime_epoch': 1746246286, 'localtime': '2025-05-03 00:24'}, 'current': {'last_updated_epoch': 1746245700, 'last_updated': '2025-05-03 00:15', 'temp_c': 10.4, 'temp_f': 50.7, 'is_day': 0, 'condition': {'text': 'Overcast', 'icon': '//cdn.weatherapi.com/weather/64x64/night/122.png', 'code': 1009}, 'wind_mph': 6.7, 'wind_kph': 10.8, 'wind_degree': 39, 'wind_dir': 'NE', 'pressure_mb': 1013.0, 'pressure_in': 29.91, 'precip_mm': 0.0, 'precip_in': 0.0, 'humidity': 74, 'cloud': 0, 'feelslike_c': 9.0, 'feelslike_f': 48.2, 'windchill_c': 5.9, 'windchill_f': 42.7, 'heatindex_c': 8.2, 'heatindex_f': 46.7, 'dewpoint_c': 4.4, 'dewpoint_f': 40.0, 'vis_km': 10.0, 'vis_miles': 6.0, 'uv': 0.0, 'gust_mph': 10.5, 'gust_kph': 16.9}}\",\n",
" 'score': 0.9573658},\n",
" {'title': 'New Delhi 14 Day Extended Forecast - Weather - Time and Date',\n",
" 'url': 'https://www.timeanddate.com/weather/india/new-delhi/ext',\n",
" 'content': 'SatMay 17 | | 98 / 89\\xa0°F | Sunny. | 93\\xa0°F | 15 mph | ↑ | 15% | 4% | - | 10(Very high) | 5:29 am | 7:06 pm\\n* Updated Saturday, May 3, 2025 2:54:05 am New Delhi time - Weather by CustomWeather, © 2025\\nHour-by-hour weather for New Delhi next 7 days [...] TueMay 13 | | 97 / 86\\xa0°F | Showers late. Increasing cloudiness. | 94\\xa0°F | 14 mph | ↑ | 24% | 46% | 0.01\" | 5(Moderate) | 5:31 am | 7:03 pm\\nWedMay 14 | | 97 / 86\\xa0°F | Sunny. | 92\\xa0°F | 13 mph | ↑ | 14% | 5% | - | 10(Very high) | 5:30 am | 7:04 pm\\nThuMay 15 | | 97 / 88\\xa0°F | Sunny. | 93\\xa0°F | 14 mph | ↑ | 15% | 4% | - | 10(Very high) | 5:30 am | 7:04 pm\\nFriMay 16 | | 98 / 89\\xa0°F | Sunny. | 93\\xa0°F | 15 mph | ↑ | 16% | 5% | - | 10(Very high) | 5:29 am | 7:05 pm',\n",
" 'score': 0.7171114},\n",
" {'title': 'Real-Time New Delhi Weather Conditions & Forecast - India - AQI',\n",
" 'url': 'https://www.aqi.in/weather/in/india/delhi/new-delhi',\n",
" 'content': '8.\\n\\nBodhan, India\\n\\nSunny\\n\\n30%\\n\\n2.5\\n\\n20.5 kmph\\xa0/\\xa0 SW\\n\\n9.\\n\\nPrayagraj, India\\n\\nSunny\\n\\n24%\\n\\n2.5\\n\\n12.6 kmph\\xa0/\\xa0 SE\\n\\n10.\\n\\nAllahabad, India\\n\\nSunny\\n\\n24%\\n\\n2.5\\n\\n12.6 kmph\\xa0/\\xa0 SE\\n\\nLast Updated: 03 May 2025, 03:37 AM\\n\\nPrana sense\\n\\nExperience precise, real-time weather monitoring with our Automatic Weather Station, reliable source for accurate meteorological data.\\n\\nWeather Station [...] New Delhi, Delhi, IndiaReal-time Weather Conditions\\n\\nNew Delhi, Delhi, India\\n\\nReal-time Weather Conditions\\n\\n25\\xa0\\xa0°C\\n\\n173\\xa0AQI\\n\\nAir quality index is: \\xa0Unhealthy\\n\\nLast Updated: 2025-05-03 09:00 (Local Time)\\n\\nNew Delhi\\n\\nWeather ParametersNew Delhi\\n\\nWeather Parameters\\n\\nNew Delhi\\n\\n12\\xa0km/h\\n\\n4\\xa0m/s\\n\\n168° SSE\\n\\n75\\xa0%\\n\\n2.2\\xa0km\\n\\n0\\xa0mm\\n\\n1009\\xa0mb\\n\\nUV Index4\\n\\nSuggestions for\\n\\n3\\xa0May\\n\\nTrending in India\\n\\nTrending in India\\n\\nHow Recent Dust Storms Affected Air Quality Across the Middle East [...] Moderate or heavy rain with thunder\\n\\n10.8 kmph\\xa0/\\xa0 SSE\\n\\nMost Hottest Cities 2025India\\n\\nMost Hottest Cities 2025\\n\\nIndia\\n\\n1.\\n\\nAmravati, India\\n\\nSunny\\n\\n14%\\n\\n2.7\\n\\n10.1 kmph\\xa0/\\xa0 NW\\n\\n2.\\n\\nAdilabad, India\\n\\nSunny\\n\\n28%\\n\\n2.7\\n\\n24.8 kmph\\xa0/\\xa0 SW\\n\\n3.\\n\\nNanded, India\\n\\nSunny\\n\\n16%\\n\\n2.6\\n\\n11.9 kmph\\xa0/\\xa0 WSW\\n\\n4.\\n\\nAkola, India\\n\\nSunny\\n\\n15%\\n\\n2.6\\n\\n27 kmph\\xa0/\\xa0 NW\\n\\n5.\\n\\nChandrapur, India\\n\\nSunny\\n\\n32%\\n\\n2.7\\n\\n17.6 kmph\\xa0/\\xa0 SSW\\n\\n6.\\n\\nYavatmal, India\\n\\nSunny\\n\\n17%\\n\\n2.7\\n\\n17.6 kmph\\xa0/\\xa0 WSW\\n\\n7.\\n\\nKupti, India\\n\\nSunny\\n\\n24%\\n\\n2.7\\n\\n15.8 kmph\\xa0/\\xa0 WSW',\n",
" 'score': 0.7023877},\n",
" {'title': 'Current Weather - Delhi - AccuWeather',\n",
" 'url': 'https://www.accuweather.com/en/in/delhi/202396/current-weather/202396',\n",
" 'content': 'Current Weather. 6:23 AM. 78°F. Sunny. RealFeel® 76°. Pleasant. RealFeel Guide. Pleasant. 63° to 81°. Most consider this temperature range ideal.',\n",
" 'score': 0.6672566},\n",
" {'title': 'Delhi, Delhi, India Weather Forecast - AccuWeather',\n",
" 'url': 'https://www.accuweather.com/en/in/delhi/202396/weather-forecast/202396',\n",
" 'content': \"Today's Weather. Sat, May 3. Hazy sunshine with a thunderstorm in spots this afternoon Hi: 93°. Tonight: Partly cloudy Lo: 78° · Current Weather. 7:07 AM. 78°F.\",\n",
" 'score': 0.54535896}]"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"get_weather.invoke(\"Delhi\")"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "9c2884c7",
"metadata": {},
"outputs": [],
"source": [
"from langchain_core.prompts import ChatPromptTemplate\n",
"from langchain_core.runnables import Runnable\n",
"\n",
"\n",
"# Define a prompt template\n",
"recommendation_prompt = ChatPromptTemplate.from_template(\"\"\"\n",
"You are a helpful assistant that gives weather-based advice.\n",
"\n",
"Given the current weather condition: \"{weather_condition}\", provide:\n",
"1. Clothing or activity recommendations suited for this weather.\n",
"2. At least one health tip to stay safe or comfortable in this condition.\n",
"\n",
"Be concise and clear.\n",
"\"\"\")\n",
"\n",
"# Combine prompt and LLM into a runnable\n",
"recommendation_chain: Runnable = recommendation_prompt | llm\n",
"\n",
"# Wrap it as a LangChain tool\n",
"@tool\n",
"def get_recommendation(weather_condition: str) -> str:\n",
" \"\"\"Give activity/clothing recommendations and health tips based on the weather condition using an LLM.\"\"\"\n",
" return recommendation_chain.invoke({\"weather_condition\": weather_condition})"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "76f5efa2",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"AIMessage(content=\"\\n<think>\\nOkay, the user wants advice for sunny 30°C weather. Let me start by thinking about clothing. It's warm but not super hot yet. Light fabrics like cotton or linen would be good because they're breathable. Shorts and a t-shirt are obvious, but maybe mention specific types like loose-fitting to allow airflow. A hat would provide shade, maybe a wide-brimmed one to protect the face and neck. Sunglasses are a must to shield the eyes from UV rays.\\n\\nActivities? Outdoor stuff obviously. Maybe suggest water activities like swimming since it's hot. Barbecues or picnics in the park could be nice. But also think about timing—like suggesting to do outdoor exercises in the morning or evening to avoid the midday sun. Maybe mention things like hiking or cycling but again with the time consideration.\\n\\nHealth tips. Hydration is key. Need to remind to drink water even if not thirsty. Sunscreen with high SPF, reapplying every few hours. Maybe mention avoiding the sun during peak hours, like 11 AM to 3 PM. Also, wearing protective clothing if staying out long. Oh, and maybe something about not leaving kids or pets in the car. Wait, but the user didn't specify, so maybe stick to general tips. \\n\\nWait, the user asked for at least one health tip. So pick the most important ones. Hydration and sunscreen are top. Maybe combine them. Also, taking breaks in the shade. \\n\\nLet me structure this. For clothing and activities, list a few bullet points. Then the health tip as a separate point. Need to be concise. Let me check if 30°C is considered hot. 30 is about 86°F, so yeah, warm but manageable. So maybe light clothing, staying hydrated, using sunscreen. \\n\\nHmm, maybe also mention staying in the shade when possible. Or using an umbrella? Not sure if that's common. Hats are better. \\n\\nOkay, putting it all together. Make sure it's clear and not too wordy. The user wants concise answers. Alright, I think that's covered.\\n</think>\\n\\n1. **Clothing/Activities**: Wear light, breathable fabrics (e.g., linen/cotton), a wide-brimmed hat, and sunglasses. Enjoy outdoor activities like swimming, hiking in shaded areas, or evening barbecues. Avoid intense midday sun; plan outdoor exercise for early morning or late afternoon. \\n\\n2. **Health Tip**: Stay hydrated by drinking water regularly, even if not thirsty. Apply broad-spectrum SPF 30+ sunscreen, reapplying every 2 hours, and seek shade during peak sun hours (10 AM–4 PM).\", additional_kwargs={}, response_metadata={'token_usage': {'completion_tokens': 552, 'prompt_tokens': 71, 'total_tokens': 623, 'completion_time': 1.372413311, 'prompt_time': 0.005961551, 'queue_time': 0.24641989999999997, 'total_time': 1.378374862}, 'model_name': 'qwen-qwq-32b', 'system_fingerprint': 'fp_3796682456', 'finish_reason': 'stop', 'logprobs': None}, id='run-0b552e02-103f-486a-ab52-5e5b833a7a71-0', usage_metadata={'input_tokens': 71, 'output_tokens': 552, 'total_tokens': 623})"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"get_recommendation.invoke(\"sunny and 30 degrees Celsius\")"
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "1bf8d533",
"metadata": {},
"outputs": [],
"source": [
"from langchain_community.document_loaders import WikipediaLoader\n",
"@tool\n",
"def wiki_search(query : str) -> str:\n",
" \"\"\"Search Wikipedia for a given query and return the summary.\n",
" Args:\n",
" query (str): The search query.\n",
" \"\"\"\n",
" \n",
" search_docs = WikipediaLoader(query=query, load_max_docs=1).load()\n",
" formatted_search_docs = \"\\n\\n----\\n\\n\".join(\n",
" [\n",
" f'<Document Source=\"{doc.metadata[\"source\"]}\" page=\"{doc.metadata.get(\"page\", \"\")}\">\\n{doc.page_content}\\n</Document>'\n",
" for doc in search_docs\n",
" ])\n",
" return formatted_search_docs"
]
},
{
"cell_type": "code",
"execution_count": 11,
"id": "87617077",
"metadata": {},
"outputs": [],
"source": [
"# ! pip install wikipedia"
]
},
{
"cell_type": "code",
"execution_count": 12,
"id": "4f5b4398",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'<Document Source=\"https://en.wikipedia.org/wiki/Agentic_AI\" page=\"\">\\nAgentic AI is a class of artificial intelligence that focuses on autonomous systems that can make decisions and perform tasks without human intervention. The independent systems automatically respond to conditions, to produce process results. The field is closely linked to agentic automation, also known as agent-based process management systems, when applied to process automation. Applications include software development, customer support, cybersecurity and business intelligence. \\n\\n\\n== Overview ==\\nThe core concept of agentic AI is the use of AI agents to perform automated tasks but without human intervention. While robotic process automation (RPA) and AI agents can be programmed to automate specific tasks or support rule-based decisions, the rules are usually fixed. Agentic AI operates independently, making decisions through continuous learning and analysis of external data and complex data sets. Functioning agents can require various AI techniques, such as natural language processing, machine learning (ML), and computer vision, depending on the environment.\\nParticularly, reinforcement learning (RL) is essential in assisting agentic AI in making self-directed choices by supporting agents in learning best actions through the trial-and-error method. Agents using RL continuously to explore their surroundings, will be given rewards or punishment for their actions, which refines their decision-making capability over time. While Deep learning, as opposed to rule-based methods, supports Agentic AI through multi-layered neural networks to learn features from extensive and complex sets of data. RL combined with deep learning thus supports the use of AI agents to adjust dynamically, optimize procedures, and engage in complex behaviors with limited control from humans.\\n\\n\\n== History ==\\nSome scholars trace the conceptual roots of agentic AI to Alan Turing\\'s mid-20th century work with machine intelligence and Norbert Wiener\\'s work on feedback systems. The term agent-based process management system was used as far back as 1998 to describe the concept of using autonomous agents for business process management. The psychological principle of agency was also discussed in the 2008 work of sociologist Albert Bandura, who studied how humans can shape their environments. This research would shape how humans modeled and developed artificial intelligence agents. \\nSome additional milestones of agentic AI include IBM\\'s Deep Blue, demonstrating how agency could work within a confined domain, advances in machine learning in the 2000s, AI being integrated into robotics, and the rise of generative AI such as OpenAI\\'s GPT models and Salesforce\\'s Agentforce platform.\\nIn the last decade, significant advances in AI have spurred the development of Agentic AI. Breakthroughs in deep learning, reinforcement learning, and neural networks allowed AI systems to learn on their own and make decision with minimal human guidance. Consilience of agentic AI across autonomous transportation, industrial automation, and tailored healthcare has also supported its viability. Self-driving cars use agentic AI to handle complex road scenarios, while\\nIn 2025, research firm Forrester named agentic AI a top emerging technology for 2025.\\n\\n\\n== Applications ==\\nApplications using agentic AI include:\\n\\nSoftware development - AI coding agents can write large pieces of code, and review it. Agents can even perform non-code related tasks such as reverse engineering specifications from code.\\nCustomer support automation - AI agents can improve customer service by improving the ability of chatbots to answer a wider variety of questions, rather than having a limited set of answers pre-programmed by humans.\\nEnterprise workflows - AI agents can automatically automate routine tasks by processing pooled data, as opposed to a company needing APIs preprogrammed for specific tasks.\\nCybersecurity and threat detection - AI agents deployed for cybersecurity can automatically detect and mitigate threats in\\n</Document>'"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import wikipedia\n",
"wiki_search.invoke(\"AI Agents\")"
]
},
{
"cell_type": "code",
"execution_count": 13,
"id": "1f445fb8",
"metadata": {},
"outputs": [],
"source": [
"@tool\n",
"def web_search(query: str) -> str:\n",
" \"\"\"Search the web for a given query and return the summary.\n",
" Args:\n",
" query (str): The search query.\n",
" \"\"\"\n",
" \n",
" search_tool = TavilySearchResults()\n",
" result = search_tool.run(query)\n",
" return result[0]['content']"
]
},
{
"cell_type": "code",
"execution_count": 14,
"id": "70e42662",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"AI agents are a type of artificial intelligence (AI) system that can understand and respond to customer inquiries without human intervention. They are created using an agent builder, like Agentforce, and rely on machine learning and natural language processing (NLP) to handle a wide range of tasks. These intelligent agents can include anything from answering simple questions to resolving complex issues — even multi-tasking. Most importantly, AI agents can continuously improve their own [...] Want better, fully-optimized marketing campaigns? AI agents can help your marketing team build better campaigns — faster. With Agentforce Campaigns, AI agents generate a campaign brief and target audience segment, then create relevant content speaking to those audiences. AI can even build a customer journey in Flow. AI agents also continually analyze campaign performance against your key performance indicators and proactively recommend improvements.\n"
]
}
],
"source": [
"output = web_search.invoke(\"AI Agents\")\n",
"print(output)"
]
},
{
"cell_type": "code",
"execution_count": 18,
"id": "bf1c120e",
"metadata": {},
"outputs": [],
"source": [
"@tool\n",
"def add(x: int, y: int) -> int:\n",
" \"\"\"Add two numbers.\n",
" Args:\n",
" x (int): First number.\n",
" y (int): Second number.\n",
" \"\"\"\n",
"\n",
" return x + y\n",
"\n",
"@tool\n",
"def subtract(x: int, y: int) -> int:\n",
" \"\"\"Subtract two numbers.\n",
" Args:\n",
" x (int): First number.\n",
" y (int): Second number.\n",
" \"\"\"\n",
"\n",
" return x - y\n",
"\n",
"@tool\n",
"def multiply(x: int, y: int) -> int:\n",
" \"\"\"Multiply two numbers.\n",
" Args:\n",
" x (int): First number.\n",
" y (int): Second number.\n",
" \"\"\"\n",
"\n",
" return x * y\n",
"\n",
"@tool\n",
"def divide(x: int, y: int) -> float:\n",
" \"\"\"Divide two numbers.\n",
" Args:\n",
" x (int): First number.\n",
" y (int): Second number.\n",
" \"\"\"\n",
"\n",
" if y == 0:\n",
" raise ValueError(\"Cannot divide by zero.\")\n",
" return x / y\n",
"\n",
"@tool\n",
"def square(x: int) -> int:\n",
" \"\"\"Square a number.\n",
" Args:\n",
" x (int): The number to be squared.\n",
" \"\"\"\n",
"\n",
" return x * x\n",
"\n",
"@tool\n",
"def cube(x: int) -> int:\n",
" \"\"\"Cube a number.\n",
" Args:\n",
" x (int): The number to be cubed.\n",
" \"\"\"\n",
"\n",
" return x * x * x\n",
"\n",
"@tool\n",
"def power(x: int, y: int) -> int:\n",
" \"\"\"Raise a number to the power of another number.\n",
" Args:\n",
" x (int): The base number.\n",
" y (int): The exponent.\n",
" \"\"\"\n",
"\n",
" return x ** y\n",
"\n",
"@tool\n",
"def factorial(n: int) -> int:\n",
" \"\"\"Calculate the factorial of a number.\n",
" Args:\n",
" n (int): The number to calculate the factorial for.\n",
" \"\"\"\n",
"\n",
" if n < 0:\n",
" raise ValueError(\"Factorial is not defined for negative numbers.\")\n",
" if n == 0 or n == 1:\n",
" return 1\n",
" result = 1\n",
" for i in range(2, n + 1):\n",
" result *= i\n",
" return result\n",
"\n",
"@tool\n",
"def mean(numbers: list) -> float:\n",
" \"\"\"Calculate the mean of a list of numbers.\n",
" Args:\n",
" numbers (list): A list of numbers.\n",
" \"\"\"\n",
"\n",
" if not numbers:\n",
" raise ValueError(\"The list is empty.\")\n",
" return sum(numbers) / len(numbers)\n",
"\n",
"@tool\n",
"def standard_deviation(numbers: list) -> float:\n",
" \"\"\"Calculate the standard deviation of a list of numbers.\n",
" Args:\n",
" numbers (list): A list of numbers.\n",
" \"\"\"\n",
"\n",
" if not numbers:\n",
" raise ValueError(\"The list is empty.\")\n",
" mean_value = mean(numbers)\n",
" variance = sum((x - mean_value) ** 2 for x in numbers) / len(numbers)\n",
" return variance ** 0.5"
]
},
{
"cell_type": "code",
"execution_count": 29,
"id": "bf43300a",
"metadata": {},
"outputs": [],
"source": [
"# !pip install chromadb"
]
},
{
"cell_type": "code",
"execution_count": 25,
"id": "e798f4ac",
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"/var/folders/r6/l4km4ywx28zb1dkl0yp8fyn80000gn/T/ipykernel_1001/4015992125.py:20: LangChainDeprecationWarning: Since Chroma 0.4.x the manual persistence method is no longer supported as docs are automatically persisted.\n",
" vector_store.persist()\n"
]
}
],
"source": [
"from langchain_community.vectorstores import Chroma\n",
"from langchain.embeddings import HuggingFaceEmbeddings\n",
"from langchain.tools.retriever import create_retriever_tool\n",
"from langchain_core.documents import Document\n",
"import os\n",
"\n",
"# Create embeddings\n",
"embeddings = HuggingFaceEmbeddings(model_name=\"sentence-transformers/all-mpnet-base-v2\")\n",
"\n",
"# Example documents to index\n",
"documents = [\n",
" Document(page_content=\"What is artificial intelligence?\"),\n",
" Document(page_content=\"Explain how AI agents operate.\"),\n",
"]\n",
"\n",
"# Create a Chroma vector store (in memory or persistent)\n",
"vector_store = Chroma.from_documents(documents, embeddings, persist_directory=\"./chroma_db\")\n",
"\n",
"# (Optional) Persist the DB to disk\n",
"vector_store.persist()\n",
"\n",
"# Create the retriever tool\n",
"create_retriever_tool = create_retriever_tool(\n",
" retriever=vector_store.as_retriever(),\n",
" name=\"Question_Search\",\n",
" description=\"A tool to retrieve similar questions using ChromaDB vector store.\",\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 26,
"id": "06c18b4c",
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"/var/folders/r6/l4km4ywx28zb1dkl0yp8fyn80000gn/T/ipykernel_1001/1571824264.py:1: LangChainDeprecationWarning: The class `Chroma` was deprecated in LangChain 0.2.9 and will be removed in 1.0. An updated version of the class exists in the :class:`~langchain-chroma package and should be used instead. To use it run `pip install -U :class:`~langchain-chroma` and import as `from :class:`~langchain_chroma import Chroma``.\n",
" vector_store = Chroma(persist_directory=\"./chroma_db\", embedding_function=embeddings)\n"
]
}
],
"source": [
"vector_store = Chroma(persist_directory=\"./chroma_db\", embedding_function=embeddings)"
]
},
{
"cell_type": "code",
"execution_count": 27,
"id": "9eefbbe0",
"metadata": {},
"outputs": [],
"source": [
"tools = [\n",
" multiply,\n",
" add,\n",
" subtract,\n",
" divide,\n",
" square,\n",
" cube,\n",
" power,\n",
" factorial,\n",
" mean,\n",
" standard_deviation,\n",
" get_weather,\n",
" get_recommendation,\n",
" wiki_search,\n",
" web_search\n",
"]"
]
},
{
"cell_type": "code",
"execution_count": 31,
"id": "10b24bed",
"metadata": {},
"outputs": [],
"source": [
"from langgraph.graph import StateGraph, START\n",
"from langgraph.prebuilt import ToolNode\n",
"from langchain_groq import ChatGroq\n",
"from langchain_core.messages import HumanMessage\n",
"from configs.prompt import Agent_prompt_template\n",
"\n",
"def build_graph():\n",
" \"\"\"Build the graph using Groq and custom prompt/tools setup\"\"\"\n",
"\n",
" # Initialize the LLM\n",
" llm = ChatGroq(\n",
" model=\"qwen-qwq-32b\",\n",
" temperature=0\n",
" )\n",
"\n",
" # Bind tools to LLM\n",
" llm_with_tools = llm.bind_tools(tools)\n",
"\n",
" # Define assistant node\n",
" def assistant(state: MessagesState):\n",
" \"\"\"Assistant node\"\"\"\n",
" return {\"messages\": [llm_with_tools.invoke(state[\"messages\"])]}\n",
"\n",
" # Define retriever node\n",
" def retriever(state: MessagesState):\n",
" \"\"\"Retriever node\"\"\"\n",
" similar_question = vector_store.similarity_search(state[\"messages\"][0].content)\n",
" example_msg = HumanMessage(\n",
" content=f\"Here I provide a similar question and answer for reference: \\n\\n{similar_question[0].page_content}\",\n",
" )\n",
" return {\"messages\": [Agent_prompt_template] + state[\"messages\"] + [example_msg]}\n",
"\n",
" # Create graph\n",
" builder = StateGraph(MessagesState)\n",
" builder.add_node(\"retriever\", retriever)\n",
" builder.add_node(\"assistant\", assistant)\n",
" builder.add_node(\"tools\", ToolNode(tools))\n",
"\n",
" builder.add_edge(START, \"retriever\")\n",
" builder.add_edge(\"retriever\", \"assistant\")\n",
" builder.add_conditional_edges(\"assistant\", tools_condition)\n",
" builder.add_edge(\"tools\", \"assistant\")\n",
"\n",
" # Compile and return the graph\n",
" return builder.compile()"
]
},
{
"cell_type": "code",
"execution_count": 33,
"id": "2a74e687",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"================================\u001b[1m Human Message \u001b[0m=================================\n",
"\n",
"When was attention is all you need paper printed and what is the main idea of it?\n",
"================================\u001b[1m Human Message \u001b[0m=================================\n",
"\n",
"You are a helpful assistant following the REACT methodology and tasked with answering questions using a set of tools. \n",
"Once a question is asked,you have to Report your thoughts, and finish your answer with the following template: \n",
"FINAL ANSWER: [YOUR FINAL ANSWER]. \n",
"\n",
"### **Instructions:** \n",
"- YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings. \n",
"- If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise. \n",
"- If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise. If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string.\n",
"- Provide the answer in clear and professional language. \n",
"- **Limit** the FINAL ANSWER to 1000 words and keep it to the point.\n",
"- **Do not** include any additional information or explanations in your FINAL ANSWER.\n",
"- **Do not** include any information that is not relevant to the question.\n",
"- **Validate** your answer before providing it. \n",
"\n",
"\n",
"Your answer should only start with \"FINAL ANSWER: \", then follows with the answer. \n",
"================================\u001b[1m Human Message \u001b[0m=================================\n",
"\n",
"Here I provide a similar question and answer for reference: \n",
"\n",
"What is artificial intelligence?\n",
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
"\n",
"FINAL ANSWER: 2017, The main idea is the introduction of the Transformer architecture using self-attention mechanisms for efficient sequence processing, eliminating the need for recurrent layers.\n"
]
}
],
"source": [
"# test\n",
"if __name__ == \"__main__\":\n",
" question = \"When was attention is all you need paper printed and what is the main idea of it?\"\n",
" # Build the graph\n",
" graph = build_graph()\n",
" # Run the graph\n",
" messages = [HumanMessage(content=question)]\n",
" messages = graph.invoke({\"messages\": messages})\n",
" for m in messages[\"messages\"]:\n",
" m.pretty_print()\n"
]
},
{
"cell_type": "code",
"execution_count": 43,
"id": "4c0862b1",
"metadata": {},
"outputs": [],
"source": [
"def build_graph():\n",
" \"\"\"Build the graph with traceable output using Groq + tools + vector search.\"\"\"\n",
" \n",
" from langgraph.graph import StateGraph, START\n",
" from langgraph.prebuilt import ToolNode\n",
" from langchain_core.messages import HumanMessage\n",
" from configs.prompt import Agent_prompt_template\n",
"\n",
" llm = ChatGroq(model=\"qwen-qwq-32b\", temperature=0)\n",
" llm_with_tools = llm.bind_tools(tools)\n",
"\n",
" def assistant(state: MessagesState):\n",
" llm_response = llm_with_tools.invoke(state[\"messages\"])\n",
" step_log = {\n",
" \"step\": \"assistant\",\n",
" \"tool_used\": \"LLM (Groq qwen-qwq-32b)\",\n",
" \"input\": state[\"messages\"],\n",
" \"output\": llm_response.content\n",
" }\n",
" return {\n",
" \"messages\": [llm_response],\n",
" \"steps\": state.get(\"steps\", []) + [step_log]\n",
" }\n",
"\n",
" def retriever(state: MessagesState):\n",
" query = state[\"messages\"][0].content\n",
" similar_docs = vector_store.similarity_search(query)\n",
" example_msg = HumanMessage(\n",
" content=f\"Here I provide a similar question and answer for reference:\\n\\n{similar_docs[0].page_content}\",\n",
" )\n",
" step_log = {\n",
" \"step\": \"retriever\",\n",
" \"tool_used\": \"Vector Store (Similarity Search)\",\n",
" \"input\": query,\n",
" \"output\": similar_docs[0].page_content\n",
" }\n",
" return {\n",
" \"messages\": [Agent_prompt_template] + state[\"messages\"] + [example_msg],\n",
" \"steps\": state.get(\"steps\", []) + [step_log]\n",
" }\n",
"\n",
" builder = StateGraph(MessagesState)\n",
" builder.add_node(\"retriever\", retriever)\n",
" builder.add_node(\"assistant\", assistant)\n",
" builder.add_node(\"tools\", ToolNode(tools))\n",
" builder.add_edge(START, \"retriever\")\n",
" builder.add_edge(\"retriever\", \"assistant\")\n",
" builder.add_conditional_edges(\"assistant\", tools_condition)\n",
" builder.add_edge(\"tools\", \"assistant\")\n",
"\n",
" return builder.compile()"
]
},
{
"cell_type": "code",
"execution_count": 44,
"id": "f658bc7a",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"================================\u001b[1m Human Message \u001b[0m=================================\n",
"\n",
"What is the average temperature in Delhi in last week in celcius and are there any health tips?\n",
"================================\u001b[1m Human Message \u001b[0m=================================\n",
"\n",
"You are a helpful assistant following the REACT methodology and tasked with answering questions using a set of tools. \n",
"Once a question is asked,you have to Report your thoughts, and finish your answer with the following template: \n",
"FINAL ANSWER: [YOUR FINAL ANSWER]. \n",
"\n",
"### **Instructions:** \n",
"- YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings. \n",
"- If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise. \n",
"- If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise. If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string.\n",
"- Provide the answer in clear and professional language. \n",
"- **Limit** the FINAL ANSWER to 1000 words and keep it to the point.\n",
"- **Do not** include any additional information or explanations in your FINAL ANSWER.\n",
"- **Do not** include any information that is not relevant to the question.\n",
"- **Validate** your answer before providing it. \n",
"\n",
"\n",
"Your answer should only start with \"FINAL ANSWER: \", then follows with the answer. \n",
"================================\u001b[1m Human Message \u001b[0m=================================\n",
"\n",
"Here I provide a similar question and answer for reference:\n",
"\n",
"What is artificial intelligence?\n",
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
"Tool Calls:\n",
" web_search (call_74ab)\n",
" Call ID: call_74ab\n",
" Args:\n",
" query: average temperature in Delhi last week in celsius\n",
"=================================\u001b[1m Tool Message \u001b[0m=================================\n",
"Name: web_search\n",
"\n",
"Past Weather in New Delhi, Delhi, India — Yesterday and Last 2 Weeks\n",
"\n",
"Past Weather in New Delhi — Graph\n",
"\n",
"See weather overview\n",
"\n",
"New Delhi Temperature Yesterday\n",
"\n",
"Maximum temperature yesterday: 84 °F (at 2:30 am)Minimum temperature yesterday: 68 °F (at 5:30 am)Average temperature yesterday: 76 °F\n",
"\n",
"High & Low Weather Summary for the Past Weeks [...] | Temperature | Humidity | Pressure\n",
"High | 105 °F(Apr 21, 2:30 pm) | 100%(May 2, 5:30 am) | 29.89 \"Hg(May 2, 5:30 am)\n",
"Low | 68 °F(May 2, 5:30 am) | 13%(Apr 22, 2:30 pm) | 29.44 \"Hg(Apr 18, 5:30 pm)\n",
"Average | 88 °F | 45% | 29.66 \"Hg\n",
"* Reported Apr 18 11:30 am — May 3 11:30 am, New Delhi. Weather by CustomWeather, © 2025\n",
"Note: Actual official high and low records may vary slightly from our data, if they occured in-between our weather recording intervals... More about our weather records\n",
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
"\n",
"FINAL ANSWER: 31, Stay hydrated, use sunscreen, wear light clothing, avoid prolonged sun exposure, stay in shaded areas during peak heat.\n"
]
}
],
"source": [
"# test\n",
"if __name__ == \"__main__\":\n",
" question = \"What is the average temperature in Delhi in last week in celcius and are there any health tips?\"\n",
" # Build the graph\n",
" graph = build_graph()\n",
" # Run the graph\n",
" messages = [HumanMessage(content=question)]\n",
" messages = graph.invoke({\"messages\": messages})\n",
" for m in messages[\"messages\"]:\n",
" m.pretty_print()\n",
"\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.6"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|