Skip to content

Latest commit

 

History

History
506 lines (418 loc) · 14.2 KB

File metadata and controls

506 lines (418 loc) · 14.2 KB

React TypeScript Azure AI Foundry Agent Integration - Development Specification (Recommended)

Overview

A modern React.js application with TypeScript that provides a chat interface for connecting to an existing agent in Azure AI Foundry. This is a prototype application designed for development purposes with a focus on modern UI/UX patterns and seamless AI agent integration.

🚨 CRITICAL CONFIGURATION NOTES

⚠️ Build Tool & Deployment Alignment

CRITICAL: Ensure build tool output directory matches deployment configuration to prevent deployment issues.

  • Build Tool: Vite (outputs to dist/ folder)
  • Azure Static Web Apps: Must be configured to deploy from dist/ folder
  • azure.yaml: dist: dist (NOT dist: build)

🔧 Development Environment Prerequisites

Required before starting development:

  1. Docker Desktop: Must be running for backend container deployment
  2. Azure CLI: Properly installed and in system PATH
  3. Azure Developer CLI (azd): Latest version installed and in PATH
  4. Node.js 18+: With npm/yarn package manager
  5. Environment PATH: Ensure all CLIs are accessible from any terminal

Application Architecture

Overall Architecture

  • Frontend: React.js 18+ with TypeScript (Client-side)
  • Backend: Node.js/Express API service wrapper (Server-side)
  • Agent Integration: Azure AI Foundry agent (Existing)
  • Deployment: Separate hosting for frontend and backend services

Frontend Framework

  • Framework: React.js 18+
  • Language: TypeScript
  • Build Tool: Vite (modern, fast builds with better DX than Webpack)
  • Package Manager: npm
  • Build Output: dist/ folder (Vite default)
  • Dev Server: Hot Module Replacement (HMR) enabled
  • Environment Variables: Prefixed with VITE_ (not REACT_APP_)

Backend Service Wrapper

  • Framework: Node.js with Express.js
  • Language: TypeScript
  • Purpose: Secure proxy for Azure AI Foundry agent communication
  • Hosting: Azure Container Apps (preferred) or Azure App Service
  • Container: Docker-based deployment

Core Technology Stack

Runtime Environment

  • Node.js 18+
  • TypeScript 5.0+

Primary Dependencies

{
  "react": "^18.2.0",
  "react-dom": "^18.2.0",
  "typescript": "^5.0.0",
  "@azure/ai-agents": "^1.0.0",
  "@azure/identity": "^3.4.0",
  "@azure/core-auth": "^1.5.0",
  "@azure/core-client": "^1.7.0",
  "axios": "^1.6.0"
}

Development and Build Tools

  • TypeScript Compiler: typescript, ts-node
  • Bundling: vite (replaces webpack for better performance)
  • Testing: vitest (Vite's native test runner), @testing-library/react
  • Linting: eslint, @typescript-eslint/parser
  • Code Formatting: prettier

UI/UX Libraries

  • CSS Framework: Tailwind CSS (configured for Vite)
  • Icons: Lucide React (tree-shakeable icons)
  • State Management: React hooks (useState, useReducer)
  • Component Library: Custom components with consistent design system

🛠️ Critical Configuration Sections

Build Configuration Alignment

Vite Configuration (vite.config.ts)

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react()],
  build: {
    outDir: 'dist', // ← This MUST match azure.yaml dist setting
    sourcemap: true,
    rollupOptions: {
      output: {
        manualChunks: {
          vendor: ['react', 'react-dom'],
          azure: ['@azure/identity', '@azure/ai-agents']
        }
      }
    }
  },
  server: {
    port: 3000,
    proxy: {
      '/api': 'http://localhost:8080'
    }
  }
})

Azure Developer CLI Configuration (azure.yaml)

# yaml-language-server: $schema=https://raw.githubusercontent.com/Azure/azure-dev/main/schemas/v1.0/azure.yaml.json

name: react-ai-chat-prototype
metadata:
  template: react-ai-chat-prototype@0.0.1-beta

services:
  backend:
    project: ./backend
    language: ts
    host: containerapp
    docker:
      path: Dockerfile
      context: .
  
  frontend:
    project: ./frontend
    language: ts
    host: staticwebapp
    dist: dist  # ← CRITICAL: Must match Vite output directory

