> For the complete documentation index, see [llms.txt](https://docs.clore.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.clore.ai/guides/guides_v2-es/modelos-de-lenguaje/mistral-small.md).

# Mistral Small 3.1

Despliega Mistral Small 3.1 (24B) en Clore.ai: el modelo ideal de producción para una sola GPU

Mistral Small 3.1, lanzado en marzo de 2025 por Mistral AI, es un **modelo denso de 24 mil millones de parámetros** que supera con creces su categoría. Con una ventana de contexto de 128K, capacidades nativas de visión, llamadas a funciones de primera clase y una **licencia Apache 2.0**, posiblemente sea el mejor modelo que puedes ejecutar en una sola RTX 4090. Supera a GPT-4o Mini y Claude 3.5 Haiku en la mayoría de los benchmarks, y cabe cómodamente en hardware de consumo cuando se cuantiza.

## Características clave

* **24B de parámetros densos** — sin la complejidad de MoE, despliegue sencillo
* **Ventana de contexto de 128K** — puntuación RULER 128K de 81.2%, supera a GPT-4o Mini (65.8%)
* **Visión nativa** — analiza imágenes, gráficos, documentos y capturas de pantalla
* **licencia Apache 2.0** — totalmente abierto para uso comercial y personal
* **Llamada de funciones de élite** — uso nativo de herramientas con salida JSON, ideal para flujos de trabajo agénticos
* **Multilingüe** — más de 25 idiomas, incluidos CJK, árabe, hindi e idiomas europeos

## Requisitos

| Componente | Cuantizado (Q4)  | Precisión completa (BF16) |
| ---------- | ---------------- | ------------------------- |
| GPU        | 1× RTX 4090 24GB | 2× RTX 4090 o 1× H100     |
| VRAM       | \~16GB           | \~55GB                    |
| RAM        | 32GB             | 64GB                      |
| Disco      | 20 GB            | 50 GB                     |
| CUDA       | 12.8+            | 12.8+                     |

**Recomendación de Clore.ai**: RTX 4090 ($0.14–0.42/h) para inferencia cuantizada — la mejor relación precio/rendimiento

## Inicio rápido con Ollama

La forma más rápida de poner en marcha Mistral Small 3.1:

```bash
# Instalar Ollama
curl -fsSL https://ollama.com/install.sh | sh

# Ejecuta Mistral Small 3.1 (se descargan automáticamente ~14GB de cuantización Q4)
ollama run mistral-small3.1

# O especifica una cuantización concreta
ollama run mistral-small3.1:24b-instruct-2503-q4_K_M
```

### Ollama como API compatible con OpenAI

```bash
# Inicia el servidor de Ollama
ollama serve &

# Descarga el modelo
ollama pull mistral-small3.1

# Consulta mediante API
curl http://localhost:11434/v1/chat/completions \
  -H "Content-Type: application/json" \\
  -d '{
    "model": "mistral-small3.1",
    "messages": [
      {"role": "system", "content": "Eres un asistente de programación útil."},
      {"role": "user", "content": "Escribe un decorador de Python para limitar la tasa"}
    ],
    "temperature": 0.15
  }'
```

### Ollama con visión

```bash
# Envía una imagen para análisis
curl http://localhost:11434/api/chat -d '{
  "model": "mistral-small3.1",
  "messages": [{
    "role": "user",
    "content": "¿Qué muestra esta imagen?",
    "images": ["/path/to/image.jpg"]
  }]
}'
```

## Configuración de vLLM (producción)

Para cargas de trabajo de producción con alto rendimiento y solicitudes concurrentes:

```bash
# Instala vLLM (se requiere v0.8.1+)
pip install -U vllm

# Verifica que mistral_common esté instalado (debería ser automático)
python -c "import mistral_common; print(mistral_common.__version__)"
```

### Servir en una sola GPU (solo texto)

```bash
vllm serve mistralai/Mistral-Small-3.1-24B-Instruct-2503 \\
  --tokenizer-mode mistral \\
  --config-format mistral \\
  --load-format mistral \\
  --tool-call-parser mistral \\
  --enable-auto-tool-choice \\
  --max-model-len 32768 \
  --gpu-memory-utilization 0.90
```

### Servir con visión (se recomiendan 2 GPU)

```bash
vllm serve mistralai/Mistral-Small-3.1-24B-Instruct-2503 \\
  --tokenizer-mode mistral \\
  --config-format mistral \\
  --load-format mistral \\
  --tool-call-parser mistral \\
  --enable-auto-tool-choice \\
  --limit-mm-per-prompt 'image=10' \\
  --tensor-parallel-size 2 \\
  --max-model-len 65536
```

### Consultar el servidor

```python
from openai import OpenAI

client = OpenAI(base_url="http://localhost:8000/v1", api_key="EMPTY")

response = client.chat.completions.create(
    model="mistralai/Mistral-Small-3.1-24B-Instruct-2503",
    messages=[
        {"role": "system", "content": "Eres un asistente útil. Hoy es 2026-02-20."},
        {"role": "user", "content": "Escribe una API REST completa en FastAPI con operaciones CRUD para un blog"}
    ],
    temperature=0.15,
    max_tokens=4096
)
print(response.choices[0].message.content)
```

## Transformers de HuggingFace

Para integración y experimentación directas en Python:

```python
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

model_name = "mistralai/Mistral-Small-3.1-24B-Instruct-2503"

tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(
    model_name,
    torch_dtype=torch.bfloat16,
    device_map="auto",
    load_in_4bit=True  # Cuantización de 4 bits — cabe en una GPU de 24GB
)

messages = [
    {"role": "system", "content": "Eres un asistente de programación útil."},
    {"role": "user", "content": "Implementa un árbol binario de búsqueda en Python con métodos insert, delete y search"}
]

input_ids = tokenizer.apply_chat_template(messages, return_tensors="pt").to(model.device)

output = model.generate(
    input_ids,
    max_new_tokens=2048,
    temperature=0.15,
    do_sample=True
)
print(tokenizer.decode(output[0][input_ids.shape[-1]:], skip_special_tokens=True))
```

## Ejemplo de llamada de funciones

Mistral Small 3.1 es uno de los mejores modelos pequeños para usar herramientas:

```python
import json
from openai import OpenAI

client = OpenAI(base_url="http://localhost:8000/v1", api_key="EMPTY")

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_stock_price",
            "description": "Obtiene el precio actual de la acción para un símbolo ticker dado",
            "parameters": {
                "type": "object",
                "required": ["ticker"],
                "properties": {
                    "ticker": {"type": "string", "description": "Símbolo ticker de la acción (p. ej., AAPL)"}
                }
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "calculate_portfolio_value",
            "description": "Calcula el valor total de la cartera dadas las posiciones",
            "parameters": {
                "type": "object",
                "required": ["holdings"],
                "properties": {
                    "holdings": {
                        "type": "array",
                        "items": {
                            "type": "object",
                            "properties": {
                                "ticker": {"type": "string"},
                                "shares": {"type": "number"}
                            }
                        }
                    }
                }
            }
        }
    }
]

response = client.chat.completions.create(
    model="mistralai/Mistral-Small-3.1-24B-Instruct-2503",
    messages=[{"role": "user", "content": "¿Cuál es el precio actual de AAPL y MSFT?"}],
    tools=tools,
    tool_choice="auto",
    temperature=0.15
)

for tool_call in response.choices[0].message.tool_calls:
    print(f"Llamada: {tool_call.function.name}({tool_call.function.arguments})")
```

## Inicio rápido con Docker

```bash
# Despliegue en una sola GPU
docker run --gpus all -p 8000:8000 \\
  -v ~/.cache/huggingface:/root/.cache/huggingface \\
  vllm/vllm-openai:latest \
  --model mistralai/Mistral-Small-3.1-24B-Instruct-2503 \\
  --tokenizer-mode mistral \\
  --config-format mistral \\
  --load-format mistral \\
  --tool-call-parser mistral \\
  --enable-auto-tool-choice \\
  --max-model-len 32768

# Con soporte de visión (2 GPU)
docker run --gpus all -p 8000:8000 \\
  -v ~/.cache/huggingface:/root/.cache/huggingface \\
  vllm/vllm-openai:latest \
  --model mistralai/Mistral-Small-3.1-24B-Instruct-2503 \\
  --tokenizer-mode mistral \\
  --config-format mistral \\
  --load-format mistral \\
  --tool-call-parser mistral \\
  --enable-auto-tool-choice \\
  --limit-mm-per-prompt 'image=10' \\
  --tensor-parallel-size 2
```

## Consejos para usuarios de Clore.ai

* **La RTX 4090 es el punto ideal**: Con $0.14–0.42/h, una sola RTX 4090 ejecuta Mistral Small 3.1 cuantizado con margen de sobra. La mejor relación coste/rendimiento en Clore.ai para un LLM de propósito general.
* **Usa una temperatura baja**: Mistral AI recomienda `temperature=0.15` para la mayoría de las tareas. Las temperaturas más altas causan salidas inconsistentes con este modelo.
* **La RTX 3090 también funciona**: Con $0.07–0.21/h, la RTX 3090 (24GB) ejecuta Q4 cuantizado con Ollama sin problema. Un poco más lenta que la 4090, pero a la mitad de precio.
* **Ollama para configuraciones rápidas, vLLM para producción**: Ollama te da un modelo funcional en 60 segundos. Para solicitudes API concurrentes y mayor rendimiento, cambia a vLLM.
* **La llamada de funciones lo hace especial**: Muchos modelos de 24B pueden chatear — pocos pueden llamar herramientas de forma fiable. La llamada de funciones de Mistral Small 3.1 está a la altura de GPT-4o Mini. Construye agentes, backends de API y canalizaciones de automatización con confianza.

## Solución de problemas

| Problema                                 | Solución                                                                                                       |
| ---------------------------------------- | -------------------------------------------------------------------------------------------------------------- |
| `OutOfMemoryError` en RTX 4090           | Usa el modelo cuantizado mediante Ollama o `load_in_4bit=True` en Transformers. BF16 completo necesita \~55GB. |
| Modelo de Ollama no encontrado           | Usa `ollama run mistral-small3.1` (nombre oficial de la biblioteca).                                           |
| Errores de tokenizador de vLLM           | Siempre pasa `--tokenizer-mode mistral --config-format mistral --load-format mistral`.                         |
| Mala calidad de salida                   | Establece `temperature=0.15`. Añade un prompt del sistema. Mistral Small es sensible a la temperatura.         |
| La visión no funciona en 1 GPU           | Las funciones de visión necesitan más VRAM. Usa `--tensor-parallel-size 2` o reduce `--max-model-len`.         |
| Las llamadas a funciones devuelven vacío | Añade `--tool-call-parser mistral --enable-auto-tool-choice` a vLLM serve.                                     |

## Lecturas adicionales

* [Mistral Small 3.1 en HuggingFace](https://huggingface.co/mistralai/Mistral-Small-3.1-24B-Instruct-2503)
* [Entrada del blog de Mistral AI](https://mistral.ai/news/mistral-small-3-1/)
* [Página del modelo en Ollama](https://ollama.com/library/mistral-small3.1)
* [Documentación de vLLM](https://docs.vllm.ai/)
* [Biblioteca Mistral Common](https://github.com/mistralai/mistral-common)
* [Plataforma de Mistral AI](https://console.mistral.ai/)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.clore.ai/guides/guides_v2-es/modelos-de-lenguaje/mistral-small.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
