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.
# 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.WebAppDevelopment: Visit http://localhost:5000 for the app and https://localhost:17198 for Aspire Dashboard
Production: Observability data flows to Azure Application Insights automatically
- π¬ 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
This project implements production-grade observability using .NET Aspire and OpenTelemetry with a hybrid architecture:
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
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
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 millisecondsBuilt-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)
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 sizeBuilt-in Traces (automatic):
- ASP.NET Core HTTP requests
- Entity Framework Core SQL queries (development only)
- HTTP client calls to Azure services
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
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 InsightsSecurity: SQL statement capture is disabled in production to prevent sensitive data leakage.
Service Discovery: HTTPS-only in production, HTTP + HTTPS in development.
This application implements 2-layer defense using Azure AI Content Safety with parallel execution:
- 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)
- 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.
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:
TaskItementity with business rules, Status/Priority enums - Application: DTOs (using record types),
ITaskRepository,IThreadPersistenceService, 6 AI function tools - Infrastructure:
TaskDbContext,TaskRepository,ContentSafetyServicewith HttpClientFactory,InMemoryThreadPersistenceService - Presentation: MVC controllers, Razor views,
TaskAgentService, configuration validation extensions
Conversation Persistence:
- Thread state serialized/deserialized across requests using
AgentThread.Serialize() IThreadPersistenceServiceabstraction for storage flexibility- In-memory implementation for single-server deployments
- Production: Use Redis/SQL for multi-server scenarios
| 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 |
- .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)
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.WebApp3. Run with Aspire (recommended):
dotnet run --project src/TaskAgent.AppHost- Application: https://localhost:5001
- Aspire Dashboard: https://localhost:17198
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.
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
Lists 2+ tasks in beautiful formatted tables with emojis:
- Status: β³ Pending, π InProgress, β Completed
- Priority: π’ Low, π‘ Medium, π΄ High
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"
- Detects many pending tasks β suggests prioritizing
- Celebrates milestones β "π Great! You've completed 5 tasks!"
- Encourages progress
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
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
- 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
- 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
Real-time observability with traces, metrics, and logs
End-to-end request tracing with custom activity sources
AI agent performance metrics (requests, function calls, response time)
Response time and dependency tracking
Production distributed tracing
Comprehensive guides covering concepts, best practices, and step-by-step tutorials:
-
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
-
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
-
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
- Content Safety Guide - Security testing with 75+ test cases
- Documentation Index - Full documentation structure
This project is licensed under the MIT License - see the LICENSE file for details.
- β 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
