Skip to main content
Back

MiniCPM5-15B-A2.5B

MiniCPM Text Series

This page provides the complete specification for MiniCPM5-15B-A2.5B tool calling, including request, parameter, response and error formats, parallel and multi-turn workflows, thinking mode controls and multi-turn thinking retention, serving setup, agent harness integrations, and known limitations / FAQ.

1. Serving & Protocol Support Matrix​

With the latest built-in chat_template.jinja and --tool-call-parser minicpm5, a single SGLang server exposes all three mainstream API protocols simultaneously:

  • OpenAI Chat Completions: POST /v1/chat/completions

  • OpenAI Responses: POST /v1/responses (uses SGLang's MiniCPMToolAdapter, which extends the generic BeamToolAdapter, for Codex type: "namespace" tool flattening/restoration, consecutive commentary assistant turn merging, and lazy tool-loading history items)

  • Anthropic Messages: POST /v1/messages

Single-instance launch command:

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

Gateway requirement for multi-instance Codex deployments: When load-balancing across multiple SGLang workers for Codex (which sends type: "namespace" tools), use SGLang Model Gateway (smg >= 1.15.0) or a transparent reverse proxy (e.g., Nginx / HAProxy). Legacy sglang-router (0.3.x) enforces a strict Rust enum that rejects type: "namespace" with HTTP 400 before forwarding to workers.

1.2 vLLM​

Install vLLM as described in the deployment guide, then select the built-in minicpm5 parser.

vLLM exposes Chat Completions (/v1/chat/completions), Responses (/v1/responses) and Anthropic Messages (/v1/messages). See Agent Harness Integration for Claude Code, Codex and other clients.

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

Deploying MiniCPM5-15B-A2.5B with vLLM requires a vLLM version that supports both the MiniCPM5 MoE model architecture and the latest minicpm5 XML parser (including CDATA whitespace preservation). SGLang is the end-to-end verified recommended backend across all three protocols and Codex.

Reasoning field name: vLLM (0.30.0 and later) returns the reasoning text in message.reasoning (delta.reasoning when streaming), not reasoning_content. The reasoning_content examples in this guide follow SGLang. For other backends, build llama-server from the MiniCPM5 XML parser branch for GGUF tool calling (see the llama.cpp request example); on Apple Silicon, MLX-VLM detects minicpm5 from the chat template.

2. Underlying Prompt & XML Tool Protocol​

MiniCPM5-15B-A2.5B encodes tool schemas, invocations, and observations in an XML per-parameter format via chat_template.jinja:

  1. Tool Definition Injection (System Turn):

    • When tools are provided, the template injects each tool's JSON Schema inside <tools>...</tools> along with tool usage instructions.

    • Custom placement: If the first system message contains <tool_def_sep>, the template replaces <tool_def_sep> with the tool definitions block; otherwise it appends the block to the end of the system message (or creates one if absent).

  2. Tool Invocation Format (Assistant Turn):

    Xml
    <function name="get_weather"><param name="city">Beijing</param><param name="unit">celsius</param></function>
    • Multi-line & Special Character CDATA Wrapping: Parameter values containing <, &, or \n are wrapped in <![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>
    • Non-string Parameters: The latest chat_template.jinja serializes all non-string values (boolean, number, array, object, null) in multi-turn history as valid JSON via tojson(ensure_ascii=False) (and automatically wraps them in CDATA if the serialized string contains <, &, or \n).

    • Parallel Calls: Multiple <function ...></function> blocks may be emitted sequentially in a single assistant turn (newline-separated).

  3. Tool Responses (Tool Role Turn):

    • Consecutive role: "tool" messages are grouped into a single <|im_start|>user turn and wrapped in ordered <tool_response>...</tool_response> tags:

      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. Thinking Mode Control & Multi-Turn Thinking Retention​

Recommended decoding parameters:

  • Thinking ON: temperature=1.0, top_p=0.95, min_p=0.0
  • Thinking OFF: temperature=0.7, top_p=0.8, top_k=20, min_p=0.0, presence_penalty=1.5, repetition_penalty=1

3.1 Default Thinking Mode & How to Disable It​

Thinking mode is enabled by default in the latest chat_template.jinja:

  • When enable_thinking is omitted (or True), the generation prompt ends with <|im_start|>assistant\n<think>\n, instructing the model to think before emitting tool calls or text.

  • When enable_thinking=False, the generation prompt ends with <|im_start|>assistant\n<think>\n\n</think>\n\n, skipping reasoning for faster direct responses or tool calls.

InterfaceDefault BehaviorHow to Disable Thinking
OpenAI Chat CompletionsThinking ON (reasoning_content populated on SGLang; reasoning on vLLM)extra_body={"chat_template_kwargs": {"enable_thinking": False}}
OpenAI ResponsesThinking ON (type: "reasoning" item)reasoning={"effort": "none"}
Anthropic MessagesThinking ON (type: "thinking" block)thinking={"type": "disabled"}
HuggingFace transformersThinking ON (ends with <think>\n)tokenizer.apply_chat_template(..., enable_thinking=False)

3.2 Does chat_template.jinja Drop Prior Thinking in Multi-Turn Conversations? Should Users Pass It Back?​

Verified directly against chat_template.jinja and all three SGLang serving protocols:

  1. The current chat_template.jinja does NOT drop historical thinking:

    • Every historical assistant turn with a non-empty reasoning_content (or embedded <think>...</think> inside content) preserves its <think>...</think> block verbatim, even across multiple subsequent user turns.

    • If a historical assistant message omits reasoning_content (and contains no <think> tags), the template safely inserts an empty <think>\n\n</think>\n\n placeholder without breaking formatting.

  2. How SGLang preserves prior thinking across protocols:

    • OpenAI Chat Completions: Forwards assistant.reasoning_content directly into chat_template.jinja.

    • OpenAI Responses: Reconstructs type: "reasoning" input items into reasoning_content and merges them with the corresponding message / function_call in the same logical turn.

    • Anthropic Messages: Reconstructs type: "thinking" blocks from assistant.content into reasoning_content.

  3. Best practice — should you pass historical thinking back?

    • Multi-step tool calling & agent trajectories (Strongly Recommended: YES):

      • Maintains continuous chain-of-thought across tool steps (preserved/interleaved thinking), preventing redundant calls or lost plans;

      • Keeps the rendered prompt prefix token-identical to previous turns, maximizing Prefix KV Cache (RadixCache) hit rates and reducing TTFT and compute cost.

    • Very long general chat across unrelated user turns (Optional):

      • Keeping prior thinking is still recommended for cache hits; if context length is constrained, you may omit reasoning_content on older turns (the template inserts <think>\n\n</think>\n\n), noting that modifying earlier turns invalidates the KV cache from that turn onward.

4. API Specifications: Request, Parameter, Response & Error Formats​

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

Request & Parameter Format​

  • tools: Standard OpenAI function tool array with JSON Schema parameters (string, integer, number, boolean, array, object, enum, required).

  • tool_choice: Supports "auto", "none", or a specific named function.

  • chat_template_kwargs: Optional object supporting {"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
}'

Disabling Thinking Mode (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 with Codex namespace (/v1/responses)​

SGLang routes MiniCPM5 models (model_type: minicpm5_moe) through MiniCPMToolAdapter, which extends the generic BeamToolAdapter to support both standard type: "function" tools and Codex type: "namespace" tool groups:

  • Ingress flattening: namespace="multi_agent_v1", name="spawn_agent" is flattened to multi_agent_v1__spawn_agent for the model and minicpm5 parser.

  • Egress restoration: Both streaming SSE and non-streaming responses restore {"type": "function_call", "name": "spawn_agent", "namespace": "multi_agent_v1", ...}.

  • Multi-turn compatibility: Preserves namespace on historical function_call items, pairs with function_call_output, merges consecutive commentary assistant turns, and handles Codex lazy tool loading (tool_search_call / tool_search_output).

Request Example (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
}'

Add "reasoning": {"effort": "none"} to disable thinking on /v1/responses.

Response Example​

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

Request Example (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"]
}
}
]
}'

