跳到主要内容
返回

MiniCPM5-15B-A2.5B

MiniCPM 文本系列

本页给出 MiniCPM5-15B-A2.5B 工具调用的完整规范,包括请求、参数、响应与错误格式,并行与多轮调用流程,思考模式控制与多轮思考保留,服务部署,Agent Harness 接入,以及已知限制与常见问题。

1. 服务与协议支持​

1.1 SGLang(推荐)​

使用最新内置的 chat_template.jinja 并加上 --tool-call-parser minicpm5 后,单个 SGLang 服务可同时提供三种主流 API 协议:

  • OpenAI Chat Completions:POST /v1/chat/completions
  • OpenAI Responses:POST /v1/responses(由 SGLang 的 MiniCPMToolAdapter 处理,它扩展了通用的 BeamToolAdapter,负责 Codex type: "namespace" 工具的展平与还原、合并连续的 commentary assistant 轮次,以及处理工具懒加载的历史条目)
  • Anthropic Messages:POST /v1/messages

单实例启动命令:

Bash
python -m sglang.launch_server \
--model-path openbmb/MiniCPM5-15B-A2.5B \
--served-model-name MiniCPM5-15B-A2.5B \
--tool-call-parser minicpm5 \
--reasoning-parser qwen3 \
--host 0.0.0.0 \
--port 8000
多实例部署 Codex 的网关要求

为 Codex(会发送 type: "namespace" 工具)在多个 SGLang worker 间做负载均衡时,请使用 SGLang Model Gateway(smg >= 1.15.0),或 Nginx / HAProxy 等透明反向代理。旧版 sglang-router(0.3.x)使用严格的 Rust 枚举,会在转发到 worker 之前以 HTTP 400 拒绝 type: "namespace"。

1.2 vLLM​

按部署指南安装 vLLM,然后选用内置的 minicpm5 parser。

vLLM 提供 Chat Completions(/v1/chat/completions)、Responses(/v1/responses)和 Anthropic Messages(/v1/messages)。Claude Code、Codex 等客户端的接入方式见 第 7 节「Agent Harness 接入」。

Bash
vllm serve openbmb/MiniCPM5-15B-A2.5B \
--served-model-name MiniCPM5-15B-A2.5B \
--enable-auto-tool-choice \
--tool-call-parser minicpm5 \
--reasoning-parser qwen3 \
--port 8000
  • 使用 vLLM 部署 MiniCPM5-15B-A2.5B,需要同时支持 MiniCPM5 MoE 架构和最新 minicpm5 XML parser(含 CDATA 空白保留)的 vLLM 版本。SGLang 是在三种协议及 Codex 上均经过端到端验证的推荐后端。
  • 思考字段名:vLLM(0.30.0 及以后)在 message.reasoning(流式为 delta.reasoning)中返回思考内容,而不是 reasoning_content。本文中 reasoning_content 的示例以 SGLang 为准。

其他后端:GGUF 工具调用请从 MiniCPM5 XML parser 分支构建 llama-server(参见 llama.cpp 请求示例);在 Apple Silicon 上,MLX-VLM 会根据 chat template 自动识别 minicpm5。

2. 底层 Prompt 与 XML 工具协议​

MiniCPM5-15B-A2.5B 通过 chat_template.jinja,以 XML 逐参数格式 编码工具定义、调用与返回结果:

  1. 工具定义注入(System 轮):

    • 传入 tools 时,模板会把每个工具的 JSON Schema 放进 <tools>...</tools>,并附上工具使用说明。

    • 自定义插入位置:如果第一条 system 消息中包含 <tool_def_sep>,模板会用工具定义块替换它;否则追加到 system 消息末尾(没有 system 消息时会新建一条)。

  2. 工具调用格式(Assistant 轮):

    Xml
    <function name="get_weather"><param name="city">Beijing</param><param name="unit">celsius</param></function>
    • 多行与特殊字符的 CDATA 包裹:参数值包含 <、& 或 \n 时,会用 <![CDATA[...]]> 包裹:

      Xml
      <function name="write_file"><param name="path">/tmp/test.html</param><param name="content"><![CDATA[<h1>A & B</h1>
      <p>Hi</p>]]></param><param name="overwrite">true</param><param name="tags">["web", "demo"]</param></function>
    • 非字符串参数:最新的 chat_template.jinja 会把多轮历史中所有非字符串值(boolean、number、array、object、null)通过 tojson(ensure_ascii=False) 序列化为合法 JSON(若序列化结果包含 <、& 或 \n,会自动用 CDATA 包裹)。

    • 并行调用:同一个 assistant 轮中可以依次输出多个 <function ...></function> 块(以换行分隔)。

  3. 工具返回(Tool 角色轮):

    • 连续的 role: "tool" 消息会合并为一个 <|im_start|>user 轮,并按顺序包裹在 <tool_response>...</tool_response> 中:

      Xml
      <|im_start|>user
      <tool_response>
      {"city": "Beijing", "temperature": 12, "unit": "celsius", "condition": "Sunny"}
      </tool_response>
      <tool_response>
      {"city": "Shanghai", "temperature": 18, "unit": "celsius", "condition": "Sunny"}
      </tool_response><|im_end|>

3. 思考模式控制与多轮思考保留​

