Skip to content

An intelligent task management assistant built with .NET, Next.js, 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

81 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


πŸŽ₯ Demo Video

Task Agent Demo

Watch the full demonstration of the Task Agent in action, showcasing:

  • Natural language task management
  • AI-powered suggestions and insights
  • Content Safety protection
  • Real-time conversation management
  • Modern Next.js frontend with ChatGPT-inspired UI

πŸ“š Article Series

This project is documented in a comprehensive article series on C# Corner:

  1. Building a Task Management AI Agent - Microsoft Agent Framework, Azure OpenAI integration, and Clean Architecture
  2. Securing AI Agents - Azure AI Content Safety with Prompt Shield and parallel validation
  3. Production-Grade Observability - .NET Aspire, OpenTelemetry, and Application Insights
  4. Modern Frontend Architecture - Next.js 16 separation, dual-database strategy, and Azure Static Web Apps

Topics Covered:

  • πŸ€– Autonomous AI agents with function calling
  • πŸ›‘ Multi-layer security (Prompt Shield + Content Moderation)
  • πŸ“ˆ Production observability (Aspire Dashboard + Application Insights)
  • βš›οΈ Modern React with Next.js 16 and TypeScript
  • πŸ—„οΈ Dual-database architecture (SQL Server + PostgreSQL)
  • ☁️ Azure deployment with Static Web Apps

πŸš€ Quick Start

# 1. Configure your Azure credentials in src/backend/services/TaskAgent/src/TaskAgent.WebApi/appsettings.Development.json

# 2. Setup PostgreSQL database (see docs/POSTGRESQL_MIGRATION.md for details)

# 3. Run with .NET Aspire (includes Aspire Dashboard)
dotnet run --project src/TaskAgent.AppHost

# Or run backend standalone
cd src/backend/services/TaskAgent/src
dotnet run --project TaskAgent.WebApi

# 4. Run frontend (separate terminal)
cd src/frontend/task-agent-web
pnpm install
pnpm dev

Access:


✨ Features

Backend 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
  • πŸ—„οΈ PostgreSQL Persistence: Entity Framework Core with JSON storage (preserves property order)
  • πŸ’¬ Conversation Management: Persistent threads with metadata tracking
  • πŸ” Distributed Tracing: End-to-end request tracking with custom activity sources
  • πŸ“‰ Custom Metrics: Real-time monitoring of AI agent operations

Frontend Features:

  • βš›οΈ Modern React: Next.js 16 + React 19 with TypeScript
  • 🎯 Server Components: Optimized bundle size and performance
  • 🎨 ChatGPT-Inspired UI: Full-height adaptive layout with Tailwind CSS 4
  • πŸ“ Smart Layout: Centered welcome state, fixed input when chatting
  • πŸ”„ Independent Scrolling: Fixed header and input, scrollable messages
  • πŸ’‘ Clickable Suggestions: Interactive suggestion buttons from AI
  • ⏳ Contextual Loading: Rotating status messages during processing
  • ⚑ Optimistic Updates: Instant message feedback
  • πŸ“ Markdown Rendering: Rich text formatting in chat
  • 🎭 Type Safety: Full TypeScript with backend contract alignment
  • 🧩 Clean Architecture: Separation of concerns (UI β†’ Hooks β†’ API)
  • πŸ“‚ Conversation Management: List, load, and delete conversations with auto-generated titles
  • πŸ—‚οΈ Sidebar Navigation: Collapsible sidebar with conversation history

πŸ“Š 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, PostgreSQL)
  • 🎯 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)

Security Enhancements

Blocked Message Handling:

  • βœ… Blocked messages appear as assistant responses in chat (not error toasts)
  • βœ… Thread placeholders created for conversation continuity (ChatGPT-like UX)
  • βœ… Blocked content is NEVER persisted in database (security measure)
  • βœ… Automatic sidebar updates when threads are created
  • βœ… Smart title regeneration when first valid message is sent after a block
  • βœ… Optimized sidebar refresh: only reloads when title changes from null (efficient!)