Add "thinking": {"type": "disabled"} to disable thinking on /v1/messages.

Response Example​

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 Error Formats & Parser Fault Tolerance​

(1) Protocol-Level HTTP Error Envelopes​

  • 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 Validation & Recovery Rules (minicpm5)​

ConditionParser Behavior
Unclosed <function> block (e.g., truncated by max_tokens)Falls back to plain text content; no partial tool_calls emitted
Undeclared function name (not present in request tools)Falls back to plain text content; excluded from tool_calls
Missing any required schema parameterLogs a server warning and drops the call
Unknown parameter, duplicate parameter, or <param> missing nameLogs a warning and ignores that parameter; valid parameters are kept
Literal </function> inside <![CDATA[...]]>Respects CDATA boundaries without premature truncation
Non-string value emitted as Python literal (True, ['a'])Parses via json.loads first, falls back to safe_literal_eval, then outputs valid JSON

(3) Returning Client-Side Tool Execution Errors​

When tool execution fails on the client side (e.g., missing file, upstream timeout, permission denied), return a structured error in the tool result turn so the model can recover or report clearly:

  • OpenAI Chat Completions: Return error JSON in role: "tool" content, e.g. {"error": "ServiceUnavailable", "message": "Weather API returned 503"}.

  • OpenAI Responses: Return error text/JSON in function_call_output.output.

  • Anthropic Messages: Set "is_error": true on the tool_result block with the reason in content.

