Skip to content

Nambu89/Agent_Framwrok_Agent_Multisystem

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

17 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

🤖 Project Manager AI - Sistema Multiagente Azure

Sistema inteligente de análisis de proyectos de IA usando Microsoft Agent Framework, Azure OpenAI y validación técnica en tiempo real.

Azure Python Next.js FastAPI TypeScript


📋 Tabla de Contenidos


🎯 ¿Qué es Project Manager AI?

Project Manager AI es un sistema multiagente que automatiza el análisis completo de proyectos de inteligencia artificial:

¿Qué hace?

Usuario describe proyecto → Sistema analiza → Genera análisis completo en 2-3 minutos

¿Qué incluye el análisis?

  • Caso de uso detallado con tecnologías Azure recomendadas
  • Roadmap técnico con fases, tareas y estimaciones de tiempo
  • Validación de viabilidad técnica, operacional y económica
  • Análisis de riesgos con scoring cuantitativo (0-1000 puntos)
  • Estimación de costos con precios actualizados de Azure
  • Debate inteligente si detecta inconsistencias críticas
  • Exportación profesional a Word (.docx) y Excel (.xlsx)

✨ Features Principales

🧠 Sistema Multiagente Inteligente

5 agentes especializados trabajando en conjunto:

Agente Función Output
🎯 UseCase Agent Análisis de caso de uso y recomendaciones tecnológicas Arquitectura Azure propuesta
🗓️ Planner Agent Roadmap con fases, tareas y estimaciones Timeline detallado
Validator Agent Validación de viabilidad técnica/operacional/económica Score de viabilidad (0-6)
⚠️ Risk Agent Identificación y cuantificación de riesgos Matriz de riesgos con scores
💰 Cost Agent Estimación de costos usando Azure Retail API Tabla de costos detallada

🎭 Sistema de Debate

Detecta y resuelve automáticamente inconsistencias críticas:

  • 🔴 Riesgos críticos (severity ≥ 7/10)
  • 🔴 Tecnologías deprecated detectadas por Perplexity Search
  • 🔴 Desajuste presupuestario (> 30% diferencia)
  • 🔴 Timeline poco realista (score < 5/6)

Proceso:

Detección → Moderador → Debate multi-ronda → Consenso → Resolución

🔍 Validación Técnica en Tiempo Real

Technology Validator Tool powered by Perplexity Search API:

  • ✅ Detecta tecnologías CURRENT (actualizadas)
  • ⚠️ Detecta tecnologías LEGACY (antiguas pero soportadas)
  • ❌ Detecta tecnologías DEPRECATED (obsoletas)
  • 💡 Sugiere alternativas modernas automáticamente

Ejemplo:

Input:  "Cognitive Services"
Output: DEPRECATED (severity 9/10)
        → Recomienda: "Azure AI Services"

💰 Pricing Dinámico

Estimación de costos usando Azure Retail Prices API:

  • 🔄 Precios actualizados en tiempo real
  • 🌍 Soporte para múltiples regiones (West Europe, East US, etc.)
  • 📊 Desglose detallado por servicio Azure
  • 💵 Conversión automática a EUR (desde USD)

📊 Exportación Profesional

Genera documentación lista para presentar al cliente:

📄 Word (.docx):

  • Resumen ejecutivo
  • Arquitectura técnica
  • Roadmap detallado
  • Análisis de riesgos
  • Presupuesto

📊 Excel (.xlsx):

  • Tabla de costos por servicio
  • Timeline con fechas
  • Matriz de riesgos con scoring
  • Resumen de tecnologías

🏗️ Arquitectura

Stack Tecnológico

┌─────────────────────────────────────────────┐
│           FRONTEND (Next.js 15)             │
│  React 18 + TypeScript + Tailwind CSS      │
│  Server-Sent Events (SSE) para streaming   │
└──────────────────┬──────────────────────────┘
                   │ HTTP/SSE
                   ▼
┌─────────────────────────────────────────────┐
│           BACKEND (FastAPI)                 │
│  Python 3.11 + Pydantic + Uvicorn          │
└──────────────────┬──────────────────────────┘
                   │
                   ▼
┌─────────────────────────────────────────────┐
│     MICROSOFT AGENT FRAMEWORK v1.0          │
│  ┌─────────────────────────────────────┐   │
│  │   AgentCoordinator                  │   │
│  │   ├── ProjectAnalysisWorkflow       │   │
│  │   │   ├── UseCaseAgent              │   │
│  │   │   ├── PlannerAgent              │   │
│  │   │   ├── ValidatorAgent            │   │
│  │   │   ├── RiskAgent                 │   │
│  │   │   └── CostAgent                 │   │
│  │   └── DebateSystem (optional)       │   │
│  └─────────────────────────────────────┘   │
└──────────────────┬──────────────────────────┘
                   │
        ┌──────────┼──────────┐
        │          │          │
        ▼          ▼          ▼
