Spaces:
Sleeping
Sleeping
Update agent.ipynb
Browse files- agent.ipynb +307 -564
agent.ipynb
CHANGED
|
@@ -1,564 +1,307 @@
|
|
| 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 |
-
"\n",
|
| 309 |
-
" # AI summarization node\n",
|
| 310 |
-
" def ai_summarizer_node(inputs):\n",
|
| 311 |
-
" raw_route = inputs.get(\"raw_route\", \"\")\n",
|
| 312 |
-
"\n",
|
| 313 |
-
" if raw_route.startswith(\"❌\"):\n",
|
| 314 |
-
" # If there's an error in route fetching, pass it through\n",
|
| 315 |
-
" return {\"final_summary\": raw_route}\n",
|
| 316 |
-
"\n",
|
| 317 |
-
" # Create detailed prompt for DeepSeek V3.1 Terminus\n",
|
| 318 |
-
" prompt = f\"\"\"\n",
|
| 319 |
-
"I need you to analyze this route information and create a helpful navigation summary.\n",
|
| 320 |
-
"\n",
|
| 321 |
-
"ROUTE DATA:\n",
|
| 322 |
-
"{raw_route}\n",
|
| 323 |
-
"\n",
|
| 324 |
-
"Please provide:\n",
|
| 325 |
-
"1. A brief overview of the journey (distance, time, key roads)\n",
|
| 326 |
-
"2. Simplified directions highlighting only the most important turns and landmarks\n",
|
| 327 |
-
"3. Any notable features or potential challenges mentioned in the route\n",
|
| 328 |
-
"4. A confidence assessment of the route quality\n",
|
| 329 |
-
"\n",
|
| 330 |
-
"Format your response to be clear and easy to follow while driving. Use emojis appropriately to make it more readable.\n",
|
| 331 |
-
"\"\"\"\n",
|
| 332 |
-
"\n",
|
| 333 |
-
" print(\"🤖 Generating AI summary with DeepSeek V3.1 Terminus...\")\n",
|
| 334 |
-
" ai_summary = llm(prompt, max_tokens=1200, temperature=0.2)\n",
|
| 335 |
-
"\n",
|
| 336 |
-
" return {\"final_summary\": ai_summary}\n",
|
| 337 |
-
"\n",
|
| 338 |
-
" # Create the graph\n",
|
| 339 |
-
" graph = NavigationGraph()\n",
|
| 340 |
-
"\n",
|
| 341 |
-
" # Add nodes in order\n",
|
| 342 |
-
" route_node = Node(\"route_fetcher\", route_fetcher_node)\n",
|
| 343 |
-
" ai_node = Node(\"ai_summarizer\", ai_summarizer_node)\n",
|
| 344 |
-
"\n",
|
| 345 |
-
" graph.add_node(route_node)\n",
|
| 346 |
-
" graph.add_node(ai_node)\n",
|
| 347 |
-
"\n",
|
| 348 |
-
" return graph\n",
|
| 349 |
-
"\n",
|
| 350 |
-
"def navigate_with_ai(origin: str, destination: str, api_key: str) -> str:\n",
|
| 351 |
-
" \"\"\"\n",
|
| 352 |
-
" Main navigation function using DeepSeek V3.1 Terminus\n",
|
| 353 |
-
"\n",
|
| 354 |
-
" Args:\n",
|
| 355 |
-
" origin: Origin coordinates as \"longitude,latitude\"\n",
|
| 356 |
-
" destination: Destination coordinates as \"longitude,latitude\"\n",
|
| 357 |
-
" api_key: OpenRouter API key\n",
|
| 358 |
-
"\n",
|
| 359 |
-
" Returns:\n",
|
| 360 |
-
" AI-generated navigation summary\n",
|
| 361 |
-
" \"\"\"\n",
|
| 362 |
-
"\n",
|
| 363 |
-
" print(\"🚀 Starting AI Navigation Agent...\")\n",
|
| 364 |
-
" print(f\"📍 Route: {origin} → {destination}\")\n",
|
| 365 |
-
"\n",
|
| 366 |
-
" # Create and run the navigation agent\n",
|
| 367 |
-
" agent = create_navigation_agent(api_key)\n",
|
| 368 |
-
"\n",
|
| 369 |
-
" result = agent.run({\n",
|
| 370 |
-
" \"origin\": origin,\n",
|
| 371 |
-
" \"destination\": destination\n",
|
| 372 |
-
" })\n",
|
| 373 |
-
"\n",
|
| 374 |
-
" # Return the final summary\n",
|
| 375 |
-
" if \"final_summary\" in result:\n",
|
| 376 |
-
" return result[\"final_summary\"]\n",
|
| 377 |
-
" elif \"raw_route\" in result:\n",
|
| 378 |
-
" return result[\"raw_route\"] # Fallback to raw route\n",
|
| 379 |
-
" else:\n",
|
| 380 |
-
" return \"❌ Error: Could not generate navigation instructions\"\n",
|
| 381 |
-
"\n",
|
| 382 |
-
"# Test function\n",
|
| 383 |
-
"def test_navigation():\n",
|
| 384 |
-
" \"\"\"Test the navigation agent\"\"\"\n",
|
| 385 |
-
"\n",
|
| 386 |
-
" api_key = os.getenv(\"my_key\")\n",
|
| 387 |
-
"\n",
|
| 388 |
-
" if not api_key:\n",
|
| 389 |
-
" print(\"❌ Please set your OpenRouter API key:\")\n",
|
| 390 |
-
" print('os.environ[\"my_key\"] = \"sk-or-v1-your-actual-key\"')\n",
|
| 391 |
-
" return\n",
|
| 392 |
-
"\n",
|
| 393 |
-
" # Test coordinates\n",
|
| 394 |
-
" dhaka = \"90.4125,23.8103\" # Dhaka, Bangladesh\n",
|
| 395 |
-
" chittagong = \"91.7832,22.3569\" # Chittagong, Bangladesh\n",
|
| 396 |
-
"\n",
|
| 397 |
-
" print(\"=\" * 60)\n",
|
| 398 |
-
" print(\"🗺️ AI NAVIGATION AGENT - DEEPSEEK V3.1 TERMINUS\")\n",
|
| 399 |
-
" print(\"=\" * 60)\n",
|
| 400 |
-
"\n",
|
| 401 |
-
" result = navigate_with_ai(dhaka, chittagong, api_key)\n",
|
| 402 |
-
"\n",
|
| 403 |
-
" print(\"\\n\" + \"=\" * 60)\n",
|
| 404 |
-
" print(\"📋 NAVIGATION RESULT:\")\n",
|
| 405 |
-
" print(\"=\" * 60)\n",
|
| 406 |
-
" print(result)\n",
|
| 407 |
-
" print(\"=\" * 60)\n",
|
| 408 |
-
"\n",
|
| 409 |
-
"if __name__ == \"__main__\":\n",
|
| 410 |
-
" test_navigation()\n",
|
| 411 |
-
"\n",
|
| 412 |
-
"# === USAGE EXAMPLES ===\n",
|
| 413 |
-
"\n",
|
| 414 |
-
"# Example 1: Basic usage\n",
|
| 415 |
-
"\"\"\"\n",
|
| 416 |
-
"import os\n",
|
| 417 |
-
"os.environ[\"my_key\"] = \"sk-or-v1-your-actual-openrouter-key\"\n",
|
| 418 |
-
"\n",
|
| 419 |
-
"origin = \"90.4125,23.8103\" # Dhaka\n",
|
| 420 |
-
"destination = \"91.7832,22.3569\" # Chittagong\n",
|
| 421 |
-
"\n",
|
| 422 |
-
"result = navigate_with_ai(origin, destination, os.getenv(\"my_key\"))\n",
|
| 423 |
-
"print(result)\n",
|
| 424 |
-
"\"\"\"\n",
|
| 425 |
-
"\n",
|
| 426 |
-
"# Example 2: Custom coordinates\n",
|
| 427 |
-
"\"\"\"\n",
|
| 428 |
-
"# London to Manchester\n",
|
| 429 |
-
"london = \"-0.1276,51.5074\"\n",
|
| 430 |
-
"manchester = \"-2.2426,53.4808\"\n",
|
| 431 |
-
"\n",
|
| 432 |
-
"result = navigate_with_ai(london, manchester, os.getenv(\"my_key\"))\n",
|
| 433 |
-
"print(result)\n",
|
| 434 |
-
"\"\"\"\n",
|
| 435 |
-
"\n",
|
| 436 |
-
"# Example 3: Just test the LLM\n",
|
| 437 |
-
"\"\"\"\n",
|
| 438 |
-
"llm = OpenRouterLLM(api_key=os.getenv(\"my_key\"), model=\"deepseek/deepseek-v3.1-terminus\")\n",
|
| 439 |
-
"response = llm(\"Hello! Can you help me with navigation between two cities?\")\n",
|
| 440 |
-
"print(response)\n",
|
| 441 |
-
"\"\"\""
|
| 442 |
-
],
|
| 443 |
-
"metadata": {
|
| 444 |
-
"colab": {
|
| 445 |
-
"base_uri": "https://localhost:8080/",
|
| 446 |
-
"height": 296
|
| 447 |
-
},
|
| 448 |
-
"id": "FKufZbsh2_I4",
|
| 449 |
-
"outputId": "e2fee184-143e-4757-8623-c62e08efe2cd"
|
| 450 |
-
},
|
| 451 |
-
"execution_count": 17,
|
| 452 |
-
"outputs": [
|
| 453 |
-
{
|
| 454 |
-
"output_type": "stream",
|
| 455 |
-
"name": "stdout",
|
| 456 |
-
"text": [
|
| 457 |
-
"============================================================\n",
|
| 458 |
-
"🗺️ AI NAVIGATION AGENT - DEEPSEEK V3.1 TERMINUS\n",
|
| 459 |
-
"============================================================\n",
|
| 460 |
-
"🚀 Starting AI Navigation Agent...\n",
|
| 461 |
-
"📍 Route: 90.4125,23.8103 → 91.7832,22.3569\n",
|
| 462 |
-
"🔍 Fetching route from 90.4125,23.8103 to 91.7832,22.3569...\n",
|
| 463 |
-
"✅ Route found: 250.4km, ~186 minutes\n",
|
| 464 |
-
"🤖 Generating AI summary with DeepSeek V3.1 Terminus...\n",
|
| 465 |
-
"\n",
|
| 466 |
-
"============================================================\n",
|
| 467 |
-
"📋 NAVIGATION RESULT:\n",
|
| 468 |
-
"============================================================\n",
|
| 469 |
-
"❌ Error: Invalid API key or unauthorized. Please check your OpenRouter API key.\n",
|
| 470 |
-
"============================================================\n"
|
| 471 |
-
]
|
| 472 |
-
},
|
| 473 |
-
{
|
| 474 |
-
"output_type": "execute_result",
|
| 475 |
-
"data": {
|
| 476 |
-
"text/plain": [
|
| 477 |
-
"'\\nllm = OpenRouterLLM(api_key=os.getenv(\"my_key\"), model=\"deepseek/deepseek-v3.1-terminus\")\\nresponse = llm(\"Hello! Can you help me with navigation between two cities?\")\\nprint(response)\\n'"
|
| 478 |
-
],
|
| 479 |
-
"application/vnd.google.colaboratory.intrinsic+json": {
|
| 480 |
-
"type": "string"
|
| 481 |
-
}
|
| 482 |
-
},
|
| 483 |
-
"metadata": {},
|
| 484 |
-
"execution_count": 17
|
| 485 |
-
}
|
| 486 |
-
]
|
| 487 |
-
},
|
| 488 |
-
{
|
| 489 |
-
"cell_type": "code",
|
| 490 |
-
"source": [
|
| 491 |
-
"import os\n",
|
| 492 |
-
"os.environ[\"agentkey\"] = \"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\"\n",
|
| 493 |
-
"\n",
|
| 494 |
-
"origin = \"90.4125,23.8103\" # Dhaka\n",
|
| 495 |
-
"destination = \"91.7832,22.3569\" # Chittagong\n",
|
| 496 |
-
"\n",
|
| 497 |
-
"result = navigate_with_ai(origin, destination, os.getenv(\"agentkey\"))\n",
|
| 498 |
-
"print(result)"
|
| 499 |
-
],
|
| 500 |
-
"metadata": {
|
| 501 |
-
"colab": {
|
| 502 |
-
"base_uri": "https://localhost:8080/"
|
| 503 |
-
},
|
| 504 |
-
"id": "y-1ex5XV3g4I",
|
| 505 |
-
"outputId": "a322b4bc-6325-4d19-f6e0-85467c9b9f8d"
|
| 506 |
-
},
|
| 507 |
-
"execution_count": 18,
|
| 508 |
-
"outputs": [
|
| 509 |
-
{
|
| 510 |
-
"output_type": "stream",
|
| 511 |
-
"name": "stdout",
|
| 512 |
-
"text": [
|
| 513 |
-
"🚀 Starting AI Navigation Agent...\n",
|
| 514 |
-
"📍 Route: 90.4125,23.8103 → 91.7832,22.3569\n",
|
| 515 |
-
"🔍 Fetching route from 90.4125,23.8103 to 91.7832,22.3569...\n",
|
| 516 |
-
"✅ Route found: 250.4km, ~186 minutes\n",
|
| 517 |
-
"🤖 Generating AI summary with DeepSeek V3.1 Terminus...\n",
|
| 518 |
-
"Of course! Here is a clear and helpful navigation summary based on your route data.\n",
|
| 519 |
-
"\n",
|
| 520 |
-
"### 🧭 Navigation Summary\n",
|
| 521 |
-
"\n",
|
| 522 |
-
"**📍 Journey Overview**\n",
|
| 523 |
-
"* **Total Distance:** 250.4 km\n",
|
| 524 |
-
"* **Estimated Time:** ~3 hours 6 minutes\n",
|
| 525 |
-
"* **Primary Route:** This is a long-distance journey primarily following major highways from the Dhaka area towards Chittagong. The route uses key arteries like the **Dhaka Elevated Expressway**, **Dhaka–Kumilla Mahasarak (Highway)**, and finally the **Dhaka–Chittagong Mahasarak**.\n",
|
| 526 |
-
"\n",
|
| 527 |
-
"---\n",
|
| 528 |
-
"\n",
|
| 529 |
-
"### 🛣️ Simplified Turn-by-Turn Directions\n",
|
| 530 |
-
"\n",
|
| 531 |
-
"Here are the essential steps to focus on. For the long stretches on the highway, you will mainly just continue straight.\n",
|
| 532 |
-
"\n",
|
| 533 |
-
"1. **Start:** Begin on **Lane 11 East**.\n",
|
| 534 |
-
"2. 🛣️ **Key Start:** Merge onto the **Dhaka Elevated Expressway** and follow it for about 2.6 km.\n",
|
| 535 |
-
"3. 🔁 **Roundabout:** Take the roundabout onto **Khamar Bari Sarak**, then turn right onto **Kazi Nazrul Islam Sarani**.\n",
|
| 536 |
-
"4. 🛣️ **Major Highway:** After navigating through the city, you will merge onto the **Dhaka–Kumilla Mahasarak**. This is your main road for a significant portion of the journey.\n",
|
| 537 |
-
"5. 🌉 **Key Landmark:** Cross the **Daudkandi Setu (Bridge)** at around the 3-hour mark.\n",
|
| 538 |
-
"6. 🛣️ **Highway Change:** The road continues as the **Dhaka–Chittagong Mahasarak**. Continue straight for the remainder of the trip (over 120 km).\n",
|
| 539 |
-
"7. **End:** Your destination is near the end of **Bondor Songjog Sarak**.\n",
|
| 540 |
-
"\n",
|
| 541 |
-
"---\n",
|
| 542 |
-
"\n",
|
| 543 |
-
"### 💡 Notable Features & Potential Challenges\n",
|
| 544 |
-
"\n",
|
| 545 |
-
"* **Multiple Road Name Changes:** The highway is referred to by several similar names (e.g., ঢাকা–কুমিল্লা মহাসড়ক, ঢাকা-চট্টগ্রাম মহাসড়ক). Don't be alarmed; this is normal. Just continue following the main highway.\n",
|
| 546 |
-
"* **Urban Start:** The beginning of the route in Dhaka involves several turns, roundabouts, and flyovers (like the Mayor Mohammad Hanif Flyover). Pay close attention to navigation during this section.\n",
|
| 547 |
-
"* **Long Highway Stretch:** The majority of the drive is a long, relatively straight highway. Stay alert for occasional forks where you need to keep \"slight right\" to stay on the main road.\n",
|
| 548 |
-
"* **Potential for Traffic:** Being a major corridor between two major cities, expect the potential for heavy traffic, especially near urban areas and toll plazas.\n",
|
| 549 |
-
"\n",
|
| 550 |
-
"---\n",
|
| 551 |
-
"\n",
|
| 552 |
-
"### ✅ Confidence Assessment\n",
|
| 553 |
-
"\n",
|
| 554 |
-
"**Confidence Level: High 👍**\n",
|
| 555 |
-
"\n",
|
| 556 |
-
"* **Reasoning:** The route is logical and follows the most direct major highways available for this journey. The turn-by-turn instructions are very detailed. The main \"challenge\" is not the route's accuracy, but the need for vigilance during the complex urban section at the start and during long, monotonous highway driving.\n",
|
| 557 |
-
"\n",
|
| 558 |
-
"**Have a safe and pleasant journey!** 🚗💨\n"
|
| 559 |
-
]
|
| 560 |
-
}
|
| 561 |
-
]
|
| 562 |
-
}
|
| 563 |
-
]
|
| 564 |
-
}
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import re
|
| 3 |
+
import json
|
| 4 |
+
import requests
|
| 5 |
+
import pandas as pd
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Optional, Union, Dict, Any, List
|
| 8 |
+
from dotenv import load_dotenv
|
| 9 |
+
|
| 10 |
+
from langgraph.graph import StateGraph, MessagesState
|
| 11 |
+
from langgraph.prebuilt import create_react_agent
|
| 12 |
+
from langchain_core.messages import HumanMessage, SystemMessage
|
| 13 |
+
from langchain_core.tools import tool
|
| 14 |
+
from langchain_openai import ChatOpenAI
|
| 15 |
+
|
| 16 |
+
load_dotenv()
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class OpenRouterLLM(ChatOpenAI):
|
| 20 |
+
"""Custom OpenRouter LLM wrapper for LangGraph"""
|
| 21 |
+
|
| 22 |
+
def __init__(self, model: str = "deepseek/deepseek-v3.1-terminus", **kwargs):
|
| 23 |
+
api_key = os.getenv("OPENROUTER_API_KEY") or os.getenv("my_key")
|
| 24 |
+
|
| 25 |
+
super().__init__(
|
| 26 |
+
model=model,
|
| 27 |
+
openai_api_key=api_key,
|
| 28 |
+
openai_api_base="https://openrouter.ai/api/v1",
|
| 29 |
+
**kwargs
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
@tool
|
| 34 |
+
def search_web(query: str) -> str:
|
| 35 |
+
"""Search the web using DuckDuckGo for current information."""
|
| 36 |
+
try:
|
| 37 |
+
# Simple web search using DuckDuckGo
|
| 38 |
+
search_url = f"https://api.duckduckgo.com/?q={query}&format=json&no_html=1&skip_disambig=1"
|
| 39 |
+
response = requests.get(search_url, timeout=10)
|
| 40 |
+
|
| 41 |
+
if response.status_code == 200:
|
| 42 |
+
data = response.json()
|
| 43 |
+
|
| 44 |
+
# Extract results
|
| 45 |
+
results = []
|
| 46 |
+
if data.get("AbstractText"):
|
| 47 |
+
results.append(f"Abstract: {data['AbstractText']}")
|
| 48 |
+
|
| 49 |
+
if data.get("RelatedTopics"):
|
| 50 |
+
for topic in data["RelatedTopics"][:3]:
|
| 51 |
+
if isinstance(topic, dict) and topic.get("Text"):
|
| 52 |
+
results.append(f"Related: {topic['Text']}")
|
| 53 |
+
|
| 54 |
+
if results:
|
| 55 |
+
return "\n".join(results)
|
| 56 |
+
else:
|
| 57 |
+
return f"Search performed for '{query}' but no specific results found."
|
| 58 |
+
else:
|
| 59 |
+
return f"Search failed with status code {response.status_code}"
|
| 60 |
+
|
| 61 |
+
except Exception as e:
|
| 62 |
+
return f"Search error: {str(e)}"
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
@tool
|
| 66 |
+
def search_wikipedia(query: str) -> str:
|
| 67 |
+
"""Search Wikipedia for factual information."""
|
| 68 |
+
try:
|
| 69 |
+
# Wikipedia API search
|
| 70 |
+
search_url = "https://en.wikipedia.org/api/rest_v1/page/summary/" + query.replace(" ", "_")
|
| 71 |
+
response = requests.get(search_url, timeout=10)
|
| 72 |
+
|
| 73 |
+
if response.status_code == 200:
|
| 74 |
+
data = response.json()
|
| 75 |
+
extract = data.get("extract", "")
|
| 76 |
+
if extract:
|
| 77 |
+
return f"Wikipedia: {extract[:500]}..."
|
| 78 |
+
else:
|
| 79 |
+
return f"Wikipedia page found for '{query}' but no extract available."
|
| 80 |
+
else:
|
| 81 |
+
return f"Wikipedia search failed for '{query}'"
|
| 82 |
+
|
| 83 |
+
except Exception as e:
|
| 84 |
+
return f"Wikipedia search error: {str(e)}"
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
@tool
|
| 88 |
+
def execute_python(code: str) -> str:
|
| 89 |
+
"""Execute Python code and return the result."""
|
| 90 |
+
try:
|
| 91 |
+
# Create a safe execution environment
|
| 92 |
+
safe_globals = {
|
| 93 |
+
'__builtins__': {
|
| 94 |
+
'print': print,
|
| 95 |
+
'len': len,
|
| 96 |
+
'str': str,
|
| 97 |
+
'int': int,
|
| 98 |
+
'float': float,
|
| 99 |
+
'bool': bool,
|
| 100 |
+
'list': list,
|
| 101 |
+
'dict': dict,
|
| 102 |
+
'tuple': tuple,
|
| 103 |
+
'set': set,
|
| 104 |
+
'range': range,
|
| 105 |
+
'sum': sum,
|
| 106 |
+
'max': max,
|
| 107 |
+
'min': min,
|
| 108 |
+
'abs': abs,
|
| 109 |
+
'round': round,
|
| 110 |
+
'sorted': sorted,
|
| 111 |
+
'enumerate': enumerate,
|
| 112 |
+
'zip': zip,
|
| 113 |
+
},
|
| 114 |
+
'math': __import__('math'),
|
| 115 |
+
'json': __import__('json'),
|
| 116 |
+
'datetime': __import__('datetime'),
|
| 117 |
+
'random': __import__('random'),
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
# Capture output
|
| 121 |
+
import io
|
| 122 |
+
import sys
|
| 123 |
+
|
| 124 |
+
old_stdout = sys.stdout
|
| 125 |
+
sys.stdout = mystdout = io.StringIO()
|
| 126 |
+
|
| 127 |
+
try:
|
| 128 |
+
# Execute the code
|
| 129 |
+
exec(code, safe_globals)
|
| 130 |
+
output = mystdout.getvalue()
|
| 131 |
+
finally:
|
| 132 |
+
sys.stdout = old_stdout
|
| 133 |
+
|
| 134 |
+
return output if output else "Code executed successfully (no output)"
|
| 135 |
+
|
| 136 |
+
except Exception as e:
|
| 137 |
+
return f"Python execution error: {str(e)}"
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
@tool
|
| 141 |
+
def read_excel_file(file_path: str, sheet_name: Optional[str] = None) -> str:
|
| 142 |
+
"""Read an Excel file and return its contents as a formatted string."""
|
| 143 |
+
try:
|
| 144 |
+
file_path_obj = Path(file_path)
|
| 145 |
+
if not file_path_obj.exists():
|
| 146 |
+
return f"Error: File not found at {file_path}"
|
| 147 |
+
|
| 148 |
+
# Try to read the Excel file
|
| 149 |
+
if sheet_name and sheet_name.isdigit():
|
| 150 |
+
sheet_name = int(sheet_name)
|
| 151 |
+
elif sheet_name is None:
|
| 152 |
+
sheet_name = 0
|
| 153 |
+
|
| 154 |
+
df = pd.read_excel(file_path, sheet_name=sheet_name)
|
| 155 |
+
|
| 156 |
+
# Convert to string representation
|
| 157 |
+
if len(df) > 20:
|
| 158 |
+
# Show first 10 and last 10 rows for large datasets
|
| 159 |
+
result = f"Excel file with {len(df)} rows and {len(df.columns)} columns:\n\n"
|
| 160 |
+
result += "First 10 rows:\n"
|
| 161 |
+
result += df.head(10).to_string(index=False)
|
| 162 |
+
result += f"\n\n... ({len(df) - 20} rows omitted) ...\n\n"
|
| 163 |
+
result += "Last 10 rows:\n"
|
| 164 |
+
result += df.tail(10).to_string(index=False)
|
| 165 |
+
else:
|
| 166 |
+
result = f"Excel file with {len(df)} rows and {len(df.columns)} columns:\n\n"
|
| 167 |
+
result += df.to_string(index=False)
|
| 168 |
+
|
| 169 |
+
return result
|
| 170 |
+
|
| 171 |
+
except Exception as e:
|
| 172 |
+
return f"Error reading Excel file: {str(e)}"
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
@tool
|
| 176 |
+
def read_text_file(file_path: str) -> str:
|
| 177 |
+
"""Read a text file and return its contents."""
|
| 178 |
+
try:
|
| 179 |
+
file_path_obj = Path(file_path)
|
| 180 |
+
if not file_path_obj.exists():
|
| 181 |
+
return f"Error: File not found at {file_path}"
|
| 182 |
+
|
| 183 |
+
# Try different encodings
|
| 184 |
+
encodings = ['utf-8', 'utf-16', 'iso-8859-1', 'cp1252']
|
| 185 |
+
|
| 186 |
+
for encoding in encodings:
|
| 187 |
+
try:
|
| 188 |
+
with open(file_path_obj, 'r', encoding=encoding) as f:
|
| 189 |
+
content = f.read()
|
| 190 |
+
return f"File content ({encoding} encoding):\n\n{content}"
|
| 191 |
+
except UnicodeDecodeError:
|
| 192 |
+
continue
|
| 193 |
+
|
| 194 |
+
return f"Error: Could not decode file with any standard encoding"
|
| 195 |
+
|
| 196 |
+
except Exception as e:
|
| 197 |
+
return f"Error reading file: {str(e)}"
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
class GaiaAgent:
|
| 201 |
+
"""LangGraph-based agent for GAIA tasks using OpenRouter DeepSeek"""
|
| 202 |
+
|
| 203 |
+
def __init__(self):
|
| 204 |
+
print("Initializing GaiaAgent with LangGraph and OpenRouter DeepSeek...")
|
| 205 |
+
|
| 206 |
+
# Initialize the LLM
|
| 207 |
+
self.llm = OpenRouterLLM(
|
| 208 |
+
model="deepseek/deepseek-v3.1-terminus",
|
| 209 |
+
temperature=0.1,
|
| 210 |
+
max_tokens=2000
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
# Define available tools
|
| 214 |
+
self.tools = [
|
| 215 |
+
search_web,
|
| 216 |
+
search_wikipedia,
|
| 217 |
+
execute_python,
|
| 218 |
+
read_excel_file,
|
| 219 |
+
read_text_file,
|
| 220 |
+
]
|
| 221 |
+
|
| 222 |
+
# Create the agent
|
| 223 |
+
self.agent = create_react_agent(
|
| 224 |
+
self.llm,
|
| 225 |
+
self.tools,
|
| 226 |
+
state_modifier=self._get_system_prompt()
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
print("GaiaAgent initialized successfully!")
|
| 230 |
+
|
| 231 |
+
def _get_system_prompt(self) -> str:
|
| 232 |
+
"""Get the system prompt for the agent"""
|
| 233 |
+
return """You are an advanced AI agent designed to answer complex questions that may require:
|
| 234 |
+
|
| 235 |
+
1. Web searches for current information
|
| 236 |
+
2. Mathematical calculations using Python
|
| 237 |
+
3. File analysis (Excel, text files)
|
| 238 |
+
4. Multi-step reasoning and problem solving
|
| 239 |
+
|
| 240 |
+
For GAIA evaluation:
|
| 241 |
+
- Provide EXACT, DIRECT answers
|
| 242 |
+
- Use tools when necessary to gather information or perform calculations
|
| 243 |
+
- For math problems, show your calculation but end with just the number
|
| 244 |
+
- For yes/no questions, answer just "Yes" or "No"
|
| 245 |
+
- For factual questions, provide just the fact
|
| 246 |
+
|
| 247 |
+
When you encounter files:
|
| 248 |
+
- Use read_excel_file for .xlsx, .xls files
|
| 249 |
+
- Use read_text_file for text-based files
|
| 250 |
+
- Analyze the file content to answer the question
|
| 251 |
+
|
| 252 |
+
Be thorough in your analysis but concise in your final answer."""
|
| 253 |
+
|
| 254 |
+
def __call__(self, task_id: str, question: str) -> str:
|
| 255 |
+
"""Process a question and return the answer"""
|
| 256 |
+
try:
|
| 257 |
+
print(f"Processing task {task_id}: {question[:100]}...")
|
| 258 |
+
|
| 259 |
+
# Create the input state
|
| 260 |
+
messages = [HumanMessage(content=question)]
|
| 261 |
+
|
| 262 |
+
# Run the agent
|
| 263 |
+
result = self.agent.invoke({"messages": messages})
|
| 264 |
+
|
| 265 |
+
# Extract the final answer
|
| 266 |
+
final_message = result["messages"][-1]
|
| 267 |
+
answer = final_message.content
|
| 268 |
+
|
| 269 |
+
# Clean up the answer for GAIA evaluation
|
| 270 |
+
clean_answer = self._clean_answer(answer)
|
| 271 |
+
|
| 272 |
+
print(f"Agent answer for {task_id}: {clean_answer}")
|
| 273 |
+
return clean_answer
|
| 274 |
+
|
| 275 |
+
except Exception as e:
|
| 276 |
+
error_msg = f"Agent error: {str(e)}"
|
| 277 |
+
print(f"Error processing task {task_id}: {error_msg}")
|
| 278 |
+
return error_msg
|
| 279 |
+
|
| 280 |
+
def _clean_answer(self, answer: str) -> str:
|
| 281 |
+
"""Clean the answer to extract the final result"""
|
| 282 |
+
answer = answer.strip()
|
| 283 |
+
|
| 284 |
+
# Look for "Final Answer:" pattern
|
| 285 |
+
if "final answer:" in answer.lower():
|
| 286 |
+
parts = re.split(r'final answer:', answer, flags=re.IGNORECASE)
|
| 287 |
+
if len(parts) > 1:
|
| 288 |
+
answer = parts[-1].strip()
|
| 289 |
+
|
| 290 |
+
# Remove common prefixes
|
| 291 |
+
prefixes = [
|
| 292 |
+
"The answer is", "Answer:", "Result:", "Solution:",
|
| 293 |
+
"Based on", "Therefore", "In conclusion", "So the answer is"
|
| 294 |
+
]
|
| 295 |
+
|
| 296 |
+
for prefix in prefixes:
|
| 297 |
+
if answer.lower().startswith(prefix.lower()):
|
| 298 |
+
answer = answer[len(prefix):].strip()
|
| 299 |
+
if answer.startswith(':'):
|
| 300 |
+
answer = answer[1:].strip()
|
| 301 |
+
break
|
| 302 |
+
|
| 303 |
+
# Remove quotes and periods from short answers
|
| 304 |
+
if len(answer.split()) <= 3:
|
| 305 |
+
answer = answer.strip('"\'.')
|
| 306 |
+
|
| 307 |
+
return answer
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|