5. Parallel Tool Calling & Complete Multi-Turn Examples (Requests, Responses & Code)​

MiniCPM5-15B-A2.5B supports single-turn parallel multi-tool calling. Client-executed tool results must be returned sequentially in the exact order of tool_calls, and preserving reasoning_content across turns is strongly recommended.

5.1 Complete Multi-Turn Wire Example (OpenAI Chat Completions)​

Turn 1 Request​

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
}

Turn 1 Response (Parallel Tool Calls)​

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\"}"
}
}
]
}
}
]
}

Turn 2 Request (Echoing Full Assistant Turn + Ordered Tool Results)​

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
}

Turn 2 Response (Final Answer)​

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 Runnable Python Multi-Turn Examples​

Example A: OpenAI Chat Completions Multi-Turn Parallel Loop​

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,
})

Example B: OpenAI Responses Multi-Turn namespace Loop​

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)

Example C: Anthropic Python SDK Multi-Turn Loop (Preserving thinking & Filtering Whitespace text Blocks)​

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. Local Usage with HuggingFace transformers​

When calling tokenizer.apply_chat_template() directly without SGLang/vLLM:

  1. Thinking is enabled by default: Omitting enable_thinking appends <|im_start|>assistant\n<think>\n; passing enable_thinking=False appends <|im_start|>assistant\n<think>\n\n</think>\n\n.

  2. Historical thinking is preserved: All prior reasoning_content entries remain rendered inside <think>...</think>.

  3. arguments must be a dict: HuggingFace transformers's Jinja sandbox (ImmutableSandboxedEnvironment) does not provide a fromjson filter, so tool_calls[].function.arguments must be a Python dict. Deserialize OpenAI JSON-string arguments with normalize_messages_for_template() before calling apply_chat_template().

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

When calling model.generate() locally, pass the recommended decoding parameters from Section 3 together with do_sample=True (otherwise temperature / top_p / top_k / min_p are ignored):

  • Thinking ON: do_sample=True, temperature=1.0, top_p=0.95, min_p=0.0
  • Thinking OFF: do_sample=True, temperature=0.7, top_p=0.8, top_k=20, min_p=0.0, repetition_penalty=1