┌──────────┐ ┌──────────┐ ┌──────────┐
│  Azure   │ │Perplexity│ │  Azure   │
│  OpenAI  │ │  Search  │ │  Retail  │
│ GPT-4o   │ │   API    │ │ Prices   │
└──────────┘ └──────────┘ └──────────┘

Flujo de Procesamiento

1️⃣ Usuario envía query
      ↓
2️⃣ AgentCoordinator inicializa ProjectAnalysisWorkflow
      ↓
3️⃣ Ejecución secuencial de agentes:
   
   🎯 UseCase Agent
      ├─ Analiza descripción del proyecto
      ├─ Recomienda arquitectura Azure
      └─ Output: Caso de uso + Stack tecnológico
      
   🗓️ Planner Agent  
      ├─ Input: Caso de uso del UseCase Agent
      ├─ Genera roadmap con fases y tareas
      └─ Output: Timeline detallado (2-6 meses típicamente)
      
   ✅ Validator Agent
      ├─ Input: Caso de uso + Roadmap
      ├─ Valida viabilidad (técnica, operacional, económica)
      ├─ Tool: TechnologyValidatorTool (Perplexity Search)
      └─ Output: Score 0-6 + Lista de tecnologías deprecated
      
   ⚠️ Risk Agent
      ├─ Input: Outputs de agentes anteriores
      ├─ Identifica riesgos por categoría
      ├─ Scoring: probabilidad (0-10) × impacto (0-10) × 10
      └─ Output: Matriz de riesgos con scores 0-1000
      
   💰 Cost Agent
      ├─ Input: Stack tecnológico del UseCase Agent
      ├─ Tool: Azure Retail Prices API
      ├─ Estimación por servicio + región
      └─ Output: Presupuesto detallado en EUR
      
4️⃣ StopGate: Evalúa calidad del análisis (score 0-6)
      ├─ Si score < 3.5 → Rechaza y pide más info
      └─ Si score ≥ 3.5 → Aprueba y continúa
      
5️⃣ DebateSystem (opcional)
      ├─ Detecta inconsistencias críticas
      ├─ Moderador facilita debate entre agentes
      └─ Output: Resolución consensuada
      
6️⃣ Generación de respuesta final
      ├─ Consolidación de outputs
      ├─ Formato Markdown estructurado
      └─ Stream al frontend via SSE

🚀 Quick Start

Prerequisitos

# Software requerido
- Docker >= 20.10
- Docker Compose >= 2.0
- Azure CLI >= 2.50
- Node.js >= 20.x (solo desarrollo local)
- Python >= 3.11 (solo desarrollo local)

Recursos Azure Necesarios

  • ✅ Azure OpenAI Service con deployment gpt-4o
  • ✅ Azure Container Registry (para deployment)
  • ✅ Perplexity API Key (opcional pero recomendado)

🐳 Opción 1: Docker Compose (Recomendado)

# 1. Clonar repositorio
git clone <tu-repo-url>
cd agentframework

# 2. Configurar variables de entorno
cp .env.example .env
nano .env  # Editar con tus valores

# 3. Levantar servicios
docker-compose up --build

# 4. Acceder a la aplicación
# Frontend: http://localhost:3000
# Backend:  http://localhost:8000
# API Docs: http://localhost:8000/docs

💻 Opción 2: Desarrollo Local

Backend:

cd backend

# Crear entorno virtual
python -m venv venv
source venv/bin/activate  # Linux/Mac
# o
venv\Scripts\activate  # Windows

# Instalar dependencias
pip install -r requirements.txt

# Configurar .env
cp .env.example .env
nano .env

# Iniciar servidor
python main.py --api

# API disponible en http://localhost:8000

Frontend:

cd frontend

# Instalar dependencias
npm install

# Configurar variables
cp .env.local.example .env.local
nano .env.local

# Modo desarrollo
npm run dev

# Frontend disponible en http://localhost:3000

📦 Deployment

🚢 Deployment en Azure Web App

El proyecto está optimizado para deployment en Azure Web App for Containers como un single container (backend + frontend).

1. Build y Push a Azure Container Registry:

# Opción A: Build en Azure (más rápido)
az acr build \
  --registry <TU_REGISTRY_NAME> \
  --image agentframework:2.0 \
  --file Dockerfile \
  --platform linux \
  .

# Opción B: Build local
docker build -t <REGISTRY>.azurecr.io/agentframework:2.0 .
docker push <REGISTRY>.azurecr.io/agentframework:2.0

2. Crear Web App:

# Crear App Service Plan
az appservice plan create \
  --name agentframework-plan \
  --resource-group <RG_NAME> \
  --is-linux \
  --sku B2

