检索增强生成聊天系统

基于Azure AI Foundry的PDF文档问答系统,支持语义搜索、工具调用和异步处理。

  • by alemcuevas
  • Python
  • 本地部署
  • 更新于
在 GitHub 查看 alemcuevas/azure-rag-foundry-workshop

使用说明

🤖 RAG Chat con Azure AI Foundry

Sistema de chat con Retrieval-Augmented Generation (RAG) usando Azure AI Foundry, Azure AI Search y Tool Calling.

📋 Descripción

Este proyecto implementa un sistema completo de Q&A sobre documentos PDF que incluye:

  • Indexación de PDFs con extracción de texto e imágenes
  • Búsqueda semántica con Azure AI Search (vectorial + híbrida)
  • Tool Calling para que el modelo use herramientas automáticamente
  • Procesamiento asíncrono con Azure Service Bus y Functions
  • MCP Server para integración con VS Code Copilot

🏗️ Arquitectura

┌─────────────────┐     ┌──────────────────┐     ┌─────────────────┐
│   Frontend      │────▶│   Web App        │────▶│  Azure OpenAI   │
│   (HTML/JS)     │     │   (FastAPI)      │     │  (GPT-4.1)      │
└─────────────────┘     └────────┬─────────┘     └─────────────────┘
                                 │
                    ┌────────────┼────────────┐
                    ▼            ▼            ▼
            ┌───────────┐ ┌───────────┐ ┌───────────────┐
            │ AI Search │ │  Service  │ │   Computer    │
            │ (Vectors) │ │   Bus     │ │    Vision     │
            └───────────┘ └─────┬─────┘ └───────────────┘
                                │
                                ▼
                        ┌───────────────┐
                        │ Azure Function│
                        │ (Queue Worker)│
                        └───────────────┘

📁 Estructura del Proyecto

proyecto-rag-azure/
├── webapp/                    # Aplicación web principal
│   ├── backend/
│   │   ├── app.py            # API FastAPI con RAG y Tool Calling
│   │   └── queue_processor.py # Procesador de cola (local)
│   ├── frontend/
│   │   ├── index.html        # Interfaz del chat
│   │   ├── app.js            # Lógica del frontend
│   │   └── styles.css        # Estilos
│   ├── requirements.txt      # Dependencias Python
│   ├── run.py                # Script para ejecutar localmente
│   └── startup.sh            # Script de inicio en Azure
│
├── functions/                 # Azure Function para procesar cola
│   ├── function_app.py       # Trigger de Service Bus
│   ├── host.json             # Configuración de Functions
│   └── requirements.txt      # Dependencias
│
├── mcp/                       # MCP Server para VS Code
│   ├── mcp_server.py         # Versión completa (offline)
│   └── mcp_server_lite.py    # Versión lite (usa API)
│
├── scripts/                   # Scripts auxiliares
│   ├── crear_indice_rag.py   # Crear índice en AI Search
│   ├── indexar_documentos.py # Indexar PDFs manualmente
│   ├── busqueda_rag.py       # Probar búsquedas
│   └── verificar_ambiente.py # Verificar configuración
│
├── .vscode/
│   └── mcp.json              # Configuración MCP para Copilot
│
├── .env                       # Variables de entorno
└── README.md                  # Este archivo

🚀 Requisitos Previos

Azure Resources

  • Azure AI Foundry con modelos desplegados:
    • gpt-4.1 (o similar) para chat
    • text-embedding-3-small para embeddings
  • Azure AI Search (Basic o superior)
  • Azure App Service (Linux, Python 3.11)
  • Azure Service Bus (opcional, para cola)
  • Azure Storage (opcional, para blobs)
  • Azure Functions (opcional, para procesamiento async)

Local

  • Python 3.11+
  • Azure CLI (az login)
  • VS Code con GitHub Copilot (opcional, para MCP)

⚙️ Configuración

1. Variables de Entorno

Crea un archivo .env en la raíz:

# Azure OpenAI / AI Foundry
AZURE_OPENAI_ENDPOINT=https://tu-recurso.cognitiveservices.azure.com/
AZURE_OPENAI_API_VERSION=2024-08-01-preview
AZURE_CHAT_MODEL=gpt-4.1
AZURE_EMBEDDING_MODEL=text-embedding-3-small

# Azure AI Search
AZURE_SEARCH_ENDPOINT=https://tu-search.search.windows.net
AZURE_SEARCH_KEY=tu-api-key
AZURE_SEARCH_INDEX=documentos-pdf-rag

