AI Insights Generation (ReAct Loop)
Relevant source files
The following files were used as context for generating this wiki page:The AI Insights Generation feature, also known as the "Ultimate AI Battery Guru," is an advanced agentic system within BMSview. It utilizes Google's Gemini AI in a ReAct (Reasoning and Acting) loop, allowing the AI to dynamically call tools and request data during analysis. This approach moves beyond static prompts, enabling the AI to perform complex, multi-step reasoning to provide deep, context-rich insights into battery performance.
This system is designed to be a self-improving development partner, capable of analyzing 100% of available data, using statistical models, and even suggesting application improvements through a structured feedback mechanism. For more information on related features, see the Solar Integration Guide.
Sources: README.md, REACT_LOOP_README.md, SPRINT_COMPLETE_SUMMARY.md
Architecture
The system is built around a set of Netlify serverless functions that manage the interaction between the user, the Gemini AI, and the application's data sources. It operates in two primary modes—Synchronous and Asynchronous (Background)—to balance responsiveness with the ability to perform deep analysis.
Sources: INSIGHTS_DEPLOYMENT_GUIDE.md, PR_SUMMARY.md
Execution Flow
The primary endpoint, /generate-insights-with-tools, first attempts a synchronous analysis. If the request is too complex and exceeds the 55-second timeout, it automatically transitions to a background job, returning a jobId to the client for status polling.
This diagram illustrates the dual-mode execution flow.
Sources: INSIGHTS_DEPLOYMENT_GUIDE.md, PR_SUMMARY.md
Core Components
The ReAct loop is implemented across several key backend modules.
| Component | File Path | Description |
|---|---|---|
| ReAct Loop | netlify/functions/utils/react-loop.cjs | The main orchestration engine. It manages the conversation history, detects and triggers tool calls, enforces turn limits, and handles timeouts. |
| Tool Executor | netlify/functions/utils/tool-executor.cjs | Executes the specific tool functions requested by Gemini, such as querying the MongoDB database. |
| Gemini Client | netlify/functions/utils/geminiClient.cjs | An enhanced client that supports conversation history and passing tool definitions in requests to the Gemini API. |
| Insights Guru | netlify/functions/utils/insights-guru.cjs | Builds the initial prompt and context for Gemini, including historical data rollups and instructions on tool usage. |
| Response Validator | netlify/functions/utils/response-validator.cjs | A module that validates the format of Gemini's final response (e.g., CSV, JSON) and triggers an auto-correction loop if needed. |
Sources: REACT_LOOP_README.md, COMPLETION_SUMMARY.md, INSIGHTS_TOOL_EXECUTION_ENHANCEMENT.md
The ReAct Loop Process
The ReAct loop is an iterative process where the AI reasons about a problem, decides to act by calling a tool, and then observes the tool's output to inform its next step. This cycle repeats until the AI has gathered enough information to provide a final answer.
Initialization Sequence
To combat "insufficient data" errors, a mandatory initialization sequence was implemented. Before the main analysis begins, Gemini is prompted to call the request_bms_data tool to retrieve a historical dataset. The size of this dataset can be controlled by the user via a slider in the UI.
This diagram shows the mandatory data-fetch step before the main analysis loop.
Main Loop
After initialization, the main loop begins. It has a configurable turn limit to prevent infinite loops.
This sequence diagram details the turn-based interaction between the system and the Gemini API.
- Standard Insights: 10 iterations (
MAX_TURNS) - Custom Queries: 20 iterations (
MAX_TURNS)
Sources: REACT_LOOP_README.md, INITIALIZATION_SEQUENCE_IMPLEMENTATION.md, INSIGHTS_DEPLOYMENT_GUIDE.md
Available Tools
Gemini has access to a suite of tools to gather data. Strict prompting ensures Gemini executes these tools itself rather than recommending their use to the end-user.
| Tool Name | Status | Description |
|---|---|---|
request_bms_data | ✅ Implemented | Requests specific BMS metrics with time ranges and aggregations from MongoDB. |
getSystemHistory | ✅ Implemented | Gets historical battery measurements. |
submitAppFeedback | ✅ Implemented | Submits structured feedback about the application for continuous improvement. |
searchGitHubIssues | ✅ Implemented | Searches the project's GitHub issues to prevent duplicates. |
getCodebaseFile | ✅ Implemented | Fetches the content of a file from the repository to verify implementations. |
listDirectory | ✅ Implemented | Discovers files in approved directories. |
getWeatherData | 🔄 Stub | Returns placeholder weather data. |
getSolarEstimate | 🔄 Stub | Returns placeholder solar generation forecasts. |
getSystemAnalytics | 🔄 Stub | Returns placeholder performance analytics. |
predict_battery_trends | 🔄 Stub | Returns placeholder predictive modeling results. |
analyze_usage_patterns | 🔄 Stub | Returns placeholder pattern recognition results. |
calculate_energy_budget | 🔄 Stub | Returns placeholder energy budgeting results. |
Sources: INSIGHTS_DEPLOYMENT_GUIDE.md, INSIGHTS_TOOL_EXECUTION_ENHANCEMENT.md:240-244, SPRINT_COMPLETE_SUMMARY.md, GITHUB_INTEGRATION_COMPLETE.md
Error Handling and Recovery
The system includes robust mechanisms to handle common failure modes and guide the AI toward a successful outcome.
Keyword-Based Error Recovery
If Gemini fails to call a tool or claims data is unavailable, the system analyzes its response for keywords (e.g., "insufficient data," "invalid date"). Based on the detected issue, it provides a targeted follow-up prompt with corrective guidance, working examples, and a data catalog to help the AI recover.
Sources: INITIALIZATION_SEQUENCE_IMPLEMENTATION.md
Automatic Format Validation
When a user requests a specific output format (like CSV, JSON, or a Markdown table), the response-validator.cjs module automatically validates Gemini's final answer. If the format is invalid, it triggers another turn in the ReAct loop, sending a correction prompt to Gemini with specific instructions on how to fix the malformed output. This process is invisible to the user.
This flowchart shows the automatic format validation and correction loop.
API Endpoints
The ReAct loop functionality is exposed through a set of Netlify Function endpoints.
| Endpoint | Method | Purpose |
|---|---|---|
/generate-insights-with-tools | POST | The main endpoint for the full ReAct loop. Supports sync and background modes. |
/generate-insights-status | GET, POST | Polls for the status and result of a background job using a jobId. |
/generate-insights-background | POST | Internal endpoint for processing long-running background jobs. |
/generate-insights | POST | A legacy proxy endpoint that maintains backward compatibility by forwarding requests to /generate-insights-with-tools. |
Sources: INSIGHTS_DEPLOYMENT_GUIDE.md, PR_SUMMARY.md