# Crear Web App
az webapp create \
  --name <APP_NAME> \
  --resource-group <RG_NAME> \
  --plan agentframework-plan \
  --deployment-container-image-name <REGISTRY>.azurecr.io/agentframework:2.0

3. Configurar Variables de Entorno:

# Si usas Azure Key Vault (recomendado)
az webapp config appsettings set \
  --name <APP_NAME> \
  --resource-group <RG_NAME> \
  --settings \
    "AZURE_KEY_VAULT_NAME=<YOUR_KV_NAME>" \
    "AZURE_OPENAI_ENDPOINT=@Microsoft.KeyVault(SecretUri=https://<KV_NAME>.vault.azure.net/secrets/AZURE-OPENAI-ENDPOINT/)" \
    "WEBSITES_PORT=3000"

# O variables directas (menos seguro)
az webapp config appsettings set \
  --name <APP_NAME> \
  --resource-group <RG_NAME> \
  --settings \
    "AZURE_OPENAI_ENDPOINT=https://<resource>.openai.azure.com/" \
    "AZURE_OPENAI_DEPLOYMENT_NAME=gpt-4o" \
    "WEBSITES_PORT=3000"

4. Configurar Managed Identity:

# Habilitar System-Assigned Identity
az webapp identity assign \
  --name <APP_NAME> \
  --resource-group <RG_NAME>

# Dar permisos al Key Vault
az keyvault set-policy \
  --name <KV_NAME> \
  --object-id <IDENTITY_PRINCIPAL_ID> \
  --secret-permissions get list

☸️ Deployment en Kubernetes/Rancher

Ver DEPLOYMENT.md para instrucciones detalladas de deployment en AKS con Rancher.


🔧 Configuración

Variables de Entorno

Obligatorias:

# Azure OpenAI
AZURE_OPENAI_ENDPOINT=https://<resource>.openai.azure.com/
AZURE_OPENAI_DEPLOYMENT_NAME=gpt-4o
AZURE_OPENAI_API_VERSION=2024-08-01-preview

# Autenticación Azure (elegir una)
# Opción 1: Azure CLI (desarrollo)
# Ya autenticado con: az login

# Opción 2: Service Principal (producción)
AZURE_CLIENT_ID=<service-principal-id>
AZURE_CLIENT_SECRET=<service-principal-secret>
AZURE_TENANT_ID=<tenant-id>

Opcionales:

# Aplicación
ENVIRONMENT=production
LOG_LEVEL=INFO
PORT=8000
ALLOWED_ORIGINS=http://localhost:3000,https://myapp.azurewebsites.net

# Streaming
ENABLE_STREAMING=true
STREAM_CHUNK_SIZE=1024

# Debate System
DEBATE_ENABLED=true
DEBATE_RISK_THRESHOLD=200
DEBATE_BUDGET_MISMATCH_THRESHOLD=0.3
DEBATE_SEVERITY_THRESHOLD=7
DEBATE_TIMELINE_SCORE_THRESHOLD=5

# Technology Validation (Perplexity Search)
PERPLEXITY_API_KEY=<your-perplexity-key>
TECH_VALIDATION_ENABLED=true
TECH_VALIDATION_MODE=conservative  # conservative | balanced | aggressive
TECH_VALIDATION_DEPRECATED_SEVERITY=9
TECH_VALIDATION_LEGACY_SEVERITY=7

# Agentes (configuración de tokens y temperatura)
USECASE_MAX_TOKENS=4000
USECASE_TEMPERATURE=0.7
PLANNER_MAX_TOKENS=4000
PLANNER_TEMPERATURE=0.6
# ... (ver .env.example para más)

# Frontend
NEXT_PUBLIC_API_URL=http://localhost:8000
NODE_ENV=production

Azure Key Vault (Recomendado para Producción)

  1. Crear Key Vault:
az keyvault create \
  --name <KV_NAME> \
  --resource-group <RG_NAME> \
  --location westeurope
  1. Añadir secrets:
az keyvault secret set \
  --vault-name <KV_NAME> \
  --name AZURE-OPENAI-ENDPOINT \
  --value "https://<resource>.openai.azure.com/"

az keyvault secret set \
  --vault-name <KV_NAME> \
  --name PERPLEXITY-API-KEY \
  --value "<your-key>"
  1. Configurar en la app:
# Solo necesitas esta variable
AZURE_KEY_VAULT_NAME=<KV_NAME>

El backend cargará automáticamente todos los secrets del Key Vault al iniciar.


📚 Documentación API

Endpoints Principales

POST /api/chat

Procesa un query de proyecto y devuelve análisis completo vía SSE.

Request:

{
  "message": "Necesito crear un sistema de recomendaciones con ML para un e-commerce con 1M de usuarios",
  "stream": true
}

Response (SSE):

data: {"type": "phase", "content": "🎯 Fase 1/6: Análisis de Caso de Uso"}

