Skip to content

An intelligent task management assistant built with .NET, Microsoft Agentic AI Framework and Azure OpenAI, demonstrating Clean Architecture and autonomous AI agent capabilities

License

Notifications You must be signed in to change notification settings

cristofima/TaskAgent-AgenticAI

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

33 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Task Agent - AI-Powered Task Management

An intelligent task management assistant built with Microsoft Agent Framework, Azure OpenAI, and .NET Aspire, demonstrating Clean Architecture, autonomous AI agents, and production-grade observability with Azure Content Safety protection.

Task Agent Chat Interface


πŸš€ Quick Start

# Navigate to the project
cd src

# Restore dependencies
dotnet restore

# Configure your Azure credentials in appsettings.Development.json
# Run with .NET Aspire (includes Aspire Dashboard)
dotnet run --project src/TaskAgent.AppHost

# Or run standalone
dotnet run --project src/services/TaskAgent/src/TaskAgent.WebApp

Development: Visit http://localhost:5000 for the app and https://localhost:17198 for Aspire Dashboard
Production: Observability data flows to Azure Application Insights automatically


✨ Features

  • πŸ’¬ Natural Language Interface: Talk to your task manager like a person
  • πŸ›‘οΈ Multi-Layer Security: Azure Content Safety protection (Prompt Shield + Content Moderation)
  • πŸ“Š Production-Grade Observability: Full OpenTelemetry stack with .NET Aspire
  • βœ… Complete CRUD: Create, read, update, and delete tasks
  • οΏ½ Smart Analytics: Task summaries with filtering by status and priority
  • 🎨 Beautiful Tables: Markdown-formatted responses with emojis
  • πŸ’‘ Contextual Suggestions: Agent provides helpful next actions
  • πŸ—„οΈ SQL Server Persistence: Entity Framework Core with LocalDB
  • πŸ” Distributed Tracing: End-to-end request tracking with custom activity sources
  • πŸ“‰ Custom Metrics: Real-time monitoring of AI agent operations

πŸ“Š Observability & Monitoring

This project implements production-grade observability using .NET Aspire and OpenTelemetry with a hybrid architecture:

Development Environment (Local)

.NET Aspire Dashboard

