> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hiperai.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Actualizar Índice RAG

> Actualizar un índice de base de conocimientos existente

# Actualizar índice

Actualice un índice de base de conocimientos existente con nuevas configuraciones, metadatos o configuración.

## Endpoint

```
PUT /indexes/{indexId}
```

## Descripción

Este endpoint permite a los administradores actualizar un índice de base de conocimientos existente. Puede modificar el nombre del índice y reasignarlo a diferentes usuarios o grupos. Sólo los administradores pueden actualizar los índices.

## Autenticación

**Requerido**: Clave API con privilegios de administrador

```
Authorization: Bearer sk-your-api-key-here
```

## Parámetros de ruta

| Parámetro | Tipo | Requerido | Descripción |
| - | - | - | - |
| `indexId` | cadena | Sí | El identificador único del índice a actualizar |

## Cuerpo de solicitud

| Parámetro | Tipo | Requerido | Descripción |
| - | - | - | - |
| `name` | cadena | No | Nuevo nombre para el índice |
| `assignedUser` | cadena | No | ID de usuario al que asignar el índice (MongoDB ObjectId) |
| `assignedGroup` | cadena | No | ID de grupo al que asignar el índice (MongoDB ObjectId) |

## Solicitud de ejemplo

```json theme={null}
{
  "name": "updated-knowledge-base",
  "assignedUser": "60a7c8f5e8b4f5001f7a8c24"
}
```

## Respuesta exitosa

**Código de estado**: `200 OK`

```json theme={null}
{
  "success": true,
  "message": "Index updated successfully",
  "index": {
    "id": "60a7c8f5e8b4f5001f7a8c23",
    "name": "updated-knowledge-base",
    "sharedIndexName": "updated-knowledge-base",
    "namespace": "user-60a7c8f5e8b4f5001f7a8c24-index-updated-knowledge-base",
    "type": "personal",
    "assignedUser": {
      "id": "60a7c8f5e8b4f5001f7a8c24",
      "name": "John Doe",
      "email": "john@example.com"
    },
    "assignedGroup": null,
    "createdAt": "2024-01-01T00:00:00.000Z",
    "updatedAt": "2024-01-15T10:30:00.000Z"
  }
}
```

### Campos de respuesta

| Campo | Tipo | Descripción |
| - | - | - |
| `success` | booleano | Indica si la operación fue exitosa |
| `message` | cadena | Mensaje de éxito |
| `index` | objeto | Objeto de índice actualizado |
| `index.id` | cadena | Identificador de índice único |
| `index.name` | cadena | Nombre del índice actualizado |
| `index.sharedIndexName` | cadena | Nombre del índice compartido |
| `index.namespace` | cadena | Espacio de nombres de índice |
| `index.type` | cadena | Tipo de índice (personal, general, grupal, desconocido) |
| `index.assignedUser` | objeto | Información de usuario asignada (si es personal) |
| `index.assignedGroup` | objeto | Información del grupo asignado (si es grupo) |
| `index.createdAt` | cadena | Marca de tiempo de creación original |
| `index.updatedAt` | cadena | Marca de tiempo de la última actualización |

## Ejemplo de uso

### JavaScript

```javascript theme={null}
const updateIndex = async (indexId, updateData) => {
  const response = await fetch(`https://{customer.name}.hiperai.ai/api/external/indexes/${indexId}`, {
    method: 'PUT',
    headers: {
      'Authorization': 'Bearer sk-your-api-key-here',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(updateData)
  });
  
  return await response.json();
};

// Example usage
const updateData = {
  name: "updated-knowledge-base",
  assignedUser: "60a7c8f5e8b4f5001f7a8c24"
};

const result = await updateIndex('60a7c8f5e8b4f5001f7a8c23', updateData);
console.log('Updated index:', result.index);
```

### Pitón

```python theme={null}
import requests

def update_index(index_id, update_data):
    url = f"https://{customer.name}.hiperai.ai/api/external/indexes/{index_id}"
    headers = {
        "Authorization": "Bearer sk-your-api-key-here",
        "Content-Type": "application/json"
    }
    
    response = requests.put(url, headers=headers, json=update_data)
    return response.json()

# Example usage
update_data = {
    "name": "updated-knowledge-base",
    "assignedUser": "60a7c8f5e8b4f5001f7a8c24"
}

result = update_index("60a7c8f5e8b4f5001f7a8c23", update_data)
print("Updated index:", result["index"])
```

### rizo

```bash theme={null}
curl -X PUT "https://{customer.name}.hiperai.ai/api/external/indexes/60a7c8f5e8b4f5001f7a8c23" \
  -H "Authorization: Bearer sk-your-api-key-here" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "updated-knowledge-base",
    "assignedUser": "60a7c8f5e8b4f5001f7a8c24"
  }'