hooks:
  preprovision:
    shell: sh
    run: |
      echo "🔍 Validating environment prerequisites..."
      
      # Check required environment variables
      if [ -z "$AZURE_AI_FOUNDRY_ENDPOINT" ]; then
        echo "❌ Error: AZURE_AI_FOUNDRY_ENDPOINT is required"
        exit 1
      fi
      if [ -z "$AZURE_AI_AGENT_ID" ]; then
        echo "❌ Error: AZURE_AI_AGENT_ID is required"
        exit 1
      fi
      
      # Check Docker is running
      if ! docker info > /dev/null 2>&1; then
        echo "❌ Error: Docker is not running. Please start Docker Desktop."
        exit 1
      fi
      
      echo "✅ Environment validation passed"

  postprovision:
    shell: sh
    run: |
      echo "✅ Infrastructure provisioning completed"
      echo "🔧 Setting up application configuration..."

  prepackage:
    shell: sh
    run: |
      echo "📦 Building application packages..."
      # Build frontend with correct output directory
      cd frontend && npm run build && echo "✅ Frontend built to dist/"
      # Build backend
      cd ../backend && npm run build && echo "✅ Backend built"

Environment Variables Configuration

Frontend Environment Variables (.env.local)

# Backend API Configuration
VITE_API_BASE_URL=http://localhost:8080/api
VITE_WS_URL=ws://localhost:8080

# Application Configuration
VITE_APP_NAME=Azure AI Chat
VITE_APP_VERSION=1.0.0

# Development Settings
VITE_ENVIRONMENT=development
VITE_LOG_LEVEL=debug

# Note: VITE_ prefix is required for Vite (not REACT_APP_)

Backend Environment Variables (.env)

# Server Configuration
PORT=8080
NODE_ENV=development

# Azure AI Foundry Configuration (Secure - Server-side only)
AZURE_AI_FOUNDRY_ENDPOINT=https://your-foundry-endpoint.azure.com
AZURE_AI_AGENT_ID=your-agent-id

# Azure Authentication (Service Principal)
AZURE_CLIENT_ID=your-backend-service-principal-id
AZURE_CLIENT_SECRET=your-backend-service-principal-secret
AZURE_TENANT_ID=your-tenant-id

# Azure Key Vault
AZURE_KEY_VAULT_URL=https://your-keyvault.vault.azure.net/

# CORS Configuration
ALLOWED_ORIGINS=http://localhost:3000,https://your-frontend-domain.com

# Rate Limiting
RATE_LIMIT_WINDOW_MS=900000
RATE_LIMIT_MAX_REQUESTS=100

# Logging
LOG_LEVEL=debug
APPLICATION_INSIGHTS_CONNECTION_STRING=your-app-insights-connection-string

🚀 Pain-Free Development Workflow

Quick Start Checklist

  1. ✅ Prerequisites Check

    # Verify all tools are installed and accessible
    node --version          # Should be 18+
    docker --version        # Should be running
    az --version           # Azure CLI
    azd version            # Azure Developer CLI
  2. ✅ Environment Setup

    # Clone and setup
    git clone <repository-url>
    cd react-ai-chat-prototype
    
    # Install all dependencies
    npm install                    # Root dependencies
    cd frontend && npm install     # Frontend dependencies
    cd ../backend && npm install   # Backend dependencies
  3. ✅ Configuration Validation

    # Verify build configuration alignment
    cd frontend
    npm run build  # Should output to dist/ folder
    ls -la dist/   # Verify files exist
    
    # Verify azure.yaml points to correct folder
    grep "dist:" ../azure.yaml  # Should show "dist: dist"

Development Commands

Recommended Development Flow

# 1. Start backend first (in terminal 1)
cd backend
npm run dev

# 2. Start frontend (in terminal 2)  
cd frontend
npm run dev

# 3. Verify both services are running
curl http://localhost:8080/health  # Backend health check
open http://localhost:3000         # Frontend

Build & Deploy Commands

# Build both applications
npm run build:all

# Deploy to Azure (after ensuring Docker is running)
azd up

# Deploy only frontend (faster for UI changes)
azd deploy frontend

# Deploy only backend (for API changes)
azd deploy backend

🔧 Project Structure (Updated for Vite)

Frontend Application (React with Vite)

frontend/
├── public/
│   ├── index.html
│   └── favicon.ico
├── src/
│   ├── components/
│   │   ├── Chat/
│   │   │   ├── ChatContainer.tsx
│   │   │   ├── ChatMessage.tsx
│   │   │   └── MessageInput.tsx
│   │   └── Layout/
│   │       ├── Header.tsx          # ← App-level header component
│   │       └── Footer.tsx
│   ├── services/
│   │   ├── apiClient.ts
│   │   └── types.ts
│   ├── hooks/
│   │   └── useChat.ts
│   ├── types/
│   │   ├── chat.ts
│   │   └── api.ts
│   ├── utils/
│   │   └── config.ts
│   ├── App.tsx                     # ← Contains header + chat layout
│   ├── main.tsx                    # ← Vite entry point (not index.tsx)
│   └── vite-env.d.ts              # ← Vite environment types
├── package.json
├── tsconfig.json
├── vite.config.ts                  # ← Vite configuration (not webpack)
├── tailwind.config.js
├── postcss.config.js
├── .env.local                      # ← Local environment variables
└── README.md