推荐采样参数
  • 开启思考:temperature=1.0, top_p=0.95, min_p=0.0
  • 关闭思考:temperature=0.7, top_p=0.8, top_k=20, min_p=0.0, presence_penalty=1.5, repetition_penalty=1

3.1 默认思考模式与关闭方式​

最新的 chat_template.jinja 默认开启思考模式:

  • 不传 enable_thinking(或传 True)时,生成提示以 <|im_start|>assistant\n<think>\n 结尾,模型会先思考,再输出工具调用或文本。
  • 传 enable_thinking=False 时,生成提示以 <|im_start|>assistant\n<think>\n\n</think>\n\n 结尾,跳过推理,直接给出回答或工具调用,速度更快。
接口默认行为关闭思考的方式
OpenAI Chat Completions开启思考(SGLang 填充 reasoning_content;vLLM 为 reasoning)extra_body={"chat_template_kwargs": {"enable_thinking": False}}
OpenAI Responses开启思考(type: "reasoning" 条目)reasoning={"effort": "none"}
Anthropic Messages开启思考(type: "thinking" 块)thinking={"type": "disabled"}
HuggingFace transformers开启思考(以 <think>\n 结尾)tokenizer.apply_chat_template(..., enable_thinking=False)

3.2 多轮对话中模板会丢弃历史思考吗?需要回传吗?​

以下结论已直接对照 chat_template.jinja 和 SGLang 的三种服务协议验证:

  1. 当前 chat_template.jinja 不会丢弃历史思考:

    • 历史 assistant 轮中只要有非空的 reasoning_content(或 content 中内嵌 <think>...</think>),其 <think>...</think> 块都会原样保留,即使之后又有多个 user 轮。
    • 如果历史 assistant 消息没有 reasoning_content(也不含 <think> 标签),模板会插入一个空的 <think>\n\n</think>\n\n 占位,不会破坏格式。
  2. SGLang 在各协议中如何保留历史思考:

    • OpenAI Chat Completions:直接把 assistant.reasoning_content 传入 chat_template.jinja。
    • OpenAI Responses:把 type: "reasoning" 输入条目还原为 reasoning_content,并与同一逻辑轮中的 message / function_call 合并。
    • Anthropic Messages:把 assistant.content 中的 type: "thinking" 块还原为 reasoning_content。
  3. 最佳实践:是否回传历史思考?

    • 多步工具调用与 Agent 轨迹(强烈建议回传):
      • 在多个工具步骤之间保持连贯的思维链(保留 / 交错思考),避免重复调用或丢失计划;
      • 让渲染后的 prompt 前缀与之前轮次逐 token 一致,最大化 Prefix KV Cache(RadixCache)命中率,降低首 token 延迟和计算成本。
    • 跨多个无关 user 轮的超长普通对话(可选):
      • 为了缓存命中,仍建议保留;若上下文长度受限,可以省略较早轮次的 reasoning_content(模板会插入 <think>\n\n</think>\n\n)。注意,修改较早的轮次会使该轮之后的 KV Cache 失效。

4. API 规范:请求、参数、响应与错误格式​

4.1 OpenAI Chat Completions(/v1/chat/completions)​

请求与参数格式​

  • tools:标准 OpenAI function 工具数组,parameters 使用 JSON Schema(string、integer、number、boolean、array、object、enum、required)。
  • tool_choice:支持 "auto"、"none" 或指定函数名。
  • chat_template_kwargs:可选,支持 {"enable_thinking": false}。
Bash
curl -X POST http://localhost:8000/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "MiniCPM5-15B-A2.5B",
"messages": [
{"role": "user", "content": "Check today'\''s weather in Beijing and Shanghai in celsius."}
],
"tools": [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get current weather for a city.",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "City name"},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
},
"required": ["city"]
}
}
}
],
"temperature": 1.0,
"top_p": 0.95,
"max_tokens": 1024
}'

关闭思考模式(Python OpenAI SDK):

Python
from openai import OpenAI

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

tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get current weather for a city.",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "City name"},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
},
"required": ["city"],
},
},
}]

resp = client.chat.completions.create(
model="MiniCPM5-15B-A2.5B",
messages=[{"role": "user", "content": "Check the weather in Beijing in celsius."}],
tools=tools,
temperature=0.7,
top_p=0.8,
presence_penalty=1.5,
extra_body={
"chat_template_kwargs": {"enable_thinking": False},
"top_k": 20,
"min_p": 0.0,
"repetition_penalty": 1,
},
max_tokens=1024,
)
msg = resp.choices[0].message
assert getattr(msg, "reasoning_content", None) is None
print(msg.tool_calls)

4.2 OpenAI Responses 与 Codex namespace(/v1/responses)​

SGLang 会把 MiniCPM5 模型(model_type: minicpm5_moe)交给 MiniCPMToolAdapter 处理。它扩展了通用的 BeamToolAdapter,同时支持标准 type: "function" 工具和 Codex type: "namespace" 工具组:

  • 入口展平:namespace="multi_agent_v1", name="spawn_agent" 会被展平为 multi_agent_v1__spawn_agent,供模型和 minicpm5 parser 使用。
  • 出口还原:流式 SSE 和非流式响应都会还原为 {"type": "function_call", "name": "spawn_agent", "namespace": "multi_agent_v1", ...}。
  • 多轮兼容:保留历史 function_call 条目上的 namespace,与 function_call_output 配对,合并连续的 commentary assistant 轮次,并处理 Codex 工具懒加载(tool_search_call / tool_search_output)。