data: {"type": "content", "content": "## 📊 Análisis del Proyecto..."}

data: {"type": "phase", "content": "🗓️ Fase 2/6: Planificación"}

...

data: {"type": "complete", "content": "Análisis completado"}

GET /api/health

Health check básico para liveness probe.

Response:

{
  "status": "healthy",
  "service": "Project Manager AI",
  "version": "2.0.0",
  "timestamp": "2025-10-23T10:00:00.000Z"
}

GET /api/health/ready

Health check completo que verifica todos los componentes:

Response (200 OK):

{
  "status": "healthy",
  "timestamp": "2025-10-23T10:00:00.000Z",
  "checks": {
    "coordinator": {
      "status": "healthy",
      "message": "Coordinador inicializado correctamente"
    },
    "agents": {
      "status": "healthy",
      "count": 5,
      "agents": ["UseCaseAgent", "PlannerAgent", ...]
    },
    "azure_openai": {
      "status": "healthy",
      "endpoint": "https://***.openai.azure.com/",
      "deployment": "gpt-4o"
    },
    "key_vault": {
      "status": "healthy",
      "name": "projectmanager-kv"
    }
  }
}

Response (503 Service Unavailable):

{
  "status": "unhealthy",
  "checks": {
    "coordinator": {
      "status": "unhealthy",
      "error": "Failed to initialize coordinator"
    }
  }
}

GET /api/system/info

Información del sistema multiagente.

Response:

{
  "framework": "Microsoft Agent Framework",
  "version": "1.0.0b251016",
  "agents_configured": 5,
  "workflow": "ProjectAnalysisWorkflow",
  "debate_enabled": true,
  "streaming_enabled": true
}

Documentación Interactiva


🧪 Testing

Health Checks

# Liveness (¿está vivo?)
curl http://localhost:8000/api/health

# Readiness (¿está listo para recibir tráfico?)
curl http://localhost:8000/api/health/ready

# System Info
curl http://localhost:8000/api/system/info

Test End-to-End

# Con streaming
curl -X POST http://localhost:8000/api/chat \
  -H "Content-Type: application/json" \
  -d '{
    "message": "Quiero crear un chatbot con IA para atención al cliente de un banco",
    "stream": true
  }'

# Sin streaming
curl -X POST http://localhost:8000/api/chat \
  -H "Content-Type: application/json" \
  -d '{
    "message": "Sistema de detección de fraude con ML en tiempo real",
    "stream": false
  }'

Test con Postman/Insomnia

  1. Importar colección desde docs/postman_collection.json
  2. Configurar variable BASE_URL = http://localhost:8000
  3. Ejecutar requests

🤝 Contribuir

Reportar Bugs

Abre un issue en GitHub con:

  • Descripción del problema
  • Pasos para reproducir
  • Logs relevantes
  • Environment (local/Docker/Azure)

Proponer Features

Abre un issue con:

  • Descripción de la feature
  • Use case / problema que resuelve
  • Propuesta de implementación (opcional)

Pull Requests

  1. Fork del repositorio
  2. Crear branch: git checkout -b feature/nueva-feature
  3. Commit changes: git commit -m 'Add nueva feature'
  4. Push: git push origin feature/nueva-feature
  5. Abrir Pull Request

📖 Documentación Adicional


🛠️ Tech Stack Completo

Backend

  • Framework: Microsoft Agent Framework v1.0.0
  • API: FastAPI 0.115 + Uvicorn
  • Language: Python 3.11
  • Validation: Pydantic 2.9
  • Logging: Loguru 0.7
  • Azure SDK: azure-identity, azure-keyvault-secrets
  • HTTP Client: httpx (async)
  • Streaming: sse-starlette

Frontend

  • Framework: Next.js 15 (App Router)
  • UI Library: React 18
  • Language: TypeScript 5.0
  • Styling: Tailwind CSS 3.4
  • Components: shadcn/ui
  • Icons: Lucide React
  • HTTP: Fetch API + EventSource (SSE)

AI & Tools

  • LLM: Azure OpenAI GPT-4o
  • Search: Perplexity Search API
  • Pricing: Azure Retail Prices API
  • Orchestration: Microsoft Agent Framework

DevOps

  • Containers: Docker + Docker Compose
  • Registry: Azure Container Registry
  • Deployment: Azure Web App for Containers
  • CI/CD: Azure DevOps / GitHub Actions
  • Monitoring: Azure Application Insights
  • Secrets: Azure Key Vault

📄 Licencia

Este proyecto está bajo la licencia MIT. Ver LICENSE para más detalles.


🆘 Soporte

¿Problemas? ¿Preguntas?

  1. 📖 Consulta la documentación completa
  2. 🐛 Abre un issue en GitHub

⭐ Si este proyecto te resultó útil, considera darle una estrella ⭐

⬆ Volver arriba

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published