Omit presence_penalty when calling model.generate() locally. Transformers 5.25.0 raises a ValueError if you pass it.

To avoid manually editing JSON / TOML / YAML configuration files across harnesses, we recommend using the open-source desktop manager CC Switch.

All four harnesses below are verified against SGLang deployments:

HarnessProtocol UsedRecommended SetupReload Behavior
Claude CodeAnthropic Messages (/v1/messages)CC Switch Direct (or env vars)Hot-reloads immediately
Codex (CLI / Desktop)OpenAI Responses (/v1/responses)CC Switch Direct (with namespace passthrough)Full restart required after switching
DeepSeek Harness (dsh)OpenAI Chat / Responses / AnthropicCC Switch or in-app Custom Model APIApplies immediately
WorkBuddyOpenAI Chat Completions onlyCC Switch (>= v4.0.31) or in-app Custom ModelSelect model in dropdown

7.1 Quick Setup via CC Switch​

  1. Install the latest CC Switch (v4.0.31+ for WorkBuddy support).

  2. Select the target harness in the sidebar (Claude Code, Codex, DeepSeek Harness, or WorkBuddy).

  3. Click + (Add Provider) → choose Custom → enter your Base URL, API Key (EMPTY for unauthenticated local deployments), and model name (MiniCPM5-15B-A2.5B).

  4. Click Enable / Add. Existing MCP servers, skills, and hooks remain untouched.

7.2 Per-Harness Details & Manual Alternatives​

① Claude Code (Anthropic Messages)​

  • CC Switch: Under Claude Code → Direct, set Base URL to http://<host>:<port> (omit /v1/messages since the Anthropic SDK appends it), API Key to EMPTY, and model tiers to MiniCPM5-15B-A2.5B.

  • Manual CLI:

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