For detailed testing guide: See docs/CONTENT_SAFETY.md (75+ test cases)

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:

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                 Frontend (Next.js)              β”‚
β”‚  β€’ React 19 + TypeScript                        β”‚
β”‚  β€’ Server Components + Client Components        β”‚
β”‚  β€’ Conversation Management UI                   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                     β”‚ REST API
                     β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚              Backend (.NET 10)                  β”‚
β”‚                                                 β”‚
β”‚  Presentation β†’ Infrastructure β†’ Application    β”‚
β”‚                                  β†’ Domain       β”‚
β”‚                                                 β”‚
β”‚  β€’ AI Agent with 6 function tools               β”‚
β”‚  β€’ Content Safety middleware                    β”‚
β”‚  β€’ Dual-database persistence                    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                     β”‚
                     β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚             Databases & Services                β”‚
β”‚  β€’ SQL Server: Task entities                    β”‚
β”‚  β€’ PostgreSQL: Conversation threads (JSON)      β”‚
β”‚  β€’ Azure OpenAI: GPT-4o-mini                    β”‚
β”‚  β€’ Azure AI Content Safety                      β”‚
β”‚  β€’ Application Insights                         β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

For detailed architecture documentation:


πŸ› οΈ Tech Stack

Backend

Technology Purpose
.NET 10 Modern web framework
ASP.NET Core Web API RESTful API
.NET Aspire 13.0.0 Cloud-native orchestration
OpenTelemetry Observability framework
Entity Framework Core 10 Database ORM
SQL Server Task data persistence
PostgreSQL 15+ Conversation persistence
Microsoft Agent Framework Autonomous AI agents
Azure OpenAI (GPT-4o-mini) Language model
Azure AI Content Safety Security & moderation

Frontend

Technology Purpose
Next.js 16 React framework
React 19 UI library
TypeScript 5 Type-safe JavaScript
Tailwind CSS 4 Utility-first CSS
pnpm Fast package manager
react-markdown Markdown rendering
SWR (planned) Data fetching & caching

βš™οΈ Setup

Prerequisites

  • .NET 10 SDK
  • Node.js 20+ (for Next.js frontend)
  • pnpm package manager (npm install -g pnpm)
  • PostgreSQL 15+ (see PostgreSQL Setup Guide)
  • 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 Setup:

# Install PostgreSQL 15+ (see docs/POSTGRESQL_MIGRATION.md for detailed instructions)

# Create database
psql -U postgres
CREATE DATABASE "TaskAgentDb";
\q

# Update connection strings in appsettings.Development.json
{
  "ConnectionStrings": {
    "TasksConnection": "Server=localhost;Database=TaskAgentDb;Trusted_Connection=true;",
    "ConversationsConnection": "Host=localhost;Port=5432;Database=taskagent_conversations;Username=postgres;Password=your_password"
  }
}

# Migrations apply automatically on startup
# Or run manually from src/backend/services/TaskAgent/src:
dotnet ef database update --context TaskDbContext --project TaskAgent.Infrastructure --startup-project TaskAgent.WebApi
dotnet ef database update --context ConversationDbContext --project TaskAgent.Infrastructure --startup-project TaskAgent.WebApi

3. Configure Frontend - Create .env.local:

# src/frontend/task-agent-web/.env.local
NEXT_PUBLIC_API_URL=https://localhost:5001

4. Install Frontend Dependencies:

cd src/frontend/task-agent-web
pnpm install

5. Run with Aspire (recommended - runs both backend and prepares for frontend):

# From repository root
dotnet run --project src/TaskAgent.AppHost

6. Run Frontend (in a separate terminal):