请求示例(curl)​

Bash
curl -X POST http://localhost:8000/v1/responses \
-H "Content-Type: application/json" \
-d '{
"model": "MiniCPM5-15B-A2.5B",
"input": [
{"role": "user", "content": "Please spawn an agent named worker-1 to inspect README.md."}
],
"tools": [
{
"type": "namespace",
"name": "multi_agent_v1",
"description": "Multi-agent orchestration tools",
"tools": [
{
"type": "function",
"name": "spawn_agent",
"description": "Spawn a sub-agent to run a task",
"parameters": {
"type": "object",
"properties": {
"name": {"type": "string"},
"task": {"type": "string"}
},
"required": ["name", "task"]
}
}
]
}
],
"temperature": 1.0,
"top_p": 0.95,
"max_output_tokens": 1024
}'

在 /v1/responses 上加 "reasoning": {"effort": "none"} 即可关闭思考。

响应示例​

JSON
{
"output": [
{
"id": "rs_8a849f6f7da149699d5c7be5fc62d6a0",
"summary": [],
"type": "reasoning",
"content": [
{
"text": "The user wants me to spawn an agent named \"worker-1\" with a task to inspect README.md. Let me use the multi_agent_v1__spawn_agent tool for this.\n",
"type": "reasoning_text"
}
]
},
{
"id": "fc_a0510372",
"type": "function_call",
"call_id": "call_ee3fb9cecb3c4d5397610a85",
"name": "spawn_agent",
"namespace": "multi_agent_v1",
"arguments": "{\"name\": \"worker-1\", \"task\": \"Inspect README.md\"}",
"status": "completed"
}
]
}

4.3 Anthropic Messages(/v1/messages)​

请求示例(curl)​

Bash
curl -X POST http://localhost:8000/v1/messages \
-H "Content-Type: application/json" \
-H "anthropic-version: 2023-06-01" \
-H "x-api-key: EMPTY" \
-d '{
"model": "MiniCPM5-15B-A2.5B",
"max_tokens": 1024,
"temperature": 1.0,
"top_p": 0.95,
"messages": [
{"role": "user", "content": "Check the weather in Tokyo in celsius."}
],
"tools": [
{
"name": "get_weather",
"description": "Get current weather for a city.",
"input_schema": {
"type": "object",
"properties": {
"city": {"type": "string"},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
},
"required": ["city"]
}
}
]
}'

在 /v1/messages 上加 "thinking": {"type": "disabled"} 即可关闭思考。

响应示例​

JSON
{
"id": "msg_ab7d32d7c60643a4b22a2e0dc61601f4",
"type": "message",
"role": "assistant",
"stop_reason": "tool_use",
"content": [
{
"type": "thinking",
"thinking": "The user wants to check the weather in Tokyo in Celsius. I have the get_weather tool available...\n"
},
{
"type": "tool_use",
"id": "call_28f1e1db9fbe4cad87e1dfb9",
"name": "get_weather",
"input": {
"city": "Tokyo",
"unit": "celsius"
}
}
],
"usage": {
"input_tokens": 249,
"output_tokens": 76
}
}

4.4 错误格式与 Parser 容错​

(1)协议层 HTTP 错误格式​

  • OpenAI Chat Completions 与 Responses(HTTP 400 / 404 / 422 / 500):

    JSON
    {
    "error": {
    "message": "Invalid JSON data: Failed to deserialize the JSON body into the target type: messages: invalid type: string \"not-a-list\", expected a sequence at line 1 column 148",
    "type": "invalid_request_error",
    "param": "messages",
    "code": "invalid_type"
    }
    }
  • Anthropic Messages(HTTP 400 / 401 / 404 / 500):

    JSON
    {
    "type": "error",
    "error": {
    "type": "invalid_request_error",
    "message": "Invalid JSON data: Failed to deserialize the JSON body into the target type: missing field `max_tokens` at line 1 column 172"
    },
    "request_id": "75cc839c-d3e9-4915-ab22-c866784574b7"
    }

(2)Parser 校验与恢复规则(minicpm5)​

情况Parser 行为
<function> 块未闭合(例如被 max_tokens 截断)回退为纯文本 content,不输出不完整的 tool_calls
函数名未在请求的 tools 中声明回退为纯文本 content,不计入 tool_calls
缺少 schema 中任一 required 参数服务端记录警告并丢弃该调用
未知参数、重复参数,或 <param> 缺少 name记录警告并忽略该参数,保留其余合法参数
<![CDATA[...]]> 中出现字面量 </function>遵守 CDATA 边界,不会提前截断
非字符串值以 Python 字面量形式输出(True、['a'])先用 json.loads 解析,失败后回退到 safe_literal_eval,最终输出合法 JSON

(3)回传客户端工具执行错误​

