Skip to content

savramidis/langgraph-app-insights

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

LangGraph Application Insights Agent

An AI-driven agent that generates KQL (Kusto Query Language) queries dynamically to analyze Azure Application Insights telemetry data using natural language requests.

Features

  • 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

Prerequisites

  • Python 3.8+
  • Azure Application Insights workspace
  • Azure OpenAI resource
  • Appropriate Azure permissions to query Application Insights

Installation

  1. Clone the repository:
git clone <repository-url>
cd langgraph-app-insights
  1. Install dependencies:
pip install -r requirements.txt
  1. Set up environment variables (see Configuration section below)

Configuration

Environment Variables

Copy .env.example to .env and configure the required variables:

cp .env.example .env

Required Variables

# Azure Application Insights application ID (required)
AZURE_APPINSIGHTS_APPLICATION_ID=your-application-id-here

LLM Configuration (choose one)

Option 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-preview

Optional: Azure Authentication

If 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-here

Optional: Application Insights Logging

To 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

Finding Your Configuration Values

  1. Azure Application Insights Application ID:

    • Go to Azure Portal → Application Insights → your resource
    • Copy the "Application ID" from the Overview page
  2. Azure OpenAI Endpoint & Key:

    • Go to Azure Portal → Azure OpenAI → your resource
    • Copy the "Endpoint" and "Key" from Keys and Endpoint section
  3. 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")
  4. Application Insights Connection String (for logging):

    • Go to Azure Portal → Application Insights → your resource
    • Copy the "Connection String" from the Overview page

Project Structure

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

Key Components

  • config.py: Manages environment variables and LLM configuration
  • kql_knowledge.py: Contains KQL reference documentation and examples
  • kql_validator.py: Validates KQL queries for safety and correctness
  • app_insights_service.py: Handles Azure Application Insights authentication and query execution
  • langgraph_tools.py: Contains all LangGraph tool functions for KQL operations
  • appinsights_logging.py: Manages Application Insights logging for the application itself
  • react_agent.py: Main ReAct agent that orchestrates query generation and execution
  • main.py: Provides the user interface and main application entry point

Usage

Running the Application

You have multiple options to run the application:

# Run the application
python main.py

Example Queries

The 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?"

Commands

  • examples - Show example questions
  • help - Show detailed help
  • quit or exit - Exit the application

KQL Operations

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'"

Architecture

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

Refactored Design Benefits

  1. Separation of Concerns: Each class has a single responsibility
  2. Improved Maintainability: Easier to modify and extend individual components
  3. Better Testing: Each module can be tested independently
  4. Code Reusability: Classes can be imported and used in other projects
  5. Cleaner Dependencies: Clear import relationships between modules
  6. Modularity: Easy to add new features without affecting existing code
  7. Professional Structure: Follows Python best practices for project organization

Component Details

Core Services

  • AppInsightsService: Manages Azure authentication and query execution
  • KQLValidator: Ensures query safety before execution
  • Config: Centralizes environment variable management

Agent Components

  • AppInsightsReActAgent: Main ReAct agent coordinating the workflow
  • AgentState: TypedDict defining the agent's state structure
  • LangGraph Tools: Four specialized tools for different KQL operations

User Interface

  • main.py: Interactive console interface with help, examples, and user interaction

Importing Components

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

Safety Features

  • 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

Troubleshooting

Authentication Issues

  • 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

Missing Dependencies

If you see import errors, install missing packages:

pip install -r requirements.txt

Application Insights Logging Issues

If Application Insights logging fails to initialize:

  • Verify your AZURE_APPINSIGHTS_CONNECTION_STRING is correct
  • Ensure the Application Insights resource exists and is accessible
  • Check that OpenTelemetry packages are installed: pip install azure-monitor-opentelemetry

Configuration Errors

The application will show specific error messages about missing environment variables. Make sure all required variables are set in your .env file.

Development

Module Structure

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()

Adding New Features

  1. New KQL Tools: Add to langgraph_tools.py and register in react_agent.py
  2. Configuration Options: Extend the Config class in config.py
  3. Query Validation: Modify KQLValidator for new safety rules
  4. UI Enhancements: Update main.py for new commands or displays

License

This project is licensed under the MIT License — see the LICENSE file for details.
It is provided as-is without warranty of any kind.

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages