{ "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" ] } ] } ] }