客户端执行工具失败时(例如文件不存在、上游超时、权限不足),请在工具结果轮中返回结构化错误,便于模型恢复或清楚地向用户说明:

  • OpenAI Chat Completions:在 role: "tool" 的 content 中返回错误 JSON,例如 {"error": "ServiceUnavailable", "message": "Weather API returned 503"}。
  • OpenAI Responses:在 function_call_output.output 中返回错误文本或 JSON。
  • Anthropic Messages:在 tool_result 块上设置 "is_error": true,并在 content 中写明原因。

5. 并行工具调用与完整多轮示例​

MiniCPM5-15B-A2.5B 支持单轮并行多工具调用。客户端执行完工具后,必须严格按 tool_calls 的顺序依次回传结果;强烈建议在各轮之间保留 reasoning_content。

5.1 完整多轮交互示例(OpenAI Chat Completions)​

第 1 轮请求​

JSON
{
"model": "MiniCPM5-15B-A2.5B",
"messages": [
{"role": "user", "content": "Check today's weather in Beijing and Shanghai in celsius."}
],
"tools": [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get current weather for a city.",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "City name"},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
},
"required": ["city"]
}
}
}
],
"temperature": 1.0,
"top_p": 0.95,
"max_tokens": 2048
}

第 1 轮响应(并行工具调用)​

JSON
{
"choices": [
{
"index": 0,
"finish_reason": "tool_calls",
"message": {
"role": "assistant",
"content": "",
"reasoning_content": "The user asks for today's weather in Beijing and Shanghai in celsius. I will invoke get_weather twice in parallel with unit='celsius'.",
"tool_calls": [
{
"id": "call_57b2dcc608a841a88d23d72c",
"index": 0,
"type": "function",
"function": {
"name": "get_weather",
"arguments": "{\"city\": \"Beijing\", \"unit\": \"celsius\"}"
}
},
{
"id": "call_895f356fd5f14606820ac75a",
"index": 1,
"type": "function",
"function": {
"name": "get_weather",
"arguments": "{\"city\": \"Shanghai\", \"unit\": \"celsius\"}"
}
}
]
}
}
]
}

第 2 轮请求(回传完整 assistant 轮 + 按序的工具结果)​

JSON
{
"model": "MiniCPM5-15B-A2.5B",
"messages": [
{"role": "user", "content": "Check today's weather in Beijing and Shanghai in celsius."},
{
"role": "assistant",
"content": "",
"reasoning_content": "The user asks for today's weather in Beijing and Shanghai in celsius. I will invoke get_weather twice in parallel with unit='celsius'.",
"tool_calls": [
{
"id": "call_57b2dcc608a841a88d23d72c",
"index": 0,
"type": "function",
"function": {
"name": "get_weather",
"arguments": "{\"city\": \"Beijing\", \"unit\": \"celsius\"}"
}
},
{
"id": "call_895f356fd5f14606820ac75a",
"index": 1,
"type": "function",
"function": {
"name": "get_weather",
"arguments": "{\"city\": \"Shanghai\", \"unit\": \"celsius\"}"
}
}
]
},
{
"role": "tool",
"tool_call_id": "call_57b2dcc608a841a88d23d72c",
"name": "get_weather",
"content": "{\"city\": \"Beijing\", \"temperature\": 12, \"unit\": \"celsius\", \"condition\": \"Sunny\"}"
},
{
"role": "tool",
"tool_call_id": "call_895f356fd5f14606820ac75a",
"name": "get_weather",
"content": "{\"city\": \"Shanghai\", \"temperature\": 18, \"unit\": \"celsius\", \"condition\": \"Sunny\"}"
}
],
"tools": [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get current weather for a city.",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "City name"},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
},
"required": ["city"]
}
}
}
],
"temperature": 1.0,
"top_p": 0.95,
"max_tokens": 2048
}

第 2 轮响应(最终回答)​

JSON
{
"choices": [
{
"index": 0,
"finish_reason": "stop",
"message": {
"role": "assistant",
"reasoning_content": "Both tool calls succeeded: Beijing is 12°C and sunny, Shanghai is 18°C and sunny. I can now present the summary clearly.",
"content": "Here is today's weather (Celsius):\n\n- **Beijing**: 12°C, Sunny\n- **Shanghai**: 18°C, Sunny\n\nBoth cities are sunny today!"
}
}
]
}

5.2 可运行的 Python 多轮示例​

示例 A:OpenAI Chat Completions 多轮并行循环​

Python
import json
from openai import OpenAI

client = OpenAI(base_url="http://localhost:8000/v1", api_key="EMPTY")
MODEL = "MiniCPM5-15B-A2.5B"

tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get current weather for a city.",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "City name"},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
},
"required": ["city"],
},
},
}]

def exec_get_weather(city: str, unit: str = "celsius") -> str:
mock_db = {"Beijing": 12, "Shanghai": 18}
if city not in mock_db:
return json.dumps({"error": f"Unknown city: {city}"})
return json.dumps({"city": city, "temperature": mock_db[city], "unit": unit, "condition": "Sunny"})

messages = [{"role": "user", "content": "Check today's weather in Beijing and Shanghai in celsius."}]

while True:
resp = client.chat.completions.create(
model=MODEL,
messages=messages,
tools=tools,
temperature=1.0,
top_p=0.95,
max_tokens=2048,
)
assistant_msg = resp.choices[0].message

