Open
Conversation
…gement Agentic Chatbot: - Add agentic_chatbot.py with OpenAI function calling, local LLM support, dynamic system prompt - Add agentic_tools.py with 21 tool schemas and direct ToolExecutor - 3-tier fallback chain in /api/ai/chat (agentic → ultra → worldclass) - 8 Socket.IO listeners for real-time UI sync (scenario-controls.js) Visualization & State Management: - 3D/2D toggle with terrain, 3D buildings, and cinematic camera angles - Triangle arrow vehicles (SDF icons) with bearing-aligned rotation - 60fps vehicle interpolation loop with adaptive timing and easeOutCubic - Battery-color-coded EVs (red/orange/green) and state-based coloring (V2G, charging, stranded) - Traffic light zoom-fade (hidden when zoomed out) - Broadcast frame-skipping for performance (1 update per 5 physics steps) - vType-aware SUMO routing with edge permission error handling Infrastructure: - Dynamic Mapbox token loading from MAPBOX_TOKEN env var via /api/config - Bypass frontend LLM interception — all chat routed to backend
…d sync
New Tools:
- toggle_map_layer: show/hide map layers (lights, cables, EVs, substations, vehicles)
- set_map_view: switch between 2D (flat) and 3D (tilted) map perspectives
- fail_ev_station / restore_ev_station: individual EV station control
- trigger_blackout: fail all substations except one spare in a single command
Bug Fixes:
- Fix _run_ev_rush_test spawn queue format (was pushing {count: 30} instead of individual items with ev_percentage/battery_min_soc/battery_max_soc)
- Fix PyPSA Series index alignment in power_system.py to prevent ValueError on mismatched indices
- Fix scenario event log time format (use _format_time instead of raw value)
Improvements:
- System prompt now includes exact valid substation names, EV station IDs, and layer names to prevent LLM name-guessing failures
- Conversation history preserves tool call summaries across turns so LLM remembers past actions
- 6 new _emit_ui_updates handlers for real-time frontend sync (layer_toggle, map_view_change, ev_station_update, substation_update, ev_config_update, vehicles_spawned)
- 7 new Socket.IO listeners in scenario-controls.js for all new chatbot events
- Exposed toggleLayer, updateEVPercentage, updateBatteryRange on window for socket event handlers
…controls, fix incident logging error and clean up script.js
… links Snapshot: rewrite captureSnapshot() to produce comprehensive JSON with grid status, traffic, V2G, KPIs, scenario info alongside the map PNG. Add server-side /api/snapshot/state endpoint. Report: overhaul report_generator.py with 8 PDF sections (executive summary, per-substation table, traffic/EV, V2G ops, cable integrity, KPIs dashboard, optional map screenshot, AI-generated analysis). OpenAI-powered detailed analysis with rule-based fallback. Fix chatbot report download: auto-trigger PDF download via WebSocket event (trigger_report_download), add clickable download buttons in chat UI, pass url/download_link through tool_calls_made response. Also includes: clock flicker fix, initial layer visibility, scenario controller system-time init, agentic_tools fixes (_restore_all typo, missing _prepare_for_event, _trigger_blackout handler mapping), and reduced auto-scenario wait from 90s to 30s. Co-authored-by: Cursor <cursoragent@cursor.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Pull Request
📋 Description
This PR introduces real-time WebSocket architecture, a full agentic AI chatbot system with 26 LLM tools, enhanced 3D visualization, and comprehensive frontend-backend synchronization. It migrates the app from HTTP polling to event-driven WebSocket updates, adds an OpenAI function-calling chatbot that can control every aspect of the simulation, and delivers smoother vehicle rendering with 60fps interpolation.
Commits
e3fc4f4—feat: websocket migration (clean history)4b3d674—feat: agentic chatbot, 3D/2D toggle, smoother visuals, and state managementdb52edf—feat: expand agentic chatbot with 5 new tools, bug fixes, and frontend sync🔄 Type of Change
🧪 Testing
Test Configuration:
📸 Screenshots (if applicable)
Before:
After:
✅ Checklist
🔧 Implementation Details
Changes Made
Commit 1: WebSocket Migration (
e3fc4f4)main_complete_integration.py: Enhancedbroadcast_state()to push V2G active vehicle data and AI map focus coordinates viasystem_updateWebSocket event. Addedv2g_websocket_callback()for real-time restoration notifications.static/script.js: RemovedupdateLoop()andupdateV2GColorsOptimized()polling loops. AddedupdateV2GFromWebSocket()andapplyAIMapFocus()to process data from WebSocket events instead.static/scenario-director.js: RemovedstartChatbotMonitoring()polling loop. Added WebSocket listener forv2g_restoration_completeevents.static/scenario-controls.js: Added Socket.IO listeners for scenario sync events (scenario_time_update,scenario_temp_update,simulation_speed_update,substation_update,v2g_update, etc.)index.html: Updated cache-busting query parameters to force browser reload.core/power_system.py,sumo_manager.py,scenario_controller.py: Minor fixes for WebSocket integration.Commit 2: Agentic Chatbot & Visualization (
4b3d674)agentic_chatbot.py[NEW]: FullAgenticChatbotclass with OpenAI function-calling loop, dynamic system prompt with live grid state, conversation history management, 3-tier fallback (agentic → ultra → world-class), and_emit_ui_updatesfor real-time frontend sync via Socket.IO.agentic_tools.py[NEW]: 21 tool schemas andToolExecutorclass covering substation control, V2G management, simulation control, scenario management, EV configuration, system status queries, map control, and test scenarios.main_complete_integration.py: Integrated agentic chatbot as primary AI handler in/api/ai/chatroute with fallback chain. Added/api/configfor dynamic Mapbox token delivery.static/script.js: 3D terrain and buildings, triangle arrow vehicles with bearing-aligned rotation, 60fps interpolation loop witheaseOutCubic, battery-color-coded EVs, traffic light zoom-fade, dynamic Mapbox token loading. Bypassed frontend LLM interception — all chat routed to backend.static/scenario-controls.js: 8 Socket.IO listeners for agentic chatbot UI sync events.Commit 3: Chatbot Expansion & Bug Fixes (
db52edf)agentic_tools.py: Added 5 new tools (toggle_map_layer,set_map_view,fail_ev_station,restore_ev_station,trigger_blackout). Fixed_run_ev_rush_testspawn queue format bug.agentic_chatbot.py: System prompt now includes exact valid substation names, EV station IDs, and layer names. Conversation history preserves tool call summaries. Added 6 new_emit_ui_updateshandlers.core/power_system.py: FixedValueErrorfrom mismatched Series indices by aligningline_flowsandline_limitsbefore comparison (2 locations).scenario_controller.py: Fixed event log time format to use_format_time().static/scenario-controls.js: Added 7 new Socket.IO listeners (ev_config_update,vehicles_spawned,layer_toggle,ev_station_update,substation_update,map_view_change).static/script.js: ExposedtoggleLayer,updateEVPercentage,updateBatteryRangeonwindowfor socket event handlers.Architecture Impact
/api/configadded for Mapbox token; legacy endpoints remain for backward compatibilityPerformance Considerations
setInterval/setTimeoutpolling loops on frontend; added broadcast frame-skipping on backend🔄 Migration Notes
MAPBOX_TOKENenvironment variable (Mapbox access token is no longer hardcoded)OPENAI_API_KEYandOPENAI_BASE_URLfor agentic chatbot (falls back to other AI systems if not set)📋 Dependencies
No new Python dependencies required.
Utilizes existing infrastructure:
openai— Already in requirementsflask-socketio— Already in userequests— Already in use🔗 Related Issues/PRs
📚 Documentation
🚀 Deployment Notes
MAPBOX_TOKEN(required),OPENAI_API_KEY+OPENAI_BASE_URL(optional)Post-deployment:
🧑💻 Reviewer Notes
Please pay special attention to:
Testing Recommendations:
📝 Additional Notes
Bug Fixes Included
_run_ev_rush_testcrashes{count: 30}instead of individual items)ev_percentage,battery_min_soc,battery_max_socValueErrorin power_system.py.intersection()before comparisonself.current_timeinstead of formatted stringself._format_time(self.current_time_seconds)New Chatbot Tools (26 total)
fail_substation,restore_substation,restore_all_substationsenable_v2g,disable_v2g,get_v2g_statusstart_simulation,stop_simulation,spawn_vehicles,set_simulation_speedset_time,set_temperature,run_scenarioconfigure_evget_system_status,get_scenario_status,get_substation_details,get_load_forecastfocus_map,toggle_map_layer,set_map_viewfail_ev_station,restore_ev_stationtrigger_blackout,run_ev_rush_test,run_v2g_test