# Azure Computer Vision (para imágenes en PDFs)
AZURE_VISION_ENDPOINT=https://tu-recurso.cognitiveservices.azure.com/

# Azure Service Bus (opcional)
AZURE_SERVICEBUS_NAMESPACE=tu-namespace.servicebus.windows.net
AZURE_SERVICEBUS_QUEUE=pdf-processing-queue

# Azure Storage (opcional)
AZURE_STORAGE_ACCOUNT=tu-storage
AZURE_STORAGE_CONTAINER=pdf-uploads

# Web App URL (para MCP lite)
AZURE_WEBAPP_URL=https://tu-webapp.azurewebsites.net

2. Instalar Dependencias

cd webapp
pip install -r requirements.txt

🖥️ Ejecución Local

Opción 1: Script de inicio

cd webapp
python run.py

Opción 2: Uvicorn directo

cd webapp/backend
uvicorn app:app --reload --port 8000

Abre http://localhost:8000 en tu navegador.

☁️ Despliegue en Azure

Web App

cd webapp
az webapp up --name tu-webapp --resource-group tu-rg --runtime "PYTHON:3.11"

Configurar Startup Command

az webapp config set --name tu-webapp --resource-group tu-rg \
  --startup-file "cd backend && gunicorn --bind=0.0.0.0:8000 --workers=2 --timeout=120 app:app -k uvicorn.workers.UvicornWorker"

Azure Function (para cola)

cd functions
func azure functionapp publish tu-function-app

🔧 Uso del MCP con VS Code

1. Configurar .vscode/mcp.json

{
  "servers": {
    "workshop-rag": {
      "type": "stdio",
      "command": "python",
      "args": ["${workspaceFolder}/mcp/mcp_server_lite.py"],
      "env": {
        "PYTHONUNBUFFERED": "1",
        "MCP_API_BASE": "https://tu-webapp.azurewebsites.net"
      }
    }
  }
}

2. Recargar VS Code

Ctrl+Shift+P → "Developer: Reload Window"

3. Usar en Copilot Chat

Cambia a modo Agent y las herramientas estarán disponibles:

  • buscar_documentos - Buscar en PDFs indexados
  • chat - Hacer preguntas con RAG
  • listar_documentos - Ver documentos disponibles
  • estado_sistema - Verificar conexión

📖 Endpoints de la API

Método Endpoint Descripción
GET /api/health Health check
GET /api/documentos Listar documentos indexados
POST /api/upload Subir PDF para indexar
POST /api/chat Enviar mensaje al chat
GET /api/jobs Ver estado de procesamiento
GET /api/jobs/{id} Estado de un job específico

Ejemplo: Chat con RAG

curl -X POST https://tu-webapp.azurewebsites.net/api/chat \
  -H "Content-Type: application/json" \
  -d '{"mensaje": "¿Qué dice el documento sobre sostenibilidad?"}'

🛠️ Herramientas Disponibles (Tool Calling)

El modelo tiene acceso a estas herramientas:

Herramienta Descripción
buscar_documentos Búsqueda semántica en el índice
listar_documentos Lista todos los PDFs indexados
obtener_fecha_hora Fecha y hora actual
calcular Calculadora matemática

📊 Recursos de Azure Creados

Recurso Nombre Propósito
AI Services FoundryWST OpenAI + Computer Vision
AI Search search-foundry-workshop Índice vectorial
Web App chat-foundry-workshop Frontend + API
Function App func-foundry-workshop Procesa cola PDFs
Service Bus sb-foundry-workshop Cola de mensajes
Storage stfoundryworkshop Almacenamiento blobs

🔍 Troubleshooting

Error 429 (Rate Limit)

Aumenta la capacidad del modelo de embeddings:

az cognitiveservices account deployment create \
  --name tu-ai-services \
  --resource-group tu-rg \
  --deployment-name text-embedding-3-small \
  --model-name text-embedding-3-small \
  --model-version 1 \
  --model-format OpenAI \
  --sku-capacity 350 \
  --sku-name Standard

MCP no carga

  1. Verifica que mcp_server_lite.py existe
  2. Revisa que MCP_API_BASE apunta a la URL correcta
  3. Recarga VS Code completamente

Documentos no aparecen

El endpoint /api/documentos consulta Azure AI Search. Verifica:

  1. El índice existe: documentos-pdf-rag
  2. Hay documentos indexados
  3. La API key es correcta

📄 Licencia

MIT License - Libre para uso educativo y comercial.

👥 Autor

Creado durante el Azure AI Foundry Workshop.