File size: 26,807 Bytes
acc671c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": [],
      "gpuType": "T4"
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    },
    "accelerator": "GPU"
  },
  "cells": [
    {
      "cell_type": "code",
      "source": [],
      "metadata": {
        "id": "l5JkHf8C2-r5"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "import os\n",
        "import requests\n",
        "import json\n",
        "from typing import Dict, Any, Optional\n",
        "\n",
        "class OpenRouterLLM:\n",
        "    def __init__(self, api_key: str, model: str = \"deepseek/deepseek-v3.1-terminus\"):\n",
        "        self.api_key = api_key\n",
        "        self.model = model\n",
        "        self.base_url = \"https://openrouter.ai/api/v1/chat/completions\"\n",
        "\n",
        "    def __call__(self, prompt: str, max_tokens: int = 1000, temperature: float = 0.3) -> str:\n",
        "        \"\"\"Make API call to OpenRouter with DeepSeek V3.1 Terminus\"\"\"\n",
        "\n",
        "        # Validate API key format\n",
        "        if not self.api_key or not self.api_key.startswith('sk-or-v1-'):\n",
        "            return \"Error: Invalid OpenRouter API key format. Should start with 'sk-or-v1-'\"\n",
        "\n",
        "        headers = {\n",
        "            \"Authorization\": f\"Bearer {self.api_key}\",\n",
        "            \"Content-Type\": \"application/json\",\n",
        "            \"HTTP-Referer\": \"https://github.com/navigation-agent\",\n",
        "            \"X-Title\": \"Navigation Agent with DeepSeek V3.1 Terminus\"\n",
        "        }\n",
        "\n",
        "        payload = {\n",
        "            \"model\": self.model,\n",
        "            \"messages\": [\n",
        "                {\n",
        "                    \"role\": \"system\",\n",
        "                    \"content\": \"You are a helpful navigation assistant. Provide clear, concise, and user-friendly route summaries.\"\n",
        "                },\n",
        "                {\n",
        "                    \"role\": \"user\",\n",
        "                    \"content\": prompt\n",
        "                }\n",
        "            ],\n",
        "            \"temperature\": temperature,\n",
        "            \"max_tokens\": max_tokens,\n",
        "            \"top_p\": 0.9\n",
        "        }\n",
        "\n",
        "        try:\n",
        "            response = requests.post(\n",
        "                self.base_url,\n",
        "                headers=headers,\n",
        "                json=payload,\n",
        "                timeout=30\n",
        "            )\n",
        "\n",
        "            # Handle different HTTP status codes\n",
        "            if response.status_code == 401:\n",
        "                return \"❌ Error: Invalid API key or unauthorized. Please check your OpenRouter API key.\"\n",
        "            elif response.status_code == 402:\n",
        "                return \"❌ Error: Insufficient credits. Please add credits to your OpenRouter account.\"\n",
        "            elif response.status_code == 429:\n",
        "                return \"❌ Error: Rate limit exceeded. Please wait and try again.\"\n",
        "            elif response.status_code == 500:\n",
        "                return \"❌ Error: Server error. Please try again later.\"\n",
        "            elif response.status_code != 200:\n",
        "                error_text = response.text[:200] if response.text else \"Unknown error\"\n",
        "                return f\"❌ Error: HTTP {response.status_code} - {error_text}\"\n",
        "\n",
        "            result = response.json()\n",
        "\n",
        "            # Extract the response content\n",
        "            if \"choices\" in result and len(result[\"choices\"]) > 0:\n",
        "                content = result[\"choices\"][0][\"message\"][\"content\"].strip()\n",
        "                return content\n",
        "            else:\n",
        "                return \"❌ Error: No response content received from the model.\"\n",
        "\n",
        "        except requests.exceptions.Timeout:\n",
        "            return \"❌ Error: Request timeout. Please check your internet connection.\"\n",
        "        except requests.exceptions.RequestException as e:\n",
        "            return f\"❌ Error calling OpenRouter API: {str(e)}\"\n",
        "        except json.JSONDecodeError:\n",
        "            return \"❌ Error: Invalid JSON response from API.\"\n",
        "        except (KeyError, IndexError) as e:\n",
        "            return f\"❌ Error parsing API response: {str(e)}\"\n",
        "\n",
        "# Simple Graph implementation for LangGraph-like functionality\n",
        "class Node:\n",
        "    def __init__(self, id: str, run_func):\n",
        "        self.id = id\n",
        "        self.run = run_func\n",
        "\n",
        "class NavigationGraph:\n",
        "    def __init__(self):\n",
        "        self.nodes = {}\n",
        "        self.node_order = []\n",
        "\n",
        "    def add_node(self, node: Node):\n",
        "        self.nodes[node.id] = node\n",
        "        if node.id not in self.node_order:\n",
        "            self.node_order.append(node.id)\n",
        "\n",
        "    def run(self, inputs: Dict[str, Any]) -> Dict[str, Any]:\n",
        "        data = inputs.copy()\n",
        "\n",
        "        for node_id in self.node_order:\n",
        "            if node_id in self.nodes:\n",
        "                try:\n",
        "                    result = self.nodes[node_id].run(data)\n",
        "                    if result:\n",
        "                        data.update(result)\n",
        "                except Exception as e:\n",
        "                    data[f\"{node_id}_error\"] = f\"Error in {node_id}: {str(e)}\"\n",
        "\n",
        "        return data\n",
        "\n",
        "def fetch_route_from_osrm(origin: str, destination: str) -> str:\n",
        "    \"\"\"\n",
        "    Fetch detailed route from OSRM API with comprehensive error handling\n",
        "\n",
        "    Args:\n",
        "        origin: \"longitude,latitude\" format\n",
        "        destination: \"longitude,latitude\" format\n",
        "\n",
        "    Returns:\n",
        "        Formatted route instructions or error message\n",
        "    \"\"\"\n",
        "\n",
        "    # Validate coordinate format\n",
        "    try:\n",
        "        origin_parts = origin.split(',')\n",
        "        dest_parts = destination.split(',')\n",
        "\n",
        "        if len(origin_parts) != 2 or len(dest_parts) != 2:\n",
        "            return \"❌ Error: Coordinates must be in 'longitude,latitude' format\"\n",
        "\n",
        "        # Try to parse as floats to validate\n",
        "        float(origin_parts[0]), float(origin_parts[1])\n",
        "        float(dest_parts[0]), float(dest_parts[1])\n",
        "\n",
        "    except (ValueError, IndexError):\n",
        "        return \"❌ Error: Invalid coordinate format. Use 'longitude,latitude'\"\n",
        "\n",
        "    # Build OSRM URL\n",
        "    url = f\"http://router.project-osrm.org/route/v1/driving/{origin};{destination}\"\n",
        "    params = {\n",
        "        \"overview\": \"false\",\n",
        "        \"steps\": \"true\",\n",
        "        \"geometries\": \"geojson\"\n",
        "    }\n",
        "\n",
        "    try:\n",
        "        print(f\"🔍 Fetching route from {origin} to {destination}...\")\n",
        "\n",
        "        response = requests.get(url, params=params, timeout=15)\n",
        "        response.raise_for_status()\n",
        "        data = response.json()\n",
        "\n",
        "        # Check if route exists\n",
        "        if not data.get(\"routes\") or len(data[\"routes\"]) == 0:\n",
        "            return \"❌ No route found between the specified locations. Please check your coordinates.\"\n",
        "\n",
        "        route = data[\"routes\"][0]\n",
        "        total_distance_km = route.get(\"distance\", 0) / 1000\n",
        "        total_duration_min = route.get(\"duration\", 0) / 60\n",
        "\n",
        "        print(f\"✅ Route found: {total_distance_km:.1f}km, ~{total_duration_min:.0f} minutes\")\n",
        "\n",
        "        # Process turn-by-turn instructions\n",
        "        instructions = []\n",
        "        step_number = 1\n",
        "\n",
        "        for leg in route[\"legs\"]:\n",
        "            for step in leg[\"steps\"]:\n",
        "                maneuver = step.get(\"maneuver\", {})\n",
        "                step_type = maneuver.get(\"type\", \"continue\")\n",
        "                modifier = maneuver.get(\"modifier\", \"\")\n",
        "                road_name = step.get(\"name\", \"\")\n",
        "                distance_m = step.get(\"distance\", 0)\n",
        "\n",
        "                # Skip very short steps (less than 10 meters)\n",
        "                if distance_m < 10:\n",
        "                    continue\n",
        "\n",
        "                # Build human-readable instruction\n",
        "                instruction = f\"{step_number}. \"\n",
        "\n",
        "                if step_type == \"depart\":\n",
        "                    direction = \"Start your journey\"\n",
        "                    if modifier:\n",
        "                        direction += f\" heading {modifier}\"\n",
        "                    if road_name:\n",
        "                        direction += f\" on {road_name}\"\n",
        "\n",
        "                elif step_type == \"arrive\":\n",
        "                    instruction += \"🎯 You have arrived at your destination!\"\n",
        "                    instructions.append(instruction)\n",
        "                    break\n",
        "\n",
        "                elif step_type == \"turn\":\n",
        "                    direction = f\"Turn {modifier}\" if modifier else \"Turn\"\n",
        "                    if road_name:\n",
        "                        direction += f\" onto {road_name}\"\n",
        "\n",
        "                elif step_type == \"merge\":\n",
        "                    direction = f\"Merge {modifier}\" if modifier else \"Merge\"\n",
        "                    if road_name:\n",
        "                        direction += f\" onto {road_name}\"\n",
        "\n",
        "                elif step_type == \"continue\":\n",
        "                    direction = \"Continue straight\"\n",
        "                    if road_name:\n",
        "                        direction += f\" on {road_name}\"\n",
        "\n",
        "                elif step_type == \"roundabout\":\n",
        "                    direction = f\"Take the roundabout\"\n",
        "                    if modifier:\n",
        "                        direction += f\" and exit {modifier}\"\n",
        "                    if road_name:\n",
        "                        direction += f\" onto {road_name}\"\n",
        "\n",
        "                else:\n",
        "                    # Handle other maneuver types\n",
        "                    direction = f\"{step_type.replace('_', ' ').title()}\"\n",
        "                    if modifier:\n",
        "                        direction += f\" {modifier}\"\n",
        "                    if road_name:\n",
        "                        direction += f\" on {road_name}\"\n",
        "\n",
        "                # Add distance information for longer steps\n",
        "                if distance_m >= 100:\n",
        "                    if distance_m >= 1000:\n",
        "                        direction += f\" for {distance_m/1000:.1f} km\"\n",
        "                    else:\n",
        "                        direction += f\" for {distance_m:.0f} meters\"\n",
        "\n",
        "                instruction += direction\n",
        "                instructions.append(instruction)\n",
        "                step_number += 1\n",
        "\n",
        "        # Build comprehensive route summary\n",
        "        route_summary = f\"\"\"\n",
        "📍 ROUTE SUMMARY\n",
        "📊 Distance: {total_distance_km:.1f} km\n",
        "⏱️ Estimated Time: {total_duration_min:.0f} minutes\n",
        "🛣️ From: {origin} → To: {destination}\n",
        "\n",
        "🧭 TURN-BY-TURN DIRECTIONS:\n",
        "{chr(10).join(instructions)}\n",
        "\n",
        "💡 Total Steps: {len(instructions)}\n",
        "\"\"\"\n",
        "\n",
        "        return route_summary.strip()\n",
        "\n",
        "    except requests.exceptions.Timeout:\n",
        "        return \"❌ Error: Request timeout while fetching route data. Please try again.\"\n",
        "    except requests.exceptions.RequestException as e:\n",
        "        return f\"❌ Error fetching route from OSRM: {str(e)}\"\n",
        "    except json.JSONDecodeError:\n",
        "        return \"❌ Error: Invalid response from routing service.\"\n",
        "    except Exception as e:\n",
        "        return f\"❌ Error processing route data: {str(e)}\"\n",
        "\n",
        "def create_navigation_agent(api_key: str) -> NavigationGraph:\n",
        "    \"\"\"\n",
        "    Create navigation agent with DeepSeek V3.1 Terminus integration\n",
        "    \"\"\"\n",
        "\n",
        "    # Initialize LLM with DeepSeek V3.1 Terminus\n",
        "    llm = OpenRouterLLM(api_key=api_key, model=\"deepseek/deepseek-v3.1-terminus\")\n",
        "\n",
        "    # Route fetching node\n",
        "    def route_fetcher_node(inputs):\n",
        "        origin = inputs.get(\"origin\", \"\").strip()\n",
        "        destination = inputs.get(\"destination\", \"\").strip()\n",
        "\n",
        "        if not origin or not destination:\n",
        "            return {\"error\": \"❌ Error: Both origin and destination coordinates are required\"}\n",
        "\n",
        "        raw_route = fetch_route_from_osrm(origin, destination)\n",
        "        return {\"raw_route\": raw_route}\n",
        "\n",
        "    # AI summarization node\n",
        "    def ai_summarizer_node(inputs):\n",
        "        raw_route = inputs.get(\"raw_route\", \"\")\n",
        "\n",
        "        if raw_route.startswith(\"\"):\n",
        "            # If there's an error in route fetching, pass it through\n",
        "            return {\"final_summary\": raw_route}\n",
        "\n",
        "        # Create detailed prompt for DeepSeek V3.1 Terminus\n",
        "        prompt = f\"\"\"\n",
        "I need you to analyze this route information and create a helpful navigation summary.\n",
        "\n",
        "ROUTE DATA:\n",
        "{raw_route}\n",
        "\n",
        "Please provide:\n",
        "1. A brief overview of the journey (distance, time, key roads)\n",
        "2. Simplified directions highlighting only the most important turns and landmarks\n",
        "3. Any notable features or potential challenges mentioned in the route\n",
        "4. A confidence assessment of the route quality\n",
        "\n",
        "Format your response to be clear and easy to follow while driving. Use emojis appropriately to make it more readable.\n",
        "\"\"\"\n",
        "\n",
        "        print(\"🤖 Generating AI summary with DeepSeek V3.1 Terminus...\")\n",
        "        ai_summary = llm(prompt, max_tokens=1200, temperature=0.2)\n",
        "\n",
        "        return {\"final_summary\": ai_summary}\n",
        "\n",
        "    # Create the graph\n",
        "    graph = NavigationGraph()\n",
        "\n",
        "    # Add nodes in order\n",
        "    route_node = Node(\"route_fetcher\", route_fetcher_node)\n",
        "    ai_node = Node(\"ai_summarizer\", ai_summarizer_node)\n",
        "\n",
        "    graph.add_node(route_node)\n",
        "    graph.add_node(ai_node)\n",
        "\n",
        "    return graph\n",
        "\n",
        "def navigate_with_ai(origin: str, destination: str, api_key: str) -> str:\n",
        "    \"\"\"\n",
        "    Main navigation function using DeepSeek V3.1 Terminus\n",
        "\n",
        "    Args:\n",
        "        origin: Origin coordinates as \"longitude,latitude\"\n",
        "        destination: Destination coordinates as \"longitude,latitude\"\n",
        "        api_key: OpenRouter API key\n",
        "\n",
        "    Returns:\n",
        "        AI-generated navigation summary\n",
        "    \"\"\"\n",
        "\n",
        "    print(\"🚀 Starting AI Navigation Agent...\")\n",
        "    print(f\"📍 Route: {origin} → {destination}\")\n",
        "\n",
        "    # Create and run the navigation agent\n",
        "    agent = create_navigation_agent(api_key)\n",
        "\n",
        "    result = agent.run({\n",
        "        \"origin\": origin,\n",
        "        \"destination\": destination\n",
        "    })\n",
        "\n",
        "    # Return the final summary\n",
        "    if \"final_summary\" in result:\n",
        "        return result[\"final_summary\"]\n",
        "    elif \"raw_route\" in result:\n",
        "        return result[\"raw_route\"]  # Fallback to raw route\n",
        "    else:\n",
        "        return \"❌ Error: Could not generate navigation instructions\"\n",
        "\n",
        "# Test function\n",
        "def test_navigation():\n",
        "    \"\"\"Test the navigation agent\"\"\"\n",
        "\n",
        "    api_key = os.getenv(\"my_key\")\n",
        "\n",
        "    if not api_key:\n",
        "        print(\"❌ Please set your OpenRouter API key:\")\n",
        "        print('os.environ[\"my_key\"] = \"sk-or-v1-your-actual-key\"')\n",
        "        return\n",
        "\n",
        "    # Test coordinates\n",
        "    dhaka = \"90.4125,23.8103\"        # Dhaka, Bangladesh\n",
        "    chittagong = \"91.7832,22.3569\"   # Chittagong, Bangladesh\n",
        "\n",
        "    print(\"=\" * 60)\n",
        "    print(\"🗺️  AI NAVIGATION AGENT - DEEPSEEK V3.1 TERMINUS\")\n",
        "    print(\"=\" * 60)\n",
        "\n",
        "    result = navigate_with_ai(dhaka, chittagong, api_key)\n",
        "\n",
        "    print(\"\\n\" + \"=\" * 60)\n",
        "    print(\"📋 NAVIGATION RESULT:\")\n",
        "    print(\"=\" * 60)\n",
        "    print(result)\n",
        "    print(\"=\" * 60)\n",
        "\n",
        "if __name__ == \"__main__\":\n",
        "    test_navigation()\n",
        "\n",
        "# === USAGE EXAMPLES ===\n",
        "\n",
        "# Example 1: Basic usage\n",
        "\"\"\"\n",
        "import os\n",
        "os.environ[\"my_key\"] = \"sk-or-v1-your-actual-openrouter-key\"\n",
        "\n",
        "origin = \"90.4125,23.8103\"       # Dhaka\n",
        "destination = \"91.7832,22.3569\"  # Chittagong\n",
        "\n",
        "result = navigate_with_ai(origin, destination, os.getenv(\"my_key\"))\n",
        "print(result)\n",
        "\"\"\"\n",
        "\n",
        "# Example 2: Custom coordinates\n",
        "\"\"\"\n",
        "# London to Manchester\n",
        "london = \"-0.1276,51.5074\"\n",
        "manchester = \"-2.2426,53.4808\"\n",
        "\n",
        "result = navigate_with_ai(london, manchester, os.getenv(\"my_key\"))\n",
        "print(result)\n",
        "\"\"\"\n",
        "\n",
        "# Example 3: Just test the LLM\n",
        "\"\"\"\n",
        "llm = OpenRouterLLM(api_key=os.getenv(\"my_key\"), model=\"deepseek/deepseek-v3.1-terminus\")\n",
        "response = llm(\"Hello! Can you help me with navigation between two cities?\")\n",
        "print(response)\n",
        "\"\"\""
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 296
        },
        "id": "FKufZbsh2_I4",
        "outputId": "e2fee184-143e-4757-8623-c62e08efe2cd"
      },
      "execution_count": 17,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "============================================================\n",
            "🗺️  AI NAVIGATION AGENT - DEEPSEEK V3.1 TERMINUS\n",
            "============================================================\n",
            "🚀 Starting AI Navigation Agent...\n",
            "📍 Route: 90.4125,23.8103 → 91.7832,22.3569\n",
            "🔍 Fetching route from 90.4125,23.8103 to 91.7832,22.3569...\n",
            "✅ Route found: 250.4km, ~186 minutes\n",
            "🤖 Generating AI summary with DeepSeek V3.1 Terminus...\n",
            "\n",
            "============================================================\n",
            "📋 NAVIGATION RESULT:\n",
            "============================================================\n",
            "❌ Error: Invalid API key or unauthorized. Please check your OpenRouter API key.\n",
            "============================================================\n"
          ]
        },
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "'\\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'"
            ],
            "application/vnd.google.colaboratory.intrinsic+json": {
              "type": "string"
            }
          },
          "metadata": {},
          "execution_count": 17
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "import os\n",
        "os.environ[\"agentkey\"] = \"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\"\n",
        "\n",
        "origin = \"90.4125,23.8103\"       # Dhaka\n",
        "destination = \"91.7832,22.3569\"  # Chittagong\n",
        "\n",
        "result = navigate_with_ai(origin, destination, os.getenv(\"agentkey\"))\n",
        "print(result)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "y-1ex5XV3g4I",
        "outputId": "a322b4bc-6325-4d19-f6e0-85467c9b9f8d"
      },
      "execution_count": 18,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "🚀 Starting AI Navigation Agent...\n",
            "📍 Route: 90.4125,23.8103 → 91.7832,22.3569\n",
            "🔍 Fetching route from 90.4125,23.8103 to 91.7832,22.3569...\n",
            "✅ Route found: 250.4km, ~186 minutes\n",
            "🤖 Generating AI summary with DeepSeek V3.1 Terminus...\n",
            "Of course! Here is a clear and helpful navigation summary based on your route data.\n",
            "\n",
            "### 🧭 Navigation Summary\n",
            "\n",
            "**📍 Journey Overview**\n",
            "*   **Total Distance:** 250.4 km\n",
            "*   **Estimated Time:** ~3 hours 6 minutes\n",
            "*   **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",
            "\n",
            "---\n",
            "\n",
            "### 🛣️ Simplified Turn-by-Turn Directions\n",
            "\n",
            "Here are the essential steps to focus on. For the long stretches on the highway, you will mainly just continue straight.\n",
            "\n",
            "1.  **Start:** Begin on **Lane 11 East**.\n",
            "2.  🛣️ **Key Start:** Merge onto the **Dhaka Elevated Expressway** and follow it for about 2.6 km.\n",
            "3.  🔁 **Roundabout:** Take the roundabout onto **Khamar Bari Sarak**, then turn right onto **Kazi Nazrul Islam Sarani**.\n",
            "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",
            "5.  🌉 **Key Landmark:** Cross the **Daudkandi Setu (Bridge)** at around the 3-hour mark.\n",
            "6.  🛣️ **Highway Change:** The road continues as the **Dhaka–Chittagong Mahasarak**. Continue straight for the remainder of the trip (over 120 km).\n",
            "7.  **End:** Your destination is near the end of **Bondor Songjog Sarak**.\n",
            "\n",
            "---\n",
            "\n",
            "### 💡 Notable Features & Potential Challenges\n",
            "\n",
            "*   **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",
            "*   **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",
            "*   **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",
            "*   **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",
            "\n",
            "---\n",
            "\n",
            "### ✅ Confidence Assessment\n",
            "\n",
            "**Confidence Level: High 👍**\n",
            "\n",
            "*   **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",
            "\n",
            "**Have a safe and pleasant journey!** 🚗💨\n"
          ]
        }
      ]
    }
  ]
}