# 1. Preserve full assistant turn including reasoning_content
msg_dict = assistant_msg.model_dump(exclude_none=True)
rc = getattr(assistant_msg, "reasoning_content", None)
if rc is not None:
msg_dict["reasoning_content"] = rc
messages.append(msg_dict)

if not assistant_msg.tool_calls:
print("Final Answer:\n", assistant_msg.content)
break

# 2. Return tool results sequentially in tool_calls order
for tc in assistant_msg.tool_calls:
fn_args = json.loads(tc.function.arguments)
result = exec_get_weather(**fn_args) if tc.function.name == "get_weather" else json.dumps({"error": "unknown tool"})
messages.append({
"role": "tool",
"tool_call_id": tc.id,
"name": tc.function.name,
"content": result,
})

示例 B:OpenAI Responses 多轮 namespace 循环​

Python
import json
from openai import OpenAI

client = OpenAI(base_url="http://localhost:8000/v1", api_key="EMPTY")
MODEL = "MiniCPM5-15B-A2.5B"

tools = [{
"type": "namespace",
"name": "multi_agent_v1",
"description": "Multi-agent orchestration tools",
"tools": [{
"type": "function",
"name": "spawn_agent",
"description": "Spawn a sub-agent to run a task",
"parameters": {
"type": "object",
"properties": {"name": {"type": "string"}, "task": {"type": "string"}},
"required": ["name", "task"],
},
}],
}]

# Turn 1
resp1 = client.responses.create(
model=MODEL,
input=[{"role": "user", "content": "Please spawn an agent named worker-1 to inspect README.md."}],
tools=tools,
temperature=1.0,
top_p=0.95,
max_output_tokens=2048,
)

# Turn 2: echo reasoning, function_call (with namespace), and function_call_output
next_input = [{"role": "user", "content": "Please spawn an agent named worker-1 to inspect README.md."}]
for item in resp1.output:
if item.type == "reasoning":
next_input.append(item.model_dump(exclude_none=True))
elif item.type == "function_call":
fc_dict = {
"type": "function_call",
"call_id": item.call_id,
"name": item.name,
"arguments": item.arguments,
}
ns = getattr(item, "namespace", None)
if ns:
fc_dict["namespace"] = ns
next_input.append(fc_dict)
next_input.append({
"type": "function_call_output",
"call_id": item.call_id,
"output": json.dumps({"status": "done", "summary": "README has 3 sections."}),
})

resp2 = client.responses.create(
model=MODEL,
input=next_input,
tools=tools,
temperature=1.0,
top_p=0.95,
max_output_tokens=2048,
)
print(resp2.output_text)

示例 C:Anthropic Python SDK 多轮循环(保留 thinking 并过滤空白 text 块)​

Python
import json
import anthropic

client = anthropic.Anthropic(base_url="http://localhost:8000", api_key="EMPTY")
MODEL = "MiniCPM5-15B-A2.5B"

tools = [{
"name": "get_weather",
"description": "Get current weather for a city.",
"input_schema": {
"type": "object",
"properties": {
"city": {"type": "string"},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
},
"required": ["city"],
},
}]

def serialize_assistant_blocks(blocks):
"""Preserve thinking and tool_use blocks while skipping whitespace-only text blocks."""
result = []
for b in blocks:
if b.type == "text" and not b.text.strip():
continue
result.append(b.model_dump(exclude_none=True))
return result

# Turn 1
msg1 = client.messages.create(
model=MODEL,
max_tokens=1024,
extra_body={"temperature": 1.0, "top_p": 0.95},
messages=[{"role": "user", "content": "Check the weather in Tokyo in celsius."}],
tools=tools,
)
tool_use_blocks = [b for b in msg1.content if b.type == "tool_use"]

# Turn 2: pass back thinking + tool_use and ordered tool_result
msg2 = client.messages.create(
model=MODEL,
max_tokens=1024,
extra_body={"temperature": 1.0, "top_p": 0.95},
messages=[
{"role": "user", "content": "Check the weather in Tokyo in celsius."},
{"role": "assistant", "content": serialize_assistant_blocks(msg1.content)},
{
"role": "user",
"content": [{
"type": "tool_result",
"tool_use_id": tool_use_blocks[0].id,
"content": json.dumps({"city": "Tokyo", "temperature": 16, "unit": "celsius", "condition": "Cloudy"}),
}],
},
],
tools=tools,
)
for block in msg2.content:
if block.type == "text":
print(block.text)

6. 使用 HuggingFace transformers 本地调用​

不经过 SGLang / vLLM、直接调用 tokenizer.apply_chat_template() 时:

  1. 默认开启思考:不传 enable_thinking 时末尾追加 <|im_start|>assistant\n<think>\n;传 enable_thinking=False 时追加 <|im_start|>assistant\n<think>\n\n</think>\n\n。
  2. 保留历史思考:之前所有的 reasoning_content 都会渲染在 <think>...</think> 中。
  3. arguments 必须是 dict:HuggingFace transformers 的 Jinja 沙箱(ImmutableSandboxedEnvironment)不提供 fromjson 过滤器,因此 tool_calls[].function.arguments 必须是 Python dict。调用 apply_chat_template() 之前,请先用 normalize_messages_for_template() 把 OpenAI 风格的 JSON 字符串 arguments 反序列化。