② Codex CLI / Desktop (OpenAI Responses)​

  • Prerequisites: Deploy an SGLang build that includes MiniCPMToolAdapter. For multi-instance load balancing, use smg >= 1.15.0 (not legacy sglang-router 0.3.x).

  • CC Switch: Under Codex → Direct, set Base URL to http://<host>:<port>/v1, API Key to EMPTY, Model to MiniCPM5-15B-A2.5B, then completely quit and reopen Codex (⌘Q on macOS desktop or restart codex in terminal).

  • Manual (~/.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)​

  • Supports openai-completions, openai-responses, and anthropic-messages.

  • In-App Setup: Go to Settings → Models → Add model provider → Custom model API, choose your protocol, enter Base URL (http://<host>:<port>/v1 for OpenAI or http://<host>:<port> for Anthropic), API Key EMPTY, and Model ID MiniCPM5-15B-A2.5B. Also manageable directly via CC Switch.

④ WorkBuddy​

  • WorkBuddy custom models support OpenAI Chat Completions only.

  • Via CC Switch (>= v4.0.31): Select WorkBuddy → add a custom provider with your OpenAI-compatible URL and MiniCPM5-15B-A2.5B → click Add (writes directly to WorkBuddy's models.json).

  • Manual In-App: Open Settings → Models → Custom, enter the full endpoint http://<host>:<port>/v1/chat/completions, API Key, and model name MiniCPM5-15B-A2.5B.

8. Limitations & FAQ​

Q1: Why does tokenizer.apply_chat_template() raise tool_call.arguments must be a dict/mapping, got a string?​

Background (see openbmb/MiniCPM5-2B Discussion #30):

  • Modern XML per-parameter templates (MiniCPM5, Qwen3.5/3.8, GLM-4.7/5) must iterate over key–value pairs to emit <param name="k">v</param>.

  • HuggingFace transformers compiles templates inside Jinja's ImmutableSandboxedEnvironment, which provides tojson but forbids/omits fromjson (json.loads), so pure Jinja cannot deserialize JSON-string arguments into a dict.

  • Resolution:

    • SGLang / vLLM automatically normalize str -> dict before calling the template.

    • For direct local calls to apply_chat_template(), normalize non-empty JSON-string arguments with json.loads() first (see normalize_messages_for_template() in Section 6).

Q2: Are non-string arguments (bool, list, dict, null) still rendered as Python repr?​

No. The latest chat_template.jinja fixes this (Discussion #30 Issue #2) by serializing all non-string arguments via tojson(ensure_ascii=False) (with automatic CDATA wrapping for <, &, and \n), while the minicpm5 parser maintains a dual json.loads → safe_literal_eval fallback for lossless round-trips.

Q3: Why does multi-turn Anthropic /v1/messages return 400: text content blocks must be non-empty?​

When thinking mode is enabled, newlines between </think> and <function> may be surfaced as a whitespace-only {"type": "text", "text": "\n\n"} block. Before echoing assistant.content in the next turn, filter out whitespace-only text blocks while keeping thinking and tool_use blocks intact (see serialize_assistant_blocks() in Section 5.2, Example C).

Q4: Why does Codex fail with HTTP 400: unknown variant 'namespace' in multi-instance setups?​

Legacy sglang-router (0.3.x) rejects type: "namespace" at the gateway layer before requests reach Python workers. Upgrade the gateway to smg >= 1.15.0, use Nginx/HAProxy passthrough, or connect directly to a single worker port during testing.

Q5: The model emitted raw <function ...> XML in content instead of structured tool_calls. Why?​

  1. Verify server flags: SGLang requires --tool-call-parser minicpm5 --reasoning-parser qwen3; vLLM requires --enable-auto-tool-choice --tool-call-parser minicpm5 --reasoning-parser qwen3.

  2. Check max_tokens: Thinking mode consumes output tokens before tool calls. If generation truncates before </function>, the parser safely falls back to plain text. Set max_tokens >= 4096 (or >= 16384 for coding agents).

  3. Check schema validity: Undeclared function names or calls missing required parameters are dropped or returned as plain text.

Q6: What are the current known limitations?​

  • Streaming granularity: To safely handle literal </function> inside CDATA sections, the parser buffers each <function>...</function> block until closing and emits each tool call atomically in streaming mode rather than streaming partial argument JSON token-by-token.

  • Structural tag / grammar constraints: supports_structural_tag() currently returns False.

  • No soft thinking switches: Soft directives like /think or /nothink in user text are not supported; always control thinking via the API or template parameters in Section 3.

Developer Showcase

View all →
MiniCPM Textminicpm-dream: Nightly Memory PassLets a local agent tidy up and file the day's memories every nightMiniCPM Textmateria: Local Lab Result AssistantInterprets lab results locally, with a citation behind every suggestionMiniCPM TextMiniCPM-V MultimodalPaperReview: Handwritten Essay GradingReads and grades handwritten English essays line by line on a MacMiniCPM TextVoxCPM SpeechESP32 Radar Tower: AI ATC CalloutsA round-AMOLED tower radar announcing flights in a cloned ATC voiceMiniCPM TextVoxCPM SpeechESP32-S3 Talking Attitude IndicatorA desk flight instrument that holds voice exchanges with the towerMiniCPM TextClaimLedger: Claim Check LedgerChecks every claim in a report against its source before it shipsMiniCPM TextSelf-Evolving Catgirl: Reasoning via On-Policy Self DistillationNo teacher, no new base model: math reasoning emerges from self-distillationMiniCPM TextReJev: Decision-Model Post-TrainingLoRA post-training MiniCPM5-2B: 51.1% → 80.5% on a sealed holdoutMiniCPM TextBMB Agent: a MiniCPM-powered Personal AssistantLetting a 2B on-device model take over schedules and todos, with real-world lessonsMiniCPM TextMetaCog: Judge-Steered ReasoningAn inference-time loop where a judge scores parallel thought pathsMiniCPM TextOpenClaw Log Assistant: Local Log TriageLocal log analysis with MiniCPM5-2B that separates evidence from hypothesesMiniCPM TextMiniCPM News Desk: Local Daily BriefA local-first daily brief where MiniCPM5-2B picks exact source passagesMiniCPM TextWebGPU Pi: In-Browser Coding AgentMiniCPM5-2B running a coding agent fully in-browser via WebGPUMiniCPM TextMiniCPM5-1B Tool-Use: Offline Function CallsA 1B GGUF function-calling model (SFT + GRPO) that runs offline on CPUMiniCPM Textdeku: A Trustworthy Local Task AgentCode plans, MiniCPM5-1B answers briefly or refusesMiniCPM TextMiniCPM5-1B: LiteRT & Iberian EvalsINT8 LiteRT-LM build plus Spanish, Catalan, Basque and Galician evalsMiniCPM TextMiniCPM-V MultimodalMiniCPM Agent Gateway: Edge-Cloud RoutingLocal MiniCPM classifies each request so sensitive data stays on-deviceMiniCPM TextToneBridge: Context-Aware Mandarin CoachCorrects Mandarin sentences by context and tone, with pinyin and audioMiniCPM TextMiniCPM5-1B FP8: Faster NVIDIA InferenceFP8 vLLM profile hitting 248 decode tok/s on RTX 3060, 1.5× BF16MiniCPM TextAUGURY: Reading Soil Health from WeedsMaps weed species to soil-health indicators; phone-deployable, no cloudMiniCPM Textgmgn-minicpm: Local Crypto Research AgentA read-only GMGN crypto research agent powered by a local 1B modelMiniCPM TextMiniCPM-V MultimodalLost & Found Desk: Small-Model Item ReturnMiniCPM-V captions items, MiniCPM5 guides claims, staff confirm every handoffMiniCPM TextMiniCPM-V MultimodalVoxCPM SpeechCoreAI Model Zoo: MiniCPM on iPhoneCore AI builds of MiniCPM5 and MiniCPM-V 4.6 running natively on iPhone and MacMiniCPM TextMiniCPM-V MultimodalViva Mais: Local WhatsApp CRM CopilotA travel-agency copilot that turns WhatsApp chats into a local-first CRMMiniCPM TextTianwen: BaZi & I-Ching ReflectionA 1B model that turns BaZi and I-Ching readings into self-reflectionMiniCPM TextWanderLust: Mood-Driven Discovery WalksPlans exploratory A-to-B walking routes based on your moodMiniCPM TextNIGHTWAVE: 1970s Radio Hosted by a 1B ModelA 1970s late-night radio with a 1B-model DJ who takes live callsMiniCPM Text6ixPulse: Agentic Toronto Rent MapAgents compare Toronto neighborhoods, citing a source for every claimMiniCPM TextWall Street of AI AgentsFour small-model AI traders roam a pixel office and trade on their ownMiniCPM TextHackathon Advisor: Idea Map & CoachMaps hackathon ideas and coaches you toward more original projectsMiniCPM TextLLM Cinema: AI-Directed ASCII FilmsA small model writes and directs ASCII-art films in the browserMiniCPM Texttiny-llm: A Pure-Rust Inference EngineA from-scratch, CPU-only Rust inference engine for MiniCPM5-1B with a TUIMiniCPM TextDocument Field Agent: Batch OCR & ExtractionA workbench for batch document OCR and structured field extractionMiniCPM TextMiniCPM-V MultimodalWhen a Catgirl Learns to Think, on Your PhoneWas this model made for catgirls? An on-device deployment testMiniCPM TextMiniCPM-V MultimodalMaking a 1B Model a Good Math AgentTeXada’s on-device MiniCPM practice and lessonsMiniCPM TextORG-2: A Workbench for Coding AgentsAn organizational workbench to orchestrate and manage multiple coding agentsMiniCPM TextEdgeHome HarnessA replayable, evaluable local control loop for a 1B on-device model, built in RustMiniCPM TextSqueezing a NAS: Hooking Up WorkBuddyRunning local AI on an N150 CPU: real-world uses and lessons learned

On this page