Backend Service Wrapper (Node.js/Express)

backend/
├── src/
│   ├── controllers/
│   │   ├── chatController.ts
│   │   └── healthController.ts
│   ├── services/
│   │   └── azureAgentService.ts
│   ├── middleware/
│   │   ├── errorHandler.ts
│   │   └── rateLimiter.ts
│   ├── routes/
│   │   ├── chat.ts
│   │   └── health.ts
│   ├── types/
│   │   ├── agent.ts
│   │   ├── api.ts
│   │   └── chat.ts
│   ├── utils/
│   │   ├── config.ts
│   │   ├── logger.ts
│   │   └── helpers.ts
│   ├── app.ts
│   └── server.ts
├── dist/                           # ← Build output directory
├── tests/
├── package.json
├── tsconfig.json
├── Dockerfile                      # ← Container configuration
├── .env                           # ← Environment variables
└── README.md

🐛 Common Issues & Prevention

1. Build/Deploy Folder Mismatch

Problem: Header not visible after deployment Root Cause: azure.yaml dist: build but Vite outputs to dist/ Prevention:

  • Always verify vite.config.ts build.outDir matches azure.yaml dist setting
  • Add validation script to check folder alignment

2. Environment Variable Access

Problem: Frontend can't access environment variables Root Cause: Using REACT_APP_ prefix instead of VITE_ Prevention:

  • Use VITE_ prefix for all frontend environment variables
  • Add TypeScript definitions for environment variables

3. Docker Not Running

Problem: azd up fails with container errors Root Cause: Docker Desktop not started Prevention:

  • Add Docker check in preprovision hook
  • Include Docker status verification in setup documentation

4. Azure CLI Path Issues

Problem: azd command not found in terminal Root Cause: Azure CLI not in system PATH Prevention:

  • Include PATH verification in setup steps
  • Provide PowerShell script to fix PATH issues

🚀 Deployment Strategy

Development Environment

# 1. Validate prerequisites
npm run validate:env

# 2. Build and test locally
npm run build:all
npm run test:all

# 3. Deploy to development
azd up --environment dev

# 4. Verify deployment
curl https://your-app.azurestaticapps.net/

Production Deployment

# 1. Run full test suite
npm run test:all
npm run lint:all

# 2. Build optimized version
npm run build:prod

# 3. Deploy to production
azd up --environment prod

🔍 Debugging Tools & Techniques

Visual Debugging Approach

// Add obvious visual markers for debugging
const DebugHeader = () => (
  <div style={{
    background: 'red',
    color: 'white',
    padding: '20px',
    fontSize: '24px',
    textAlign: 'center',
    border: '5px solid yellow'
  }}>
    🚨 DEBUG: Header Component Rendered 🚨
  </div>
);

// Use console logging for component rendering
console.log('🔍 App component rendering...');

Deployment Verification

# Check build output exists
ls -la frontend/dist/

# Verify azure.yaml configuration
cat azure.yaml | grep "dist:"

# Test deployment without cache
curl "https://your-app.azurestaticapps.net/?cache_bust=$(date +%s)"

📚 Best Practices for Pain-Free Development

1. Configuration Management

  • Keep build tool and deployment configurations in sync
  • Use validation scripts to check configuration alignment
  • Document all environment variable requirements

2. Development Environment

  • Provide automated setup scripts
  • Include prerequisite validation
  • Use consistent tooling across team

3. Debugging Strategy

  • Start with obvious visual markers
  • Use systematic elimination approach
  • Verify each layer before moving to the next

4. Deployment Pipeline

  • Validate build outputs before deployment
  • Use health checks at each deployment stage
  • Implement rollback procedures

🎯 Success Metrics

Development Experience

  • ✅ One-command environment setup
  • ✅ Fast build and deploy cycles
  • ✅ Clear error messages and debugging
  • ✅ Consistent behavior across environments

Application Quality

  • ✅ Modern React with TypeScript
  • ✅ Secure Azure AI integration
  • ✅ Responsive and accessible UI
  • ✅ Production-ready deployment

💡 Key Improvements Over Original Spec

  1. Build Tool Modernization: Vite instead of Webpack for faster builds
  2. Configuration Alignment: Explicit matching of build output and deployment directories
  3. Environment Validation: Automated checks for prerequisites
  4. Debugging Strategy: Systematic approach with visual markers
  5. Pain Point Prevention: Specific solutions for common deployment issues
  6. Developer Experience: Streamlined commands and clear documentation

This specification addresses the key pain points encountered during development and provides a more robust foundation for building Azure AI chat applications.