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
1.1 SGLang (Recommended)
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'sMiniCPMToolAdapter, which extends the genericBeamToolAdapter, for Codextype: "namespace"tool flattening/restoration, consecutivecommentaryassistant turn merging, and lazy tool-loading history items) -
Anthropic Messages:
POST /v1/messages
Single-instance launch command:
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). Legacysglang-router(0.3.x) enforces a strict Rust enum that rejectstype: "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.
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.5Bwith vLLM requires a vLLM version that supports both the MiniCPM5 MoE model architecture and the latestminicpm5XML 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.reasoningwhen streaming), notreasoning_content. Thereasoning_contentexamples in this guide follow SGLang. For other backends, buildllama-serverfrom the MiniCPM5 XML parser branch for GGUF tool calling (see the llama.cpp request example); on Apple Silicon, MLX-VLM detectsminicpm5from 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:
-
Tool Definition Injection (System Turn):
-
When
toolsare provided, the template injects each tool's JSON Schema inside<tools>...</tools>along with tool usage instructions. -
Custom placement: If the first
systemmessage contains<tool_def_sep>, the template replaces<tool_def_sep>with the tool definitions block; otherwise it appends the block to the end of thesystemmessage (or creates one if absent).
-
-
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\nare 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.jinjaserializes all non-string values (boolean,number,array,object,null) in multi-turn history as valid JSON viatojson(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).
-
-
Tool Responses (Tool Role Turn):
-
Consecutive
role: "tool"messages are grouped into a single<|im_start|>userturn 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_thinkingis omitted (orTrue), 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.
| Interface | Default Behavior | How to Disable Thinking |
|---|---|---|
| OpenAI Chat Completions | Thinking ON (reasoning_content populated on SGLang; reasoning on vLLM) | extra_body={"chat_template_kwargs": {"enable_thinking": False}} |
| OpenAI Responses | Thinking ON (type: "reasoning" item) | reasoning={"effort": "none"} |
| Anthropic Messages | Thinking ON (type: "thinking" block) | thinking={"type": "disabled"} |
HuggingFace transformers | Thinking 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:
-
The current
chat_template.jinjadoes NOT drop historical thinking:-
Every historical
assistantturn with a non-emptyreasoning_content(or embedded<think>...</think>insidecontent) preserves its<think>...</think>block verbatim, even across multiple subsequentuserturns. -
If a historical
assistantmessage omitsreasoning_content(and contains no<think>tags), the template safely inserts an empty<think>\n\n</think>\n\nplaceholder without breaking formatting.
-
-
How SGLang preserves prior thinking across protocols:
-
OpenAI Chat Completions: Forwards
assistant.reasoning_contentdirectly intochat_template.jinja. -
OpenAI Responses: Reconstructs
type: "reasoning"input items intoreasoning_contentand merges them with the correspondingmessage/function_callin the same logical turn. -
Anthropic Messages: Reconstructs
type: "thinking"blocks fromassistant.contentintoreasoning_content.
-
-
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_contenton older turns (the template inserts<think>\n\n</think>\n\n), noting that modifying earlier turns invalidates the KV cache from that turn onward.
- Keeping prior thinking is still recommended for cache hits; if context length is constrained, you may omit
-
4. API Specifications: Request, Parameter, Response & Error Formats
4.1 OpenAI Chat Completions (/v1/chat/completions)
Request & Parameter Format
-
tools: Standard OpenAIfunctiontool array with JSON Schemaparameters(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}.
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):
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 tomulti_agent_v1__spawn_agentfor the model andminicpm5parser. -
Egress restoration: Both streaming SSE and non-streaming responses restore
{"type": "function_call", "name": "spawn_agent", "namespace": "multi_agent_v1", ...}. -
Multi-turn compatibility: Preserves
namespaceon historicalfunction_callitems, pairs withfunction_call_output, merges consecutivecommentaryassistant turns, and handles Codex lazy tool loading (tool_search_call/tool_search_output).
Request Example (curl)
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
{
"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)
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
{
"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)
| Condition | Parser 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 parameter | Logs a server warning and drops the call |
Unknown parameter, duplicate parameter, or <param> missing name | Logs 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": trueon thetool_resultblock with the reason incontent.
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
{
"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)
{
"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)
{
"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)
{
"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
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
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)
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:
-
Thinking is enabled by default: Omitting
enable_thinkingappends<|im_start|>assistant\n<think>\n; passingenable_thinking=Falseappends<|im_start|>assistant\n<think>\n\n</think>\n\n. -
Historical thinking is preserved: All prior
reasoning_contententries remain rendered inside<think>...</think>. -
argumentsmust be adict: HuggingFacetransformers's Jinja sandbox (ImmutableSandboxedEnvironment) does not provide afromjsonfilter, sotool_calls[].function.argumentsmust be a Pythondict. Deserialize OpenAI JSON-stringargumentswithnormalize_messages_for_template()before callingapply_chat_template().
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 withdo_sample=True(otherwisetemperature/top_p/top_k/min_pare 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=1Omit
presence_penaltywhen callingmodel.generate()locally. Transformers 5.25.0 raises aValueErrorif you pass it.
7. Agent Harness Integration (Recommended: CC Switch)
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:
| Harness | Protocol Used | Recommended Setup | Reload Behavior |
|---|---|---|---|
| Claude Code | Anthropic 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 / Anthropic | CC Switch or in-app Custom Model API | Applies immediately |
| WorkBuddy | OpenAI Chat Completions only | CC Switch (>= v4.0.31) or in-app Custom Model | Select model in dropdown |
7.1 Quick Setup via CC Switch
-
Install the latest CC Switch (
v4.0.31+for WorkBuddy support). -
Select the target harness in the sidebar (Claude Code, Codex, DeepSeek Harness, or WorkBuddy).
-
Click
+(Add Provider) → choose Custom → enter your Base URL, API Key (EMPTYfor unauthenticated local deployments), and model name (MiniCPM5-15B-A2.5B). -
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 tohttp://<host>:<port>(omit/v1/messagessince the Anthropic SDK appends it), API Key toEMPTY, and model tiers toMiniCPM5-15B-A2.5B. -
Manual CLI:
Bashexport 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, usesmg >= 1.15.0(not legacysglang-router 0.3.x). -
CC Switch: Under
Codex→ Direct, set Base URL tohttp://<host>:<port>/v1, API Key toEMPTY, Model toMiniCPM5-15B-A2.5B, then completely quit and reopen Codex (⌘Qon macOS desktop or restartcodexin terminal). -
Manual (
~/.codex/config.toml):Tomlmodel = "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, andanthropic-messages. -
In-App Setup: Go to Settings → Models → Add model provider → Custom model API, choose your protocol, enter Base URL (
http://<host>:<port>/v1for OpenAI orhttp://<host>:<port>for Anthropic), API KeyEMPTY, and Model IDMiniCPM5-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 andMiniCPM5-15B-A2.5B→ click Add (writes directly to WorkBuddy'smodels.json). -
Manual In-App: Open Settings → Models → Custom, enter the full endpoint
http://<host>:<port>/v1/chat/completions, API Key, and model nameMiniCPM5-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
transformerscompiles templates inside Jinja'sImmutableSandboxedEnvironment, which providestojsonbut forbids/omitsfromjson(json.loads), so pure Jinja cannot deserialize JSON-stringargumentsinto a dict. -
Resolution:
-
SGLang / vLLM automatically normalize
str -> dictbefore calling the template. -
For direct local calls to
apply_chat_template(), normalize non-empty JSON-stringargumentswithjson.loads()first (seenormalize_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?
-
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. -
Check
max_tokens: Thinking mode consumes output tokens before tool calls. If generation truncates before</function>, the parser safely falls back to plain text. Setmax_tokens >= 4096(or>= 16384for coding agents). -
Check schema validity: Undeclared function names or calls missing
requiredparameters 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 returnsFalse. -
No soft thinking switches: Soft directives like
/thinkor/nothinkin user text are not supported; always control thinking via the API or template parameters in Section 3.