# Mistral Small 3.1

Mistral Small 3.1，由 Mistral AI 于 2025 年 3 月发布，是一个 **240 亿参数的密集模型** 其表现远超其体量。具有 128K 上下文窗口、原生视觉能力、同类最佳的函数调用，以及一个 **Apache 2.0 许可证**，可以说是在单块 RTX 4090 上能运行的最佳模型。它在大多数基准测试中超越 GPT-4o Mini 和 Claude 3.5 Haiku，并且量化后可舒适地适配消费级硬件。

## 主要特性

* **24B 密集参数** — 无 MoE 复杂性，部署简洁明了
* **128K 上下文窗口** — RULER 128K 得分 81.2%，优于 GPT-4o Mini（65.8%）
* **原生视觉** — 分析图像、图表、文档和屏幕截图
* **Apache 2.0 许可证** — 完全开放用于商业和个人用途
* **高级函数调用** — 原生工具使用并输出 JSON，适合代理式工作流
* **多语言** — 支持 25+ 语言，包括中日韩、阿拉伯语、印地语和欧洲语言

## 要求

| 组件   | 已量化（Q4）          | 全精度（BF16）             |
| ---- | ---------------- | --------------------- |
| GPU  | 1× RTX 4090 24GB | 2× RTX 4090 或 1× H100 |
| 显存   | \~16GB           | \~55GB                |
| 内存   | 32GB             | 64GB                  |
| 磁盘   | 20GB             | 50GB                  |
| CUDA | 11.8+            | 12.0+                 |

**Clore.ai 建议**：RTX 4090（约 $0.5–2/天）用于量化推理 — 最佳性价比

## 使用 Ollama 快速入门

运行 Mistral Small 3.1 的最快方法：

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

# 运行 Mistral Small 3.1（自动下载约 14GB Q4 量化模型）
ollama run mistral-small3.1

# 或指定特定量化
ollama run mistral-small3.1:24b-instruct-2503-q4_K_M
```

### Ollama 作为兼容 OpenAI 的 API

```bash
# 启动 Ollama 服务器
ollama serve &

# 拉取模型
ollama pull mistral-small3.1

# 通过 API 查询
curl http://localhost:11434/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "mistral-small3.1",
    "messages": [
      {"role": "system", "content": "你是一个乐于助人的编码助理。"},
      {"role": "user", "content": "为速率限制编写一个 Python 装饰器"}
    ],
    "temperature": 0.15
  }'
```

### 带视觉能力的 Ollama

```bash
# 发送图像进行分析
curl http://localhost:11434/api/chat -d '{
  "model": "mistral-small3.1",
  "messages": [{
    "role": "user",
    "content": "这张图片显示了什么？",
    "images": ["/path/to/image.jpg"]
  }]
}'
```

## vLLM 设置（用于生产）

针对具有高吞吐量和并发请求的生产工作负载：

```bash
# 安装 vLLM（需要 v0.8.1+）
pip install -U vllm

# 验证已安装 mistral_common（应自动安装）
python -c "import mistral_common; print(mistral_common.__version__)"
```

### 在单 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 \
  --max-model-len 32768 \
  --gpu-memory-utilization 0.90
```

### 带视觉功能的服务（建议 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
```

### 查询服务器

```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": "你是一个乐于助人的助手。今天是 2026-02-20。"},
        {"role": "user", "content": "用 FastAPI 编写一个完整的带 CRUD 操作的博客 REST API"}
    ],
    temperature=0.15,
    max_tokens=4096
)
print(response.choices[0].message.content)
```

## HuggingFace Transformers

用于直接的 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  # 4 位量化 — 可适配 24GB GPU
)

messages = [
    {"role": "system", "content": "你是一个乐于助人的编码助理。"},
    {"role": "user", "content": "在 Python 中实现一个二叉搜索树，包含插入、删除和查找方法"}
]

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))
```

## 函数调用示例

Mistral Small 3.1 是用于工具使用的最佳小型模型之一：

```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": "获取指定股票代码的当前股价",
            "parameters": {
                "type": "object",
                "required": ["ticker"],
                "properties": {
                    "ticker": {"type": "string", "description": "股票代码（例如：AAPL）"}
                }
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "calculate_portfolio_value",
            "description": "根据持仓计算投资组合总价值",
            "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": "当前 AAPL 和 MSFT 的价格是多少？"}],
    tools=tools,
    tool_choice="auto",
    temperature=0.15
)

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

## Docker 快速开始

```bash
# 单 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

# 带视觉支持（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
```

## 给 Clore.ai 用户的提示

* **RTX 4090 是最佳选择**：以 $0.5–2/天 的成本，单块 RTX 4090 可以运行量化后的 Mistral Small 3.1 并有余地。对于通用 LLM，在 Clore.ai 上具有最佳性价比。
* **使用较低温度**：Mistral AI 建议 `temperature=0.15` 用于大多数任务。较高的温度会导致该模型输出不一致。
* **RTX 3090 也可用**：以 $0.3–1/天 的成本，RTX 3090（24GB）可用 Ollama 运行 Q4 量化模型。速度略逊于 4090，但价格约为一半。
* **Ollama 适合快速设置，vLLM 适合生产**：Ollama 可在 60 秒内让你得到可用模型。对于并发 API 请求和更高吞吐量，请切换到 vLLM。
* **函数调用让它与众不同**：许多 24B 模型能进行对话——很少能可靠地调用工具。Mistral Small 3.1 的函数调用可与 GPT-4o Mini 媲美。可以自信地构建代理、API 后端和自动化流水线。

## # 使用固定种子以获得一致结果

| 问题                              | 解决方案                                                                           |
| ------------------------------- | ------------------------------------------------------------------------------ |
| `OutOfMemoryError` 在 RTX 4090 上 | 通过 Ollama 使用量化模型或 `load_in_4bit=True` 在 Transformers 中。全 BF16 需约 55GB。         |
| Ollama 未找到模型                    | 使用 `ollama run mistral-small3.1` （官方库名称）。                                      |
| vLLM 分词器错误                      | 始终传递 `--tokenizer-mode mistral --config-format mistral --load-format mistral`. |
| 输出质量差                           | 设置 `temperature=0.15`。添加系统提示。Mistral Small 对温度较为敏感。                            |
| 视觉在 1 块 GPU 上无法工作               | 视觉功能需要更多显存。使用 `--tensor-parallel-size 2` 或减少 `--max-model-len`.                |
| 函数调用返回为空                        | 添加 `--tool-call-parser mistral --enable-auto-tool-choice` 到 vLLM serve。        |

## 延伸阅读

* [HuggingFace 上的 Mistral Small 3.1](https://huggingface.co/mistralai/Mistral-Small-3.1-24B-Instruct-2503)
* [Mistral AI 博客文章](https://mistral.ai/news/mistral-small-3-1/)
* [Ollama 模型页面](https://ollama.com/library/mistral-small3.1)
* [vLLM 文档](https://docs.vllm.ai/)
* [Mistral Common 库](https://github.com/mistralai/mistral-common)
* [Mistral AI 平台](https://console.mistral.ai/)


---

# Agent Instructions: 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:

```
GET https://docs.clore.ai/guides/guides_v2-zh/yu-yan-mo-xing/mistral-small.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
