Mehedi2 commited on
Commit
ed66f64
·
verified ·
1 Parent(s): 5966015

Update agent.ipynb

Browse files
Files changed (1) hide show
  1. agent.ipynb +307 -564
agent.ipynb CHANGED
@@ -1,564 +1,307 @@
1
- {
2
- "nbformat": 4,
3
- "nbformat_minor": 0,
4
- "metadata": {
5
- "colab": {
6
- "provenance": [],
7
- "gpuType": "T4"
8
- },
9
- "kernelspec": {
10
- "name": "python3",
11
- "display_name": "Python 3"
12
- },
13
- "language_info": {
14
- "name": "python"
15
- },
16
- "accelerator": "GPU"
17
- },
18
- "cells": [
19
- {
20
- "cell_type": "code",
21
- "source": [],
22
- "metadata": {
23
- "id": "l5JkHf8C2-r5"
24
- },
25
- "execution_count": null,
26
- "outputs": []
27
- },
28
- {
29
- "cell_type": "code",
30
- "source": [
31
- "import os\n",
32
- "import requests\n",
33
- "import json\n",
34
- "from typing import Dict, Any, Optional\n",
35
- "\n",
36
- "class OpenRouterLLM:\n",
37
- " def __init__(self, api_key: str, model: str = \"deepseek/deepseek-v3.1-terminus\"):\n",
38
- " self.api_key = api_key\n",
39
- " self.model = model\n",
40
- " self.base_url = \"https://openrouter.ai/api/v1/chat/completions\"\n",
41
- "\n",
42
- " def __call__(self, prompt: str, max_tokens: int = 1000, temperature: float = 0.3) -> str:\n",
43
- " \"\"\"Make API call to OpenRouter with DeepSeek V3.1 Terminus\"\"\"\n",
44
- "\n",
45
- " # Validate API key format\n",
46
- " if not self.api_key or not self.api_key.startswith('sk-or-v1-'):\n",
47
- " return \"Error: Invalid OpenRouter API key format. Should start with 'sk-or-v1-'\"\n",
48
- "\n",
49
- " headers = {\n",
50
- " \"Authorization\": f\"Bearer {self.api_key}\",\n",
51
- " \"Content-Type\": \"application/json\",\n",
52
- " \"HTTP-Referer\": \"https://github.com/navigation-agent\",\n",
53
- " \"X-Title\": \"Navigation Agent with DeepSeek V3.1 Terminus\"\n",
54
- " }\n",
55
- "\n",
56
- " payload = {\n",
57
- " \"model\": self.model,\n",
58
- " \"messages\": [\n",
59
- " {\n",
60
- " \"role\": \"system\",\n",
61
- " \"content\": \"You are a helpful navigation assistant. Provide clear, concise, and user-friendly route summaries.\"\n",
62
- " },\n",
63
- " {\n",
64
- " \"role\": \"user\",\n",
65
- " \"content\": prompt\n",
66
- " }\n",
67
- " ],\n",
68
- " \"temperature\": temperature,\n",
69
- " \"max_tokens\": max_tokens,\n",
70
- " \"top_p\": 0.9\n",
71
- " }\n",
72
- "\n",
73
- " try:\n",
74
- " response = requests.post(\n",
75
- " self.base_url,\n",
76
- " headers=headers,\n",
77
- " json=payload,\n",
78
- " timeout=30\n",
79
- " )\n",
80
- "\n",
81
- " # Handle different HTTP status codes\n",
82
- " if response.status_code == 401:\n",
83
- " return \"❌ Error: Invalid API key or unauthorized. Please check your OpenRouter API key.\"\n",
84
- " elif response.status_code == 402:\n",
85
- " return \"❌ Error: Insufficient credits. Please add credits to your OpenRouter account.\"\n",
86
- " elif response.status_code == 429:\n",
87
- " return \"❌ Error: Rate limit exceeded. Please wait and try again.\"\n",
88
- " elif response.status_code == 500:\n",
89
- " return \" Error: Server error. Please try again later.\"\n",
90
- " elif response.status_code != 200:\n",
91
- " error_text = response.text[:200] if response.text else \"Unknown error\"\n",
92
- " return f\"❌ Error: HTTP {response.status_code} - {error_text}\"\n",
93
- "\n",
94
- " result = response.json()\n",
95
- "\n",
96
- " # Extract the response content\n",
97
- " if \"choices\" in result and len(result[\"choices\"]) > 0:\n",
98
- " content = result[\"choices\"][0][\"message\"][\"content\"].strip()\n",
99
- " return content\n",
100
- " else:\n",
101
- " return \"❌ Error: No response content received from the model.\"\n",
102
- "\n",
103
- " except requests.exceptions.Timeout:\n",
104
- " return \"❌ Error: Request timeout. Please check your internet connection.\"\n",
105
- " except requests.exceptions.RequestException as e:\n",
106
- " return f\"❌ Error calling OpenRouter API: {str(e)}\"\n",
107
- " except json.JSONDecodeError:\n",
108
- " return \"❌ Error: Invalid JSON response from API.\"\n",
109
- " except (KeyError, IndexError) as e:\n",
110
- " return f\"❌ Error parsing API response: {str(e)}\"\n",
111
- "\n",
112
- "# Simple Graph implementation for LangGraph-like functionality\n",
113
- "class Node:\n",
114
- " def __init__(self, id: str, run_func):\n",
115
- " self.id = id\n",
116
- " self.run = run_func\n",
117
- "\n",
118
- "class NavigationGraph:\n",
119
- " def __init__(self):\n",
120
- " self.nodes = {}\n",
121
- " self.node_order = []\n",
122
- "\n",
123
- " def add_node(self, node: Node):\n",
124
- " self.nodes[node.id] = node\n",
125
- " if node.id not in self.node_order:\n",
126
- " self.node_order.append(node.id)\n",
127
- "\n",
128
- " def run(self, inputs: Dict[str, Any]) -> Dict[str, Any]:\n",
129
- " data = inputs.copy()\n",
130
- "\n",
131
- " for node_id in self.node_order:\n",
132
- " if node_id in self.nodes:\n",
133
- " try:\n",
134
- " result = self.nodes[node_id].run(data)\n",
135
- " if result:\n",
136
- " data.update(result)\n",
137
- " except Exception as e:\n",
138
- " data[f\"{node_id}_error\"] = f\"Error in {node_id}: {str(e)}\"\n",
139
- "\n",
140
- " return data\n",
141
- "\n",
142
- "def fetch_route_from_osrm(origin: str, destination: str) -> str:\n",
143
- " \"\"\"\n",
144
- " Fetch detailed route from OSRM API with comprehensive error handling\n",
145
- "\n",
146
- " Args:\n",
147
- " origin: \"longitude,latitude\" format\n",
148
- " destination: \"longitude,latitude\" format\n",
149
- "\n",
150
- " Returns:\n",
151
- " Formatted route instructions or error message\n",
152
- " \"\"\"\n",
153
- "\n",
154
- " # Validate coordinate format\n",
155
- " try:\n",
156
- " origin_parts = origin.split(',')\n",
157
- " dest_parts = destination.split(',')\n",
158
- "\n",
159
- " if len(origin_parts) != 2 or len(dest_parts) != 2:\n",
160
- " return \" Error: Coordinates must be in 'longitude,latitude' format\"\n",
161
- "\n",
162
- " # Try to parse as floats to validate\n",
163
- " float(origin_parts[0]), float(origin_parts[1])\n",
164
- " float(dest_parts[0]), float(dest_parts[1])\n",
165
- "\n",
166
- " except (ValueError, IndexError):\n",
167
- " return \"❌ Error: Invalid coordinate format. Use 'longitude,latitude'\"\n",
168
- "\n",
169
- " # Build OSRM URL\n",
170
- " url = f\"http://router.project-osrm.org/route/v1/driving/{origin};{destination}\"\n",
171
- " params = {\n",
172
- " \"overview\": \"false\",\n",
173
- " \"steps\": \"true\",\n",
174
- " \"geometries\": \"geojson\"\n",
175
- " }\n",
176
- "\n",
177
- " try:\n",
178
- " print(f\"🔍 Fetching route from {origin} to {destination}...\")\n",
179
- "\n",
180
- " response = requests.get(url, params=params, timeout=15)\n",
181
- " response.raise_for_status()\n",
182
- " data = response.json()\n",
183
- "\n",
184
- " # Check if route exists\n",
185
- " if not data.get(\"routes\") or len(data[\"routes\"]) == 0:\n",
186
- " return \"❌ No route found between the specified locations. Please check your coordinates.\"\n",
187
- "\n",
188
- " route = data[\"routes\"][0]\n",
189
- " total_distance_km = route.get(\"distance\", 0) / 1000\n",
190
- " total_duration_min = route.get(\"duration\", 0) / 60\n",
191
- "\n",
192
- " print(f\"✅ Route found: {total_distance_km:.1f}km, ~{total_duration_min:.0f} minutes\")\n",
193
- "\n",
194
- " # Process turn-by-turn instructions\n",
195
- " instructions = []\n",
196
- " step_number = 1\n",
197
- "\n",
198
- " for leg in route[\"legs\"]:\n",
199
- " for step in leg[\"steps\"]:\n",
200
- " maneuver = step.get(\"maneuver\", {})\n",
201
- " step_type = maneuver.get(\"type\", \"continue\")\n",
202
- " modifier = maneuver.get(\"modifier\", \"\")\n",
203
- " road_name = step.get(\"name\", \"\")\n",
204
- " distance_m = step.get(\"distance\", 0)\n",
205
- "\n",
206
- " # Skip very short steps (less than 10 meters)\n",
207
- " if distance_m < 10:\n",
208
- " continue\n",
209
- "\n",
210
- " # Build human-readable instruction\n",
211
- " instruction = f\"{step_number}. \"\n",
212
- "\n",
213
- " if step_type == \"depart\":\n",
214
- " direction = \"Start your journey\"\n",
215
- " if modifier:\n",
216
- " direction += f\" heading {modifier}\"\n",
217
- " if road_name:\n",
218
- " direction += f\" on {road_name}\"\n",
219
- "\n",
220
- " elif step_type == \"arrive\":\n",
221
- " instruction += \"🎯 You have arrived at your destination!\"\n",
222
- " instructions.append(instruction)\n",
223
- " break\n",
224
- "\n",
225
- " elif step_type == \"turn\":\n",
226
- " direction = f\"Turn {modifier}\" if modifier else \"Turn\"\n",
227
- " if road_name:\n",
228
- " direction += f\" onto {road_name}\"\n",
229
- "\n",
230
- " elif step_type == \"merge\":\n",
231
- " direction = f\"Merge {modifier}\" if modifier else \"Merge\"\n",
232
- " if road_name:\n",
233
- " direction += f\" onto {road_name}\"\n",
234
- "\n",
235
- " elif step_type == \"continue\":\n",
236
- " direction = \"Continue straight\"\n",
237
- " if road_name:\n",
238
- " direction += f\" on {road_name}\"\n",
239
- "\n",
240
- " elif step_type == \"roundabout\":\n",
241
- " direction = f\"Take the roundabout\"\n",
242
- " if modifier:\n",
243
- " direction += f\" and exit {modifier}\"\n",
244
- " if road_name:\n",
245
- " direction += f\" onto {road_name}\"\n",
246
- "\n",
247
- " else:\n",
248
- " # Handle other maneuver types\n",
249
- " direction = f\"{step_type.replace('_', ' ').title()}\"\n",
250
- " if modifier:\n",
251
- " direction += f\" {modifier}\"\n",
252
- " if road_name:\n",
253
- " direction += f\" on {road_name}\"\n",
254
- "\n",
255
- " # Add distance information for longer steps\n",
256
- " if distance_m >= 100:\n",
257
- " if distance_m >= 1000:\n",
258
- " direction += f\" for {distance_m/1000:.1f} km\"\n",
259
- " else:\n",
260
- " direction += f\" for {distance_m:.0f} meters\"\n",
261
- "\n",
262
- " instruction += direction\n",
263
- " instructions.append(instruction)\n",
264
- " step_number += 1\n",
265
- "\n",
266
- " # Build comprehensive route summary\n",
267
- " route_summary = f\"\"\"\n",
268
- "📍 ROUTE SUMMARY\n",
269
- "📊 Distance: {total_distance_km:.1f} km\n",
270
- "⏱️ Estimated Time: {total_duration_min:.0f} minutes\n",
271
- "🛣️ From: {origin} → To: {destination}\n",
272
- "\n",
273
- "🧭 TURN-BY-TURN DIRECTIONS:\n",
274
- "{chr(10).join(instructions)}\n",
275
- "\n",
276
- "💡 Total Steps: {len(instructions)}\n",
277
- "\"\"\"\n",
278
- "\n",
279
- " return route_summary.strip()\n",
280
- "\n",
281
- " except requests.exceptions.Timeout:\n",
282
- " return \"❌ Error: Request timeout while fetching route data. Please try again.\"\n",
283
- " except requests.exceptions.RequestException as e:\n",
284
- " return f\"❌ Error fetching route from OSRM: {str(e)}\"\n",
285
- " except json.JSONDecodeError:\n",
286
- " return \"❌ Error: Invalid response from routing service.\"\n",
287
- " except Exception as e:\n",
288
- " return f\"❌ Error processing route data: {str(e)}\"\n",
289
- "\n",
290
- "def create_navigation_agent(api_key: str) -> NavigationGraph:\n",
291
- " \"\"\"\n",
292
- " Create navigation agent with DeepSeek V3.1 Terminus integration\n",
293
- " \"\"\"\n",
294
- "\n",
295
- " # Initialize LLM with DeepSeek V3.1 Terminus\n",
296
- " llm = OpenRouterLLM(api_key=api_key, model=\"deepseek/deepseek-v3.1-terminus\")\n",
297
- "\n",
298
- " # Route fetching node\n",
299
- " def route_fetcher_node(inputs):\n",
300
- " origin = inputs.get(\"origin\", \"\").strip()\n",
301
- " destination = inputs.get(\"destination\", \"\").strip()\n",
302
- "\n",
303
- " if not origin or not destination:\n",
304
- " return {\"error\": \"❌ Error: Both origin and destination coordinates are required\"}\n",
305
- "\n",
306
- " raw_route = fetch_route_from_osrm(origin, destination)\n",
307
- " return {\"raw_route\": raw_route}\n",
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