Stack: OpenTelemetry β†’ OTLP Exporter β†’ Aspire Dashboard (https://localhost:17198)

Features:

  • πŸ“Š Real-time metrics visualization
  • πŸ” Distributed tracing with automatic trace correlation
  • πŸ“ Structured logging with log levels and scopes
  • πŸ”— Dependency mapping (Azure OpenAI, Content Safety, SQL Server)
  • 🎯 Custom instrumentation for AI agent operations

Production Environment (Azure)

Stack: OpenTelemetry β†’ Azure Monitor Exporter β†’ Application Insights

Features:

  • πŸ“ˆ Performance monitoring and alerting
  • πŸ—ΊοΈ Application Map with dependencies
  • πŸ”₯ Live metrics and real-time telemetry
  • πŸ“Š Custom dashboards and workbooks
  • πŸ”” Smart detection and anomaly alerts

Three Pillars of Observability

1️⃣ Metrics (Custom + Built-in)

Custom AI Agent Metrics:

Meter: "TaskAgent.Agent"

Counters:
- agent.requests         β†’ Total requests to the agent
- agent.function_calls   β†’ Function tool invocations
- agent.errors          β†’ Error count by type

Histograms:
- agent.response.duration β†’ Response time in milliseconds

Built-in Metrics (automatic):

  • ASP.NET Core instrumentation (HTTP requests, response times)
  • HTTP Client instrumentation (Azure OpenAI, Content Safety calls)
  • Runtime instrumentation (GC, thread pool, exceptions)

2️⃣ Distributed Tracing

Custom Activity Sources:

ActivitySource: "TaskAgent.Agent"

Spans:
- Agent.ProcessMessage    β†’ End-to-end message processing
- Function.{FunctionName} β†’ Individual function tool calls

Tags:
- thread.id              β†’ Conversation thread identifier
- function.name          β†’ Called function name
- message.length         β†’ User message size
- response.length        β†’ Agent response size

Built-in Traces (automatic):

  • ASP.NET Core HTTP requests
  • Entity Framework Core SQL queries (development only)
  • HTTP client calls to Azure services

3️⃣ Structured Logging

Configuration:

  • Formatted messages included
  • Log scopes enabled
  • Integration with OpenTelemetry
  • Automatic correlation with traces

Log Levels:

  • Information: Agent operations, function calls
  • Warning: Content safety blocks, validation failures
  • Error: Exceptions, service failures

Hybrid Telemetry Architecture

Smart Environment Detection:

// Automatically selects exporter based on configuration
if (OTEL_EXPORTER_OTLP_ENDPOINT exists)
    β†’ Use OTLP β†’ Aspire Dashboard

if (APPLICATIONINSIGHTS_CONNECTION_STRING exists)
    β†’ Use Azure Monitor β†’ Application Insights

Security: SQL statement capture is disabled in production to prevent sensitive data leakage.

Service Discovery: HTTPS-only in production, HTTP + HTTPS in development.


πŸ›‘οΈ Content Safety

This application implements 2-layer defense using Azure AI Content Safety with parallel execution:

Layer 1: Prompt Shield

  • Detects prompt injection attacks (jailbreaks, instruction override, role manipulation)
  • REST API: /contentsafety/text:shieldPrompt (API version 2024-09-01)
  • Blocks malicious attempts to manipulate the AI system
  • Optimized: Trusts Azure's pre-trained model without system context (reduces false positives)

Layer 2: Content Moderation

  • Analyzes text for harmful content (Hate, Violence, Sexual, Self-Harm)
  • SDK: Azure AI Content Safety
  • Configurable severity thresholds (0-6 scale)

Architecture: Content safety checks run automatically via middleware before any AI processing.

Performance:

  • Parallel Execution: Both layers validate simultaneously using Task.WhenAll (~50% faster)
  • IHttpClientFactory: Named HttpClient for optimal connection pooling and DNS refresh
  • Response Time: ~200-400ms for safe prompts (vs ~400-800ms sequential)

Best Practices:

  • Generic conversational refusals (like ChatGPT) - no technical details exposed
  • Security violations render as normal bot messages
  • No error styling for content safety blocks

Testing: See docs/CONTENT_SAFETY.md for 75+ test cases, known limitations, and troubleshooting guide.


πŸ—οΈ Architecture

Built with Clean Architecture for maintainability and testability:

TaskAgent.Domain (Entities, Business Logic)
    ↓
TaskAgent.Application (Use Cases, Interfaces)
    ↓
TaskAgent.Infrastructure (Data Access, Azure Services)
    ↓
TaskAgent.WebApp (UI, Controllers, AI Agent)

Key Components:

  • Domain: TaskItem entity with business rules, Status/Priority enums
  • Application: DTOs (using record types), ITaskRepository, IThreadPersistenceService, 6 AI function tools
  • Infrastructure: TaskDbContext, TaskRepository, ContentSafetyService with HttpClientFactory, InMemoryThreadPersistenceService
  • Presentation: MVC controllers, Razor views, TaskAgentService, configuration validation extensions

Conversation Persistence:

  • Thread state serialized/deserialized across requests using AgentThread.Serialize()
  • IThreadPersistenceService abstraction for storage flexibility
  • In-memory implementation for single-server deployments
  • Production: Use Redis/SQL for multi-server scenarios

πŸ› οΈ Tech Stack

Technology Purpose
.NET 9.0 Modern web framework
ASP.NET Core MVC Web application
.NET Aspire Cloud-native orchestration
OpenTelemetry Observability framework
Entity Framework Core Database ORM
SQL Server LocalDB Data persistence
Microsoft Agent Framework Autonomous AI agents
Azure OpenAI (GPT-4o-mini) Language model
Azure AI Content Safety Security & moderation
Bootstrap 5 Responsive UI
Marked.js Markdown rendering

βš™οΈ Setup

Prerequisites

  • .NET 9.0 SDK
  • SQL Server LocalDB (included with Visual Studio)
  • Azure OpenAI resource with deployed model (GPT-4o-mini recommended)
  • Azure AI Content Safety resource
  • Azure Application Insights resource (for production)

Configuration

Development Environment

1. Update appsettings.Development.json:

{
  "AzureOpenAI": {
    "Endpoint": "https://your-openai-resource.openai.azure.com/",
    "ApiKey": "your-openai-api-key",
    "ModelDeployment": "gpt-4o-mini"
  },
  "ContentSafety": {
    "Endpoint": "https://your-contentsafety-resource.cognitiveservices.azure.com/",
    "ApiKey": "your-contentsafety-api-key",
    "HateThreshold": 2,
    "ViolenceThreshold": 2,
    "SexualThreshold": 2,
    "SelfHarmThreshold": 2
  }
}

2. Database (auto-created on first run, or manually):

cd src/services/TaskAgent/src
dotnet ef database update --project TaskAgent.Infrastructure --startup-project TaskAgent.WebApp

3. Run with Aspire (recommended):

dotnet run --project src/TaskAgent.AppHost

Production Environment (Azure)

1. Update appsettings.Production.json:

{
  "AzureOpenAI": {
    "Endpoint": "https://your-openai-resource.openai.azure.com/",
    "ApiKey": "your-openai-api-key",
    "ModelDeployment": "gpt-4o-mini"
  },
  "ContentSafety": {
    "Endpoint": "https://your-contentsafety-resource.cognitiveservices.azure.com/",
    "ApiKey": "your-contentsafety-api-key",
    "HateThreshold": 2,
    "ViolenceThreshold": 2,
    "SexualThreshold": 2,
    "SelfHarmThreshold": 2
  },
  "APPLICATIONINSIGHTS_CONNECTION_STRING": "InstrumentationKey=your-key;IngestionEndpoint=https://...",
  "ConnectionStrings": {
    "DefaultConnection": "Server=tcp:your-server.database.windows.net,1433;Initial Catalog=TaskAgentDb;..."
  }
}

2. Deploy to Azure App Service using standard deployment methods.


πŸ€– AI Agent Capabilities

The Task Agent provides 6 function tools:

Function Description
CreateTask Create new tasks with title, description, priority
ListTasks Show all tasks with optional filters
GetTaskDetails Get detailed info about a specific task
UpdateTask Modify task status or priority
DeleteTask Remove tasks
GetTaskSummary View statistics and analytics

Example Interactions:

You: Create a high priority task to review the quarterly report
Agent: βœ… Task created! ID: 1, Priority: High

You: Show me all my tasks
Agent: [Displays beautiful Markdown table with all tasks]
      πŸ’‘ Suggestions: β€’ Filter by priority β€’ Update oldest task

You: Mark task 1 as Completed
Agent: βœ… Task updated! Status changed to Completed

🎨 Agent Features

Markdown Tables

Lists 2+ tasks in beautiful formatted tables with emojis:

  • Status: ⏳ Pending, πŸ”„ InProgress, βœ… Completed
  • Priority: 🟒 Low, 🟑 Medium, πŸ”΄ High

Contextual Suggestions

Agent provides 1-2 smart suggestions after each operation:

  • After creating: "View all tasks" or "Create follow-up"
  • After listing: "Filter by priority" or "Update oldest task"
  • After completing: "View remaining tasks" or "Get summary"

Smart Insights

  • Detects many pending tasks β†’ suggests prioritizing
  • Celebrates milestones β†’ "πŸŽ‰ Great! You've completed 5 tasks!"
  • Encourages progress

πŸ“‚ Project Structure

TaskAgentWeb/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ TaskAgent.AppHost/                         # .NET Aspire orchestration
β”‚   β”‚   β”œβ”€β”€ AppHost.cs                            # Aspire app host configuration
β”‚   β”‚   └── appsettings.json                      # Aspire settings
β”‚   β”‚
β”‚   β”œβ”€β”€ TaskAgent.ServiceDefaults/                 # Shared observability configuration
β”‚   β”‚   └── ServiceDefaultsExtensions.cs          # OpenTelemetry setup
β”‚   β”‚
β”‚   └── services/TaskAgent/src/
β”‚       β”œβ”€β”€ TaskAgent.Domain/                      # Core business logic (NO dependencies)
β”‚       β”‚   β”œβ”€β”€ Entities/                         # TaskItem with business rules
β”‚       β”‚   β”œβ”€β”€ Enums/                            # TaskStatus, TaskPriority
β”‚       β”‚   └── Constants/                        # Domain constants
β”‚       β”‚
β”‚       β”œβ”€β”€ TaskAgent.Application/                 # Use cases & interfaces
β”‚       β”‚   β”œβ”€β”€ DTOs/                             # Record types for immutability
β”‚       β”‚   β”œβ”€β”€ Functions/                        # 6 AI function tools
β”‚       β”‚   β”œβ”€β”€ Interfaces/                       # ITaskRepository, IContentSafetyService
β”‚       β”‚   └── Telemetry/                        # Custom metrics & activity sources
β”‚       β”‚       β”œβ”€β”€ AgentMetrics.cs               # Custom Meter
β”‚       β”‚       └── AgentActivitySource.cs        # Custom ActivitySource
β”‚       β”‚
β”‚       β”œβ”€β”€ TaskAgent.Infrastructure/              # External concerns
β”‚       β”‚   β”œβ”€β”€ Data/                             # TaskDbContext, EF configurations
β”‚       β”‚   β”œβ”€β”€ Repositories/                     # Repository implementations
β”‚       β”‚   β”œβ”€β”€ Services/                         # ContentSafetyService, ThreadPersistence
β”‚       β”‚   └── InfrastructureServiceExtensions.cs # HttpClientFactory, DI
β”‚       β”‚
β”‚       └── TaskAgent.WebApp/                      # Presentation layer
β”‚           β”œβ”€β”€ Controllers/                       # ChatController, HomeController
β”‚           β”œβ”€β”€ Services/                         # TaskAgentService (AI orchestration)
β”‚           β”œβ”€β”€ Middleware/                       # ContentSafetyMiddleware
β”‚           β”œβ”€β”€ Extensions/                       # Configuration validation
β”‚           β”œβ”€β”€ Views/                            # Razor UI
β”‚           β”œβ”€β”€ wwwroot/                          # Static assets
β”‚           └── PresentationServiceExtensions.cs   # AI Agent registration
β”‚
β”œβ”€β”€ docs/                                          # Documentation
β”‚   β”œβ”€β”€ screenshots/                              # Application screenshots
β”‚   β”œβ”€β”€ architecture/                             # Architecture diagrams (planned)
β”‚   └── CONTENT_SAFETY.md                         # Content Safety testing guide
β”‚
└── scripts/                                       # PowerShell scripts
    β”œβ”€β”€ Analyze-Commits.ps1                       # Commit analysis tool
    └── config.json                               # Script configuration
β”‚   β”œβ”€β”€ terraform.tfvars.example                  # Example configuration
β”‚   β”œβ”€β”€ .gitignore                                # Exclude state files
β”‚   └── README.md                                 # Terraform documentation
β”‚
β”œβ”€β”€ docs/                                          # Documentation
β”‚   β”œβ”€β”€ screenshots/                              # Application & observability screenshots
β”‚   β”œβ”€β”€ deployment/                               # Deployment guides
β”‚   β”œβ”€β”€ architecture/                             # Architecture diagrams
β”‚   └── CONTENT_SAFETY.md                         # Security testing guide
β”‚
└── README.md                                      # This file

Key Architectural Decisions

Clean Architecture: Domain β†’ Application β†’ Infrastructure β†’ WebApp (strict dependency flow)

Observability-First: OpenTelemetry instrumentation at every layer via ServiceDefaults

Hybrid Telemetry:

  • Development: OTLP β†’ Aspire Dashboard
  • Production: Azure Monitor β†’ Application Insights

Security: Content Safety middleware + HTTPS-only service discovery in production


πŸ”’ Security

Content Safety

  • 2-Layer Defense: Automatic Prompt Shield + Content Moderation
  • Fail-Secure: Blocks requests on Prompt Shield errors; Fail-Open on Content Moderation for availability
  • Optimized Detection: Prompt Shield uses pre-trained model (no system context) to reduce false positives
  • Performance: HttpClientFactory with Named HttpClient for connection pooling and DNS refresh
  • Immutable DTOs: Record types for thread-safety and proper equality semantics
  • Best Practices: ChatGPT-style generic refusals without exposing attack details
  • See: docs/CONTENT_SAFETY.md for 75+ test cases and troubleshooting

Application Security

  • Input Validation: EF Core parameterized queries prevent SQL injection
  • XSS Protection: DOMPurify sanitization on client-side
  • Configuration Validation: Startup checks for missing credentials
  • HTTPS Enforcement: Service discovery restricted to HTTPS in production
  • Secret Management: Never commit API keys - use Azure Key Vault in production
  • SQL Security: Database statement capture disabled in production

πŸ“Έ Screenshots

.NET Aspire Dashboard (Development)

Aspire Overview Real-time observability with traces, metrics, and logs

Distributed Tracing End-to-end request tracing with custom activity sources

Custom Metrics AI agent performance metrics (requests, function calls, response time)

Azure Application Insights (Production)

Performance Metrics Response time and dependency tracking

Distributed Tracing Production distributed tracing


οΏ½ Related Articles

Comprehensive guides covering concepts, best practices, and step-by-step tutorials:

  1. Building an AI Task Management Agent using Microsoft Agentic AI Framework

    • Understanding the Microsoft Agent Framework
    • Implementing autonomous AI agents with function calling
    • Clean Architecture implementation for AI applications
    • Creating Azure OpenAI resources and configuration
  2. Securing your AI Task Agent with Azure AI Content Safety

    • Two-layer defense architecture (Prompt Shield + Content Moderation)
    • Setting up Azure AI Content Safety resources
    • Implementing parallel security checks for optimal performance
    • Best practices for AI security without exposing vulnerabilities
  3. Real-Time Observability for AI Agents with .NET Aspire, Application Insights & OpenTelemetry

    • Production-grade observability with OpenTelemetry
    • Custom metrics and distributed tracing for AI agents
    • Hybrid telemetry architecture (local + cloud)
    • Creating Application Insights resources and configuration

οΏ½πŸ“š Documentation


πŸ“– License

This project is licensed under the MIT License - see the LICENSE file for details.

What this means:

  • βœ… Free to use for personal and commercial projects
  • βœ… Free to modify and distribute
  • βœ… Free to use in your own educational content
  • ℹ️ Just keep the copyright notice

Built with ❀️ using .NET 9, Microsoft Agent Framework, .NET Aspire, and Clean Architecture