An AI-driven agent that generates KQL (Kusto Query Language) queries dynamically to analyze Azure Application Insights telemetry data using natural language requests.
- Natural Language to KQL: Ask questions in plain English and get KQL queries automatically generated
- LLM-Powered Analysis: Uses Azure OpenAI to understand context and generate appropriate queries
- Safety Validation: All queries are validated for safety before execution
- Query Explanation: Get plain English explanations of complex KQL queries
- Query Optimization: Receive suggestions for improving query performance
- Multiple Authentication: Supports both default Azure credentials and service principal authentication
- Application Insights Logging: Optionally sends the application's own logs to Application Insights for monitoring
- Python 3.8+
- Azure Application Insights workspace
- Azure OpenAI resource
- Appropriate Azure permissions to query Application Insights
- Clone the repository:
git clone <repository-url>
cd langgraph-app-insights- Install dependencies:
pip install -r requirements.txt- Set up environment variables (see Configuration section below)
Copy .env.example to .env and configure the required variables:
cp .env.example .env# Azure Application Insights application ID (required)
AZURE_APPINSIGHTS_APPLICATION_ID=your-application-id-hereOption 1: Azure OpenAI (recommended)
AZURE_OPENAI_ENDPOINT=https://your-resource.openai.azure.com/
AZURE_OPENAI_API_KEY=your-azure-openai-api-key-here
AZURE_OPENAI_DEPLOYMENT=gpt-4.1
AZURE_OPENAI_API_VERSION=2024-12-01-previewIf you need service principal authentication instead of default credentials:
AZURE_CLIENT_ID=your-client-id-here
AZURE_CLIENT_SECRET=your-client-secret-here
AZURE_TENANT_ID=your-tenant-id-hereTo send the application's own logs to Application Insights for monitoring:
AZURE_APPINSIGHTS_CONNECTION_STRING=InstrumentationKey=your-key;IngestionEndpoint=https://your-region.in.applicationinsights.azure.com/;LiveEndpoint=https://your-region.livediagnostics.monitor.azure.com/
ENABLE_APPINSIGHTS_LOGGING=true-
Azure Application Insights Application ID:
- Go to Azure Portal → Application Insights → your resource
- Copy the "Application ID" from the Overview page
-
Azure OpenAI Endpoint & Key:
- Go to Azure Portal → Azure OpenAI → your resource
- Copy the "Endpoint" and "Key" from Keys and Endpoint section
-
Azure OpenAI Deployment:
- In Azure AI Foundry (https://ai.azure.com), go to your project
- Navigate to Deployments in the left sidebar
- Copy the deployment name (e.g., "gpt-4o-mini")
-
Application Insights Connection String (for logging):
- Go to Azure Portal → Application Insights → your resource
- Copy the "Connection String" from the Overview page
This project has been refactored for better maintainability with classes separated into individual modules:
langgraph-app-insights/
├── LICENSE.md
├── README.md
├── requirements.txt
├── main.py # Main application entry point
└── src/
├── __init__.py # Package initialization
├── config.py # Configuration management
├── kql_knowledge.py # KQL knowledge base
├── kql_validator.py # KQL query validation
├── app_insights_service.py # Azure Application Insights service
├── appinsights_logging.py # Application Insights logging setup
├── langgraph_tools.py # LangGraph tools for KQL operations
├── agent_state.py # LangGraph agent state definition
└── react_agent.py # LangGraph ReAct agent
config.py: Manages environment variables and LLM configurationkql_knowledge.py: Contains KQL reference documentation and exampleskql_validator.py: Validates KQL queries for safety and correctnessapp_insights_service.py: Handles Azure Application Insights authentication and query executionlanggraph_tools.py: Contains all LangGraph tool functions for KQL operationsappinsights_logging.py: Manages Application Insights logging for the application itselfreact_agent.py: Main ReAct agent that orchestrates query generation and executionmain.py: Provides the user interface and main application entry point
You have multiple options to run the application:
# Run the application
python main.pyThe agent understands natural language requests like:
- Error Analysis: "Show me all exceptions from the last 6 hours"
- Performance Issues: "Find slow requests in the checkout operation"
- Trend Analysis: "What are the error trends this week?"
- User Impact: "How many users were affected by errors today?"
- Dependencies: "Which external services are failing?"
examples- Show example questionshelp- Show detailed helpquitorexit- Exit the application
You can also:
- Execute custom KQL queries directly
- Ask for query explanations: "Explain this query: exceptions | summarize count() by type"
- Request query improvements: "Improve this KQL: traces | where message contains 'error'"
The application uses a modular architecture with the following components:
- LangGraph: For building the reactive agent workflow
- LangChain: For LLM integration and tool management
- Azure Monitor Query: For executing KQL queries against Application Insights
- Azure Identity: For Azure authentication
- Separation of Concerns: Each class has a single responsibility
- Improved Maintainability: Easier to modify and extend individual components
- Better Testing: Each module can be tested independently
- Code Reusability: Classes can be imported and used in other projects
- Cleaner Dependencies: Clear import relationships between modules
- Modularity: Easy to add new features without affecting existing code
- Professional Structure: Follows Python best practices for project organization
AppInsightsService: Manages Azure authentication and query executionKQLValidator: Ensures query safety before executionConfig: Centralizes environment variable management
AppInsightsReActAgent: Main ReAct agent coordinating the workflowAgentState: TypedDict defining the agent's state structure- LangGraph Tools: Four specialized tools for different KQL operations
main.py: Interactive console interface with help, examples, and user interaction
For advanced usage or integration, you can import individual components:
from src.config import Config
from src.app_insights_service import get_app_insights_service
from src.react_agent import AppInsightsReActAgent- Only read-only queries are allowed
- All KQL is validated before execution
- No dangerous operations (drop, delete, etc.) are permitted
- Query results are limited to prevent overwhelming output
- Ensure you're logged into Azure CLI:
az login - Verify your Azure credentials have access to the Application Insights workspace
- Check that your service principal (if used) has the correct permissions
If you see import errors, install missing packages:
pip install -r requirements.txtIf Application Insights logging fails to initialize:
- Verify your
AZURE_APPINSIGHTS_CONNECTION_STRINGis correct - Ensure the Application Insights resource exists and is accessible
- Check that OpenTelemetry packages are installed:
pip install azure-monitor-opentelemetry
The application will show specific error messages about missing environment variables. Make sure all required variables are set in your .env file.
The codebase is organized into focused modules for maintainability:
| Module | Purpose | Key Classes/Functions |
|---|---|---|
config.py |
Environment configuration | Config.validate(), Config.get_llm_config() |
app_insights_service.py |
Azure service integration | AppInsightsService.execute_kql_query() |
kql_validator.py |
Query safety validation | KQLValidator.validate_query() |
langgraph_tools.py |
LangGraph tool definitions | generate_and_execute_kql, explain_kql_query |
react_agent.py |
Main agent orchestration | AppInsightsReActAgent.run() |
main.py |
User interface and entry point | App.run(), main() |
- New KQL Tools: Add to
langgraph_tools.pyand register inreact_agent.py - Configuration Options: Extend the
Configclass inconfig.py - Query Validation: Modify
KQLValidatorfor new safety rules - UI Enhancements: Update
main.pyfor new commands or displays
This project is licensed under the MIT License — see the LICENSE file for details.
It is provided as-is without warranty of any kind.