```

## Respuestas de error

### 400 Solicitud incorrecta

```json theme={null}
{
  "success": false,
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Index name already exists or invalid assigned IDs",
    "details": {
      "field": "name | assignedUser | assignedGroup"
    }
  }
}
```

## Validaciones y reglas de negocio

* **Asignación a un usuario (`assignedUser`)**:
  * Aplicar cuota de índice de usuarios a través de `checkUserIndexQuota` al convertir a personal o cambiar el cesionario. La cuota excedida devuelve 403.
* **Asignación a un grupo (`assignedGroup`)**:
  * El grupo debe existir y estar activo (`status != 'Archived'`); los grupos no válidos/inactivos devuelven 400.

## Normalización y almacenamiento

* Al cambiar el nombre, `name` continúa almacenándose normalizado; `sharedIndexName` tiene por defecto el nombre normalizado si no se establece explícitamente.

## Formas de error típicas

### Cuota de índice 403 excedida

```json theme={null}
{
  "success": false,
  "error": "Index quota exceeded",
  "message": "User has reached the maximum number of indexes for Ultra license (current/limit)."
}
```

### 400 Grupo no válido/inactivo

```json theme={null}
{
  "success": false,
  "error": "Invalid or inactive group",
  "message": "The specified group does not exist or is not active"
}
```

### 401 No autorizado

```json theme={null}
{
  "success": false,
  "error": {
    "code": "UNAUTHORIZED",
    "message": "Invalid or missing API key"
  }
}
```

### 403 Prohibido

```json theme={null}
{
  "success": false,
  "error": {
    "code": "INSUFFICIENT_PERMISSIONS",
    "message": "Cannot update this index"
  }
}
```

### 404 no encontrado

```json theme={null}
{
  "success": false,
  "error": {
    "code": "INDEX_NOT_FOUND",
    "message": "Index not found"
  }
}
```

### 409 Conflicto

```json theme={null}
{
  "success": false,
  "error": {
    "code": "INDEX_NAME_EXISTS",
    "message": "Index name already exists"
  }
}
```

### 429 Demasiadas solicitudes

```json theme={null}
{
  "success": false,
  "error": {
    "code": "RATE_LIMIT_EXCEEDED",
    "message": "Rate limit exceeded",
    "retryAfter": 60
  }
}
```

## Campos actualizables

| Campo | Descripción | Notas |
| - | - | - |
| `name` | Nombre del índice | Debe ser único en todo el sistema |
| `assignedUser` | Asignación de usuario | Asigna índice a un usuario específico |
| `assignedGroup` | Asignación grupal | Asigna índice a un grupo específico |

## Casos de uso

* **Cambios de nombre**: cambie el nombre de los índices para una mejor organización
* **Asignación de usuarios**: reasignar índices a diferentes usuarios
* **Asignación de grupo**: reasignar índices a diferentes grupos
* **Transferencia de propiedad**: cambiar la propiedad del índice entre usuarios

## Límites de tarifas

* **Predeterminado**: 50 solicitudes por minuto
* **Diario**: 5000 solicitudes por día
* **Mensual**: 150.000 solicitudes por mes

## Notas

* Solo los administradores pueden acceder a este endpoint.
* Campos limitados: solo se pueden actualizar el nombre, el usuario asignado y el grupo asignado
* Lógica de asignación: la asignación a un usuario borra la asignación de grupo y viceversa
* Validación: las identificaciones de usuarios y grupos se validan antes de la asignación.
* Sin configuración: no se pueden actualizar configuraciones, metadatos u otras configuraciones
* La marca de tiempo `updatedAt` se actualiza automáticamente
* Los nombres de los índices deben permanecer únicos en todo el sistema.


## OpenAPI

````yaml PUT /indexes/{indexId}
openapi: 3.0.3
info:
  title: SecureAI External API
  description: >
    SecureAI External API provides AI chat completion and image generation
    capabilities with knowledge base retrieval, 

    security policies, and comprehensive usage tracking. This API is designed
    for external developers 

    and integrations using API key authentication.


    ## Key Features

    - **RAG (Retrieval-Augmented Generation)**: Automatically search knowledge
    bases for relevant context

    - **Multi-Model Support**: OpenAI, Anthropic, Google, Meta, and other AI
    models

    - **Model Redundancy & Failover**: Caller-defined failover chains (primary +
    fallbacks) with per-attempt timeouts

    - **OpenAI-Compatible Endpoint**: Point any OpenAI SDK at `/api/external/v1`
    — no code changes

    - **Image Generation**: Generate and edit images using Google Gemini 2.5
    Flash Image

    - **Speech-to-Speech (S2S)**: Real-time voice conversations using OpenAI
    Realtime API with WebRTC

    - **Security Policies**: SMLTP policy enforcement, per-call Prompt Shield,
    and signed compliance receipts

    - **Usage Tracking**: Comprehensive usage monitoring, self-service quota,
    and rate limiting

    - **Knowledge Base Integration**: Access to personal and shared knowledge
    bases

    - **User Management**: Complete user, group, and role management
    capabilities

    - **Audit Logging**: Comprehensive activity and security audit logs


    ## Authentication

    All endpoints (except health check) require API key authentication using
    Bearer token:

    ```

    Authorization: Bearer sk-your-api-key-here

    ```


    ## Billing and Usage

    By default, API requests are billed to the user account that owns the API
    key. You can specify 

    a different user to bill by including the `user_id` parameter in your
    request. This allows for:

    - Multi-tenant applications with per-user billing

    - Flexible completion limit management

    - Per-user "Usage by Model" settings


    ## Rate Limits

    - Default: 60 requests per minute, 1000 requests per hour

    - Daily limits: 100 requests (configurable)

    - Monthly limits: 10,000 requests (configurable)


    ## Base URL

    ```

    https://secureai.hiperai.ai/api/external

    ```
  version: 1.1.0
  contact:
    name: SecureAI Support
    email: support@secureai.hiperai.ai
  license:
    name: Proprietary
    url: https://secureai.hiperai.ai/terms
servers:
  - url: https://secureai.hiperai.ai/api/external
    description: Production server
  - url: http://localhost:3010/api/external
    description: Development server
security:
  - ApiKeyAuth: []
tags:
  - name: System
    description: System health and status endpoints
  - name: Discovery
    description: Endpoints to discover available models, indexes, and policies
  - name: Chat
    description: AI chat completion endpoints
  - name: User Management
    description: Endpoints for managing user accounts and roles
  - name: Index Management
    description: Endpoints for managing knowledge base indexes
  - name: Group Management
    description: Endpoints for managing user groups
  - name: SMLTP Security
    description: Endpoints for managing SMLTP security policies and audit logs
  - name: Role Management
    description: Endpoints for managing user roles
  - name: Activity Logs
    description: Endpoints for retrieving activity logs
externalDocs:
  description: SecureAI Documentation
  url: https://secureai.hiperai.ai/docs
paths:
  /indexes/{indexId}:
    put:
      tags:
        - Index Management
      summary: Update Index
      description: >
        Update an existing index (assign to user or group). Only accessible by
        administrators.
      parameters:
        - name: indexId
          in: path
          required: true
          description: Index ID to update
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                name:
                  type: string
                  description: Index name
                  example: updated-knowledge-base
                assignedUser:
                  type: string
                  description: User ID to assign the index to (MongoDB ObjectId)
                  example: 60a7c8f5e8b4f5001f7a8c24
                assignedGroup:
                  type: string
                  description: Group ID to assign the index to (MongoDB ObjectId)
                  example: 60a7c8f5e8b4f5001f7a8c25
            example:
              name: updated-knowledge-base
              assignedUser: 60a7c8f5e8b4f5001f7a8c24
      responses:
        '200':
          description: Index updated successfully
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                    example: true
                  message:
                    type: string
                    example: Index updated successfully
                  index:
                    type: object
                    properties:
                      id:
                        type: string
                        example: 60a7c8f5e8b4f5001f7a8c23
                      name:
                        type: string
                        example: updated-knowledge-base
                      sharedIndexName:
                        type: string
                        example: updated-knowledge-base
                      namespace:
                        type: string
                        example: >-
                          user-60a7c8f5e8b4f5001f7a8c24-index-updated-knowledge-base
                      type:
                        type: string
                        enum:
                          - personal
                          - general
                          - group
                          - unknown
                        example: personal
                      assignedUser:
                        type: object
                        nullable: true
                        properties:
                          id:
                            type: string
                            example: 60a7c8f5e8b4f5001f7a8c24
                          name:
                            type: string
                            example: John Doe
                          email:
                            type: string
                            example: john@example.com
                      assignedGroup:
                        type: object
                        nullable: true
                        properties:
                          id:
                            type: string
                            example: 60a7c8f5e8b4f5001f7a8c25
                          name:
                            type: string
                            example: Engineering Team
                      createdAt:
                        type: string
                        format: date-time
                        example: '2024-01-01T00:00:00.000Z'
                      updatedAt:
                        type: string
                        format: date-time
                        example: '2024-01-15T10:30:00.000Z'
        '400':
          description: Invalid request parameters
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '401':
          description: Invalid API key
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '403':
          description: Access denied - admin only
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '404':
          description: Index not found
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
      security:
        - ApiKeyAuth: []
components:
  schemas:
    ErrorResponse:
      type: object
      properties:
        success:
          type: boolean
          example: false
        error:
          type: string
          example: Invalid API key
        message:
          type: string
          example: The provided API key is invalid or has been revoked
        request_id:
          type: string
          example: req-abc123
          description: Request ID for tracking (if available)
  securitySchemes:
    ApiKeyAuth:
      type: http
      scheme: bearer
      description: |
        API key authentication using Bearer token format.
        Example: `Authorization: Bearer sk-your-api-key-here`

````

This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.