> 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-zh/yu-yan-mo-xing/mistral-small.md).

# Mistral Small 3.1

在 Clore.ai 上部署 Mistral Small 3.1（24B）——理想的单 GPU 生产级模型

Mistral Small 3.1，由 Mistral AI 于 2025 年 3 月发布，是一款 **240 亿参数的稠密模型** 其性能远超同级。拥有 128K 上下文窗口、原生视觉能力、一流的函数调用能力，以及 **Apache 2.0 许可证**，它可以说是你能在单张 RTX 4090 上运行的最佳模型。在大多数基准测试中，它的表现优于 GPT-4o Mini 和 Claude 3.5 Haiku，而且量化后在消费级硬件上也能轻松运行。

## 主要特性

* **240亿稠密参数** —— 无 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 | 12.8+            | 12.8+                 |

**Clore.ai 推荐**: RTX 4090（$0.14–0.42/小时）适用于量化推理——最佳性价比

## 使用 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
```

### 作为 OpenAI 兼容 API 的 Ollama

```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 编写一个完整的 REST API，为博客实现 CRUD 操作"}
    ],
    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"调用：{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.14–0.42/小时 的价格，单张 RTX 4090 就能运行量化版 Mistral Small 3.1，而且还有余量。对于通用 LLM 来说，这是 Clore.ai 上最佳的成本/性能比。
* **使用低温度**：Mistral AI 建议 `temperature=0.15` 用于大多数任务。更高的温度会导致该模型输出不稳定。
* **RTX 3090 也可以**：以 $0.07–0.21/小时 的价格，RTX 3090（24GB）也能很好地运行 Q4 量化版和 Ollama。比 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
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-zh/yu-yan-mo-xing/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.