Python
import copy
import json
from transformers import AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained("openbmb/MiniCPM5-15B-A2.5B")

def normalize_messages_for_template(messages: list[dict]) -> list[dict]:
"""Convert OpenAI-style JSON string arguments to dicts for apply_chat_template."""
normalized = copy.deepcopy(messages)
for msg in normalized:
if msg.get("role") == "assistant" and msg.get("tool_calls"):
for tc in msg["tool_calls"]:
fn = tc.get("function", tc)
args = fn.get("arguments")
if isinstance(args, str):
fn["arguments"] = json.loads(args) if args.strip() else {}
return normalized

tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get weather for a city.",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string"},
"include_hourly": {"type": "boolean"},
},
"required": ["city"],
},
},
}]

messages = [
{"role": "user", "content": "Check Beijing weather without hourly forecast."},
{
"role": "assistant",
"reasoning_content": "Turn 1 thought: call get_weather for Beijing.",
"content": "",
"tool_calls": [{
"id": "call_1",
"type": "function",
"function": {
"name": "get_weather",
"arguments": '{"city": "Beijing", "include_hourly": false}',
},
}],
},
{"role": "tool", "tool_call_id": "call_1", "content": '{"city": "Beijing", "temp": 12}'},
{
"role": "assistant",
"reasoning_content": "Turn 2 thought: Beijing is 12°C, reply clearly.",
"content": "Beijing is 12°C today.",
},
{"role": "user", "content": "What about Shanghai?"},
]

# 1. Default (thinking enabled; verifies multi-turn thinking retention & JSON bool rendering)
prompt_think = tokenizer.apply_chat_template(
normalize_messages_for_template(messages),
tools=tools,
tokenize=False,
add_generation_prompt=True,
)
assert "Turn 1 thought: call get_weather for Beijing." in prompt_think
assert "Turn 2 thought: Beijing is 12°C, reply clearly." in prompt_think
assert '<param name="include_hourly">false</param>' in prompt_think
assert prompt_think.endswith("<|im_start|>assistant\n<think>\n")

# 2. Thinking disabled
prompt_no_think = tokenizer.apply_chat_template(
normalize_messages_for_template(messages),
tools=tools,
tokenize=False,
add_generation_prompt=True,
enable_thinking=False,
)
assert prompt_no_think.endswith("<|im_start|>assistant\n<think>\n\n</think>\n\n")

本地调用 model.generate() 时,请在第 3 节推荐采样参数的基础上传入 do_sample=True(否则 temperature / top_p / top_k / min_p 不会生效):

  • 开启思考:do_sample=True, temperature=1.0, top_p=0.95, min_p=0.0
  • 关闭思考:do_sample=True, temperature=0.7, top_p=0.8, top_k=20, min_p=0.0, repetition_penalty=1

本地调用 model.generate() 时不要传 presence_penalty,Transformers 5.25.0 会因此抛出 ValueError。

7. Agent Harness 接入(推荐 CC Switch)​

为避免在各个 Harness 之间手动修改 JSON / TOML / YAML 配置文件,推荐使用开源桌面管理工具 CC Switch。

以下四个 Harness 均已在 SGLang 部署上验证:

Harness使用的协议推荐配置方式生效方式
Claude CodeAnthropic Messages(/v1/messages)CC Switch Direct(或环境变量)立即热加载
Codex(CLI / Desktop)OpenAI Responses(/v1/responses)CC Switch Direct(透传 namespace)切换后需完全重启
DeepSeek Harness(dsh)OpenAI Chat / Responses / AnthropicCC Switch 或应用内 Custom Model API立即生效
WorkBuddy仅 OpenAI Chat CompletionsCC Switch(>= v4.0.31)或应用内自定义模型在下拉框中选择模型

7.1 通过 CC Switch 快速配置​

  1. 安装最新版 CC Switch(支持 WorkBuddy 需 v4.0.31+)。
  2. 在侧边栏选择目标 Harness(Claude Code、Codex、DeepSeek Harness 或 WorkBuddy)。
  3. 点击 +(Add Provider) → 选择 Custom → 填写 Base URL、API Key(本地无鉴权部署填 EMPTY)和模型名(MiniCPM5-15B-A2.5B)。
  4. 点击 Enable / Add。已有的 MCP 服务、Skills 和 Hooks 不受影响。

7.2 各 Harness 详细说明与手动配置​

① Claude Code(Anthropic Messages)​

  • CC Switch:在 Claude Code → Direct 中,Base URL 设为 http://<host>:<port>(不要带 /v1/messages,Anthropic SDK 会自动拼接),API Key 设为 EMPTY,各模型档位都设为 MiniCPM5-15B-A2.5B。

  • 手动命令行:

    Bash
    export ANTHROPIC_BASE_URL="http://<host>:<port>"
    export ANTHROPIC_API_KEY="EMPTY"
    claude --model MiniCPM5-15B-A2.5B