cd src/frontend/task-agent-web
pnpm dev

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": {
    "TasksConnection": "Server=tcp:your-server.database.windows.net,1433;Initial Catalog=TaskAgentDb;User ID=your_user;Password=your_password;Encrypt=True;",
    "ConversationsConnection": "Host=your-postgres-server.postgres.database.azure.com;Port=5432;Database=TaskAgentDb;Username=your_user;Password=your_password;SslMode=Require;"
  }
}

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/                                           # Source code root
β”‚   β”‚
β”‚   β”œβ”€β”€ .editorconfig                              # C# code style rules (shared)
β”‚   β”œβ”€β”€ Directory.Build.props                      # ⭐ MSBuild properties (MUST be at src/ level)
β”‚   β”œβ”€β”€ Directory.Packages.props                   # ⭐ Central Package Management (MUST be at src/ level)
β”‚   β”œβ”€β”€ global.json                                # ⭐ .NET SDK + Aspire SDK versions (MUST be at src/ level)
β”‚   β”‚
β”‚   β”œβ”€β”€ TaskAgent.AppHost/                         # .NET Aspire orchestration (root level)
β”‚   β”‚   β”œβ”€β”€ AppHost.cs                             # Orchestrates backend (+ future frontend)
β”‚   β”‚   β”œβ”€β”€ appsettings.json                       # Aspire settings
β”‚   β”‚   └── Properties/launchSettings.json         # Aspire Dashboard launch config
β”‚   β”‚
β”‚   β”œβ”€β”€ backend/                                   # Backend services (.NET 10 Web API)
β”‚   β”‚   └── ...                                    # See src/backend/services/TaskAgent/README.md
β”‚   β”‚
β”‚   └── frontend/                                  # Frontend applications (Next.js 16)
β”‚       └── ...                                    # See src/frontend/task-agent-web/README.md
β”‚
β”œβ”€β”€ docs/                                          # Documentation
β”‚   β”œβ”€β”€ screenshots/                               # Application screenshots
β”‚   β”œβ”€β”€ CONTENT_SAFETY.md                          # Content Safety testing guide (75+ cases)
β”‚   β”œβ”€β”€ DUAL_DATABASE_ARCHITECTURE.md              # PostgreSQL + SQL Server patterns
β”‚   β”œβ”€β”€ POSTGRESQL_MIGRATION.md                    # PostgreSQL setup guide
β”‚   └── FRONTEND_E2E_TESTING.md                    # Frontend testing guide
β”‚
β”œβ”€β”€ scripts/                                       # PowerShell scripts
β”‚   β”œβ”€β”€ Analyze-Commits.ps1                        # Commit analysis tool
β”‚   β”œβ”€β”€ config.json                                # Script configuration
β”‚   └── README.md                                  # Scripts documentation
β”‚
β”œβ”€β”€ .github/                                       # GitHub workflows & Copilot instructions
β”‚   └── copilot-instructions.md                    # Project-specific AI guidelines
β”‚
β”œβ”€β”€ LICENSE                                        # MIT License
└── README.md                                      # This file

For detailed structure:

Key Architectural Decisions

MSBuild Configuration at Root: Directory.Build.props, Directory.Packages.props, and global.json live at src/ level (not in backend/). MSBuild searches upward from each project directory - this ensures both TaskAgent.AppHost (at src/) and backend projects (at src/backend/services/) can access them. No duplicates needed.

Clean Architecture: Domain β†’ Application β†’ Infrastructure β†’ WebApp (strict dependency flow, Domain has NO external dependencies)

Aspire Orchestration at Root: TaskAgent.AppHost lives outside backend/ because it orchestrates both backend and future frontend services

Backend-Only Telemetry: TaskAgent.ServiceDefaults is .NET-specific OpenTelemetry, lives in backend/, NOT used by frontend

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


πŸ“š 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 10, Next.js 16, React 19, Microsoft Agent Framework, .NET Aspire, and Clean Architecture

About

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

Topics

Resources

License

Stars

Watchers

Forks