② Codex CLI / Desktop(OpenAI Responses)​

  • 前置条件:部署包含 MiniCPMToolAdapter 的 SGLang 版本。多实例负载均衡请使用 smg >= 1.15.0(不要使用旧版 sglang-router 0.3.x)。

  • CC Switch:在 Codex → Direct 中,Base URL 设为 http://<host>:<port>/v1,API Key 设为 EMPTY,Model 设为 MiniCPM5-15B-A2.5B,然后完全退出并重新打开 Codex(macOS 桌面版按 ⌘Q,终端中重启 codex)。

  • 手动配置(~/.codex/config.toml):

    Toml
    model = "MiniCPM5-15B-A2.5B"
    model_provider = "minicpm5"

    [model_providers.minicpm5]
    name = "MiniCPM5 Local"
    base_url = "http://<host>:<port>/v1"
    wire_api = "responses"
    env_key = "MINICPM_API_KEY"

③ DeepSeek Harness(dsh)​

  • 支持 openai-completions、openai-responses 和 anthropic-messages。
  • 应用内配置:进入 Settings → Models → Add model provider → Custom model API,选择协议,填写 Base URL(OpenAI 协议为 http://<host>:<port>/v1,Anthropic 协议为 http://<host>:<port>)、API Key EMPTY 和 Model ID MiniCPM5-15B-A2.5B。也可以直接通过 CC Switch 管理。

④ WorkBuddy​

  • WorkBuddy 自定义模型仅支持 OpenAI Chat Completions。
  • 通过 CC Switch(>= v4.0.31):选择 WorkBuddy → 添加自定义 Provider,填写 OpenAI 兼容地址和 MiniCPM5-15B-A2.5B → 点击 Add(会直接写入 WorkBuddy 的 models.json)。
  • 应用内手动配置:打开 Settings → Models → Custom,填写完整端点 http://<host>:<port>/v1/chat/completions、API Key 和模型名 MiniCPM5-15B-A2.5B。

8. 限制与常见问题​

Q1:为什么 tokenizer.apply_chat_template() 报错 tool_call.arguments must be a dict/mapping, got a string?​

背景(参见 openbmb/MiniCPM5-2B Discussion #30):

  • 现代 XML 逐参数模板(MiniCPM5、Qwen3.5/3.8、GLM-4.7/5)需要遍历键值对来输出 <param name="k">v</param>。
  • HuggingFace transformers 在 Jinja 的 ImmutableSandboxedEnvironment 中编译模板,它提供 tojson,但不提供 fromjson(json.loads),因此纯 Jinja 无法把 JSON 字符串形式的 arguments 反序列化为 dict。
  • 解决方法:
    • SGLang / vLLM 会在调用模板前自动完成 str -> dict 转换。
    • 本地直接调用 apply_chat_template() 时,先用 json.loads() 处理非空的 JSON 字符串 arguments(参见第 6 节的 normalize_messages_for_template())。

Q2:非字符串参数(bool、list、dict、null)还会被渲染成 Python repr 吗?​

不会。最新的 chat_template.jinja 已修复该问题(Discussion #30 Issue #2),所有非字符串参数都通过 tojson(ensure_ascii=False) 序列化(遇到 <、&、\n 自动用 CDATA 包裹);minicpm5 parser 则保留 json.loads → safe_literal_eval 双重回退,保证往返无损。

Q3:为什么多轮 Anthropic /v1/messages 返回 400: text content blocks must be non-empty?​

开启思考模式时,</think> 与 <function> 之间的换行可能会作为仅含空白的 {"type": "text", "text": "\n\n"} 块返回。下一轮回传 assistant.content 前,请过滤掉仅含空白的 text 块,同时保留 thinking 和 tool_use 块(参见第 5.2 节示例 C 中的 serialize_assistant_blocks())。

Q4:多实例部署下 Codex 为什么报 HTTP 400: unknown variant 'namespace'?​

旧版 sglang-router(0.3.x)会在请求到达 Python worker 之前,在网关层拒绝 type: "namespace"。请把网关升级到 smg >= 1.15.0,或使用 Nginx / HAProxy 透传;测试时也可以直接连接单个 worker 端口。

Q5:模型在 content 中输出了原始 <function ...> XML,而不是结构化的 tool_calls,为什么?​

  1. 检查服务启动参数:SGLang 需要 --tool-call-parser minicpm5 --reasoning-parser qwen3;vLLM 需要 --enable-auto-tool-choice --tool-call-parser minicpm5 --reasoning-parser qwen3。
  2. 检查 max_tokens:思考模式会在工具调用之前消耗输出 token。若生成在 </function> 之前被截断,parser 会安全地回退为纯文本。请设置 max_tokens >= 4096(Coding Agent 建议 >= 16384)。
  3. 检查 schema 是否有效:未声明的函数名,或缺少 required 参数的调用,会被丢弃或作为纯文本返回。

Q6:目前有哪些已知限制?​

  • 流式粒度:为了正确处理 CDATA 中的字面量 </function>,parser 会缓冲每个 <function>...</function> 块直到闭合,流式模式下以完整的工具调用为单位输出,而不是逐 token 流式输出参数 JSON。
  • 结构化标签 / 语法约束:supports_structural_tag() 目前返回 False。
  • 不支持软开关:不支持在用户文本中使用 /think、/nothink 等软指令;请始终通过第 3 节中的 API 或模板参数控制思考模式。

开发者精选

查看全部 →
MiniCPM 文本minicpm-dream:夜间记忆整理让本地 Agent 每晚把白天的记忆整理归档一遍MiniCPM 文本materia:本地化验解读助手解读化验单,每条建议都附上可追溯的出处MiniCPM 文本MiniCPM-V 多模态PaperReview 手写作文批改在 Mac 本地逐行识别并批改英语手写作文MiniCPM 文本VoxCPM 语音ESP32 塔台雷达:AI 语音播报航班圆屏塔台雷达,用克隆管制员音色播报航班MiniCPM 文本VoxCPM 语音ESP32-S3 会说话的姿态仪桌面飞机仪表,能用语音和"塔台"来回对话MiniCPM 文本ClaimLedger:报告结论核对台账报告交付前,把每条结论带回原件逐条核一遍MiniCPM 文本猫娘大模型的自进化:OPSD 涌现推理能力不请教师、不换底座,让猫娘在自我蒸馏中涌现数学推理MiniCPM 文本ReJev:轻量决策模型后训练LoRA 后训练 MiniCPM5-2B,留出集准确率 51.1% → 80.5%MiniCPM 文本BMB Agent:由 MiniCPM 驱动的个人助手让 2B 端侧模型接管日程与待办,.funcall 协议实战与踩坑记录MiniCPM 文本MetaCog:小裁判引导推理推理时元认知循环,多路径打分择优作答MiniCPM 文本OpenClaw 日志助手:本地日志故障初筛用 MiniCPM5-2B 在本地分析日志,分清已确认证据和可能原因MiniCPM 文本MiniCPM News Desk:本地新闻简报本地小模型挑选原文段落,生成每日新闻汇总MiniCPM 文本WebGPU Pi:浏览器本地编程 AgentMiniCPM5-2B 经 WebGPU 在浏览器本地运行的编程 AgentMiniCPM 文本MiniCPM5-1B Tool-Use:离线函数调用SFT + GRPO 的 1B 函数调用模型,CPU 离线运行MiniCPM 文本deku:本地可信任务助手代码负责规划、模型只做简短补全的本地问答 AgentMiniCPM 文本MiniCPM5-1B:端侧部署与多语评测INT8 LiteRT-LM 端侧包,附西语等四种语言评测MiniCPM 文本MiniCPM-V 多模态MiniCPM Agent Gateway:端云协同网关本地 MiniCPM 判断数据策略,敏感请求不出本机MiniCPM 文本ToneBridge:情境化中文纠错按场景语气小幅修改中文句子,附拼音与发音MiniCPM 文本MiniCPM5-1B FP8:GPU 推理加速RTX 3060 解码 248 tok/s,比 BF16 快 1.5 倍MiniCPM 文本AUGURY:从杂草读懂土壤通过杂草物种推断土壤状况,可在手机端运行MiniCPM 文本gmgn-minicpm:本地链上研究 Agent1B 模型本地驱动的只读 GMGN 链上研究助手MiniCPM 文本MiniCPM-V 多模态Lost & Found Desk:小模型失物招领MiniCPM-V 描述物品、MiniCPM5 引导问询,人工确认归还MiniCPM 文本MiniCPM-V 多模态VoxCPM 语音CoreAI Model Zoo:MiniCPM 原生上 iPhoneMiniCPM5、MiniCPM-V 4.6 转换为 Core AI 原生运行MiniCPM 文本MiniCPM-V 多模态Viva Mais:WhatsApp 本地 CRM把旅行社的 WhatsApp 聊天整理成本地 CRMMiniCPM 文本天问:1B 模型解八字周易用 1B 模型把八字与周易变成自我反思MiniCPM 文本WanderLust:按心情规划步行按心情规划从 A 到 B 的探索式步行路线MiniCPM 文本NIGHTWAVE:1B 模型深夜电台由 1B 模型主持、可现场来电的复古电台MiniCPM 文本6ixPulse:多伦多租房地图多智能体比较多伦多街区,结论都标注数据来源MiniCPM 文本华尔街 AI:小模型交易公司四个小模型智能体在像素办公室里自主炒股MiniCPM 文本Hackathon Advisor:选题地图顾问用创意地图评估黑客松选题的原创性MiniCPM 文本LLM Cinema:AI 导演 ASCII 电影小模型自编自导 ASCII 动画短片MiniCPM 文本tiny-llm:纯 Rust 推理引擎纯 Rust 手写、仅用 CPU 的 MiniCPM5-1B 推理引擎MiniCPM 文本Document Field Agent:文档字段抽取批量文档 OCR 与结构化字段抽取工作台MiniCPM 文本MiniCPM-V 多模态当猫娘学会思考,手机也能部署这个模型难道真的是为了猫娘而生的吗?端侧部署实测MiniCPM 文本MiniCPM-V 多模态让 1B 小模型当好数学 AgentTeXada 的 MiniCPM 端侧实践与方法沉淀MiniCPM 文本ORG-2:Coding Agent 工作台统一编排与管理多个编程 Agent 的组织工作台MiniCPM 文本EdgeHome Harness用 Rust 为 1B 端侧小模型构建可回放、可评测的本地控制链路MiniCPM 文本榨干 NAS!接入 WorkBuddyN150 CPU 跑本地 AI,分享一些真实用法和踩坑经验