Pidoku

Tool Calling and Reasoning

Module 18 Lesson 18.i 40 min Difficulty 3/5

Prerequisites 16.e, 16.f, 18.e


Before you start: words you need#

WordPlain meaning
Tool callingThe model asks the client to run a function (search, a database query, …) by emitting a structured call instead of a plain answer.
Reasoning modelA model that writes out its thinking before its answer, usually between markers such as <think> and </think>.
Chat templateA small Jinja program shipped with the model that turns messages and tools into the exact prompt text the model was trained on.
ParserCode that reads the model’s output text and splits it into reasoning, content and tool calls.
tool_choiceThe request field that says whether the model may, must or must not call a tool.
Structural tagA grammar that constrains only part of the output (for example, everything between <tool_call> and </tool_call>), leaving the rest free.
StreamingSending the response piece by piece as tokens are generated.

1. What is it?#

The OpenAI chat API returns three separate things: content, reasoning and tool_calls. A language model returns one thing: a stream of tokens. The model was trained to mark the parts itself (its thinking between special tags, its tool calls in some agreed syntax), and every model family chose different markers.

So tool calling and reasoning in vLLM are mostly a text-processing feature in the API server: the chat template writes the tool definitions into the prompt in the model’s format, and a per-family parser splits the output back into the three fields. The engine core is involved only when the output must be constrained, through structured output (18.e).

vLLM v0.32.0 has 57 tool-parser files and 40 reasoning-parser files, and is moving both onto one unified Parser per model family. Facts checked on 12 November 2026.


2. Why does it matter?#

  • Agents run on it. Every agent framework depends on tool calls being extracted reliably, streamed correctly and, ideally, schema-valid.
  • Silent failures. The wrong parser does not raise an error; tool calls simply appear as raw text in content.
  • Token budgets. Tool definitions and reasoning both cost tokens; misjudging them gives empty answers and high bills.

3. Simple analogy#

A translator sits between an interpreter (the model) who speaks in a private shorthand and a client who wants a typed report with three boxes: “thoughts”, “answer”, “actions”. Before the meeting, the translator writes the client’s list of possible actions in the interpreter’s shorthand (the chat template). During the meeting, the translator listens and sorts each phrase into a box (the parser), sometimes waiting a moment because a half-heard word could start an “action”. If the client insists on an action, the translator can make the interpreter fill in a form instead of speaking freely (structured output).


4. Tiny example#

model output   <think>The user wants weather.</think>Let me check.<tool_call>{"name":
               "get_weather", "arguments": {"city": "Pune"}}</tool_call>

response       reasoning   "The user wants weather."
               content     "Let me check."
               tool_calls  [{name: get_weather, arguments: {"city": "Pune"}}]
               finish_reason "tool_calls"

5. Technical explanation#

The way in: tools are prompt text#

A request’s tools array is a list of JSON schemas. There is no separate channel into the model. The renderer (16.e) passes it to the chat template, which writes it into the prompt in whatever layout this model was trained on. Two consequences:

  • Tool definitions cost tokens on every request. Twenty detailed tools can be several thousand tokens. They are identical across requests, so keep their order stable and put them where the prefix cache (17.f) can absorb them.
  • The right template is essential. A model whose template ignores tools will never call one. Some models need a template from vLLM’s examples/ directory, passed with --chat-template.

By default tools are rendered even when tool_choice is "none"; --exclude-tools-when-tool-choice-none drops them.

The way out: tool_choice decides the mechanism#

Shell
vllm serve meta-llama/Llama-3.1-8B-Instruct \
    --enable-auto-tool-choice \
    --tool-call-parser llama3_json \
    --chat-template examples/tool_chat_template_llama3.1_json.jinja
tool_choiceMeaningHow vLLM produces the call (v0.32.0)
"none"Never call a toolPlain content
"auto"The model decidesThe model writes a call in its own syntax; the parser finds it. Needs --enable-auto-tool-choice and --tool-call-parser. If any tool sets strict: true, or the server sets a strictness floor, a structural tag constrains the call.
"required"At least one callConstrained: a structural tag (for parsers that support one) or a JSON-schema grammar forces calls matching the tools
{"type": "function", "function": {"name": "f"}}Must call fConstrained to f

Strict tool calling#

v0.32.0 separates two layers of constraint, both built from structural tags (vllm/tool_parsers/structural_tag_registry.py) and run through the structured-output backend:

  • The envelope: the call markup and the function name. Always constrained for required and named calls; for auto, only when some tool is strict or the server raises the floor.
  • The argument schema of one tool: pinned only when that tool sets strict: true, or under --tool-strict-level parameter.
--tool-strict-levelEffect
auto (default)Follow the request: required/named activate structural tags; auto does so when a tool is strict
functionConstrain the envelope for every request with tools; arguments stay free unless strict
parameterAlso pin every tool’s argument schema, as if every tool were strict: true

The documentation’s reason for the floor: “Most OpenAI-compatible clients and agent frameworks never set strict on their tools, so with tool_choice="auto" the model generates tool calls without any grammar and malformed markup can leak into the response.” With auto the grammar still does not force a call; a plain answer stays valid. VLLM_ENFORCE_STRICT_TOOL_CALLING=false turns structural tags off entirely.

Parsers#

A tool parser handles one output syntax: hermes, llama3_json, mistral, pythonic, qwen3_coder, openai (gpt-oss Harmony), deepseek_v3, kimi_k2, and dozens more. Each has two jobs:

JobUsed forDifficulty
Extract from complete textNon-streaming responsesEasy: the whole output is there
Extract from a streamStreaming responsesHard: decide, token by token, whether text is content, the start of a marker, or part of a call

The streaming problem is the stop-string problem from 16.f with more state. If the output so far ends in <tool, the parser cannot emit it as content (it may start <tool_call>) and cannot treat it as a call yet. It holds the text back until the next token settles the question.

In v0.32.0 new parsers are written once, in vllm/parser/, as a unified Parser that does reasoning and tool extraction together. Most subclass a declarative ParserEngine: a set of terminals, transitions and content events, with special tokens matched as token IDs rather than text. The older ToolParser and ReasoningParser classes are kept as thin adapters so that --tool-call-parser names and out-of-tree plugins keep working. An hf parser reads the tokenizer’s response_template metadata instead of model-specific code (it supports parsing, not constrained decoding).

The wrong parser is the most common tool-calling failure. The symptom is content holding raw <tool_call>{...} text and an empty tool_calls: the model did its part and nobody translated it. parallel_tool_calls: false asks for at most one call per response.

Reasoning parsers#

--reasoning-parser <name> moves the thinking into a separate field:

JSON
{"message": {"role": "assistant",
             "reasoning": "The user wants the weather, so…",
             "content": "It is 31 °C in Pune."}}

warning

The field is called reasoning. Older versions called it reasoning_content. The documentation warns that a client still reading the old name “could silently read an empty reasoning_content, even when reasoning is populated.”

Three details cause surprises:

  • Reasoning counts as output. It uses max_tokens and is billed, timed and scheduled like any generated token. With max_tokens: 200 and 300 tokens of thinking, there is no answer at all. A per-request thinking_token_budget (with a ReasoningConfig giving the start and end strings) makes the sampler force the end-of-thinking marker when the budget runs out (18.e).
  • The opening marker may be in the prompt. Many templates end the prompt with the opening tag, so the output starts mid-thought with no marker. Each parser knows whether its family does this.
  • Past reasoning is usually dropped from history. Templates often omit earlier turns' reasoning, which changes the token sequence and ends the prefix-cache hit there. Some models support keeping it (“interleaved thinking”) for multi-step tool use.

6. Under the hood#

Where reasoning meets structured output#

A reasoning model’s output is thinking, then JSON. A grammar from the first token would forbid the thinking. So the structured-output manager is told the reasoning parser (StructuredOutputsConfig.reasoning_parser) and calls its is_reasoning_end on the tokens so far. The request carries a reasoning_ended flag, and the bitmask is not applied while it is false. enable_in_reasoning reverses this when you want the thinking itself constrained. The documentation’s reasoning-model table shows which structured-output modes and tool calling work with each parser; check it before combining the three on a new model.

Why this lives in the API server#

Parsers need text, and only the API server has the tokenizer and the detokenised stream. Running them there keeps per-model string handling out of the engine core’s main loop. It also means parser CPU cost scales with API server processes, not with the engine. For tool-heavy traffic the fix is more API server processes, or the Rust frontend, which reimplements template rendering and parsing (19.h).

Adding your own#

--tool-parser-plugin path/to/file.py registers a tool parser; --reasoning-parser-plugin does the same for reasoning. This is how a newly released model family is supported before upstream (19.f).

A checklist for a model that will not call tools#

  1. Does the rendered prompt contain the tool definitions? Call /tokenize with your messages and tools, then /detokenize, and read it.
  2. Is --enable-auto-tool-choice set, with the --tool-call-parser documented for this model?
  3. Does the raw output contain a call in a syntax the parser does not expect? Send the request without the parser and read content.
  4. Is max_tokens large enough for reasoning plus the call?
  5. If arguments are malformed under auto, mark the tool strict: true, use --tool-strict-level, or use required or a named tool.

A streaming parser#

This parser separates reasoning, content and a tool call, holding back text that might be the beginning of a marker.

Go
package main

import (
	"fmt"
	"strings"
)

const (
	thinkOpen, thinkClose = "<think>", "</think>"
	toolOpen, toolClose   = "<tool_call>", "</tool_call>"
)

// parser splits a token stream into three channels, as vLLM's reasoning and
// tool parsers do for a streaming chat completion.
type parser struct {
	buf   string // text not yet classified
	state string // "content", "reasoning" or "tool"
}

type delta struct{ kind, text string }

// heldBack returns how many trailing bytes of s could be the start of marker.
func heldBack(s, marker string) int {
	for n := min(len(marker)-1, len(s)); n > 0; n-- {
		if strings.HasPrefix(marker, s[len(s)-n:]) {
			return n
		}
	}
	return 0
}

func (p *parser) feed(piece string) []delta {
	p.buf += piece
	var out []delta
	for {
		var open, close, inner string
		switch p.state {
		case "content":
			// Either marker may come next; take whichever appears first.
			ti, ki := strings.Index(p.buf, thinkOpen), strings.Index(p.buf, toolOpen)
			switch {
			case ti >= 0 && (ki < 0 || ti < ki):
				open, inner = thinkOpen, "reasoning"
			case ki >= 0:
				open, inner = toolOpen, "tool"
			}
			if open != "" {
				i := strings.Index(p.buf, open)
				if i > 0 {
					out = append(out, delta{"content", p.buf[:i]})
				}
				p.buf = p.buf[i+len(open):]
				p.state = inner
				continue
			}
			// No marker yet: release everything that cannot be the start of one.
			hold := max(heldBack(p.buf, thinkOpen), heldBack(p.buf, toolOpen))
			if emit := p.buf[:len(p.buf)-hold]; emit != "" {
				out = append(out, delta{"content", emit})
			}
			p.buf = p.buf[len(p.buf)-hold:]
			return out
		case "reasoning":
			close = thinkClose
		case "tool":
			close = toolClose
		}
		if i := strings.Index(p.buf, close); i >= 0 {
			if i > 0 {
				out = append(out, delta{p.state, p.buf[:i]})
			}
			p.buf = p.buf[i+len(close):]
			p.state = "content"
			continue
		}
		if p.state == "reasoning" { // reasoning streams as it arrives
			hold := heldBack(p.buf, close)
			if emit := p.buf[:len(p.buf)-hold]; emit != "" {
				out = append(out, delta{"reasoning", emit})
			}
			p.buf = p.buf[len(p.buf)-hold:]
		}
		// A tool call is held until its closing tag: partial JSON is not yet a call.
		return out
	}
}

func main() {
	stream := []string{"<th", "ink>", "The user wants", " weather.", "</thi", "nk>",
		"Let me", " check.", "<tool", "_call>", `{"name": "get_weather",`,
		` "arguments": {"city": "Pune"}}`, "</tool_call>"}

	p := &parser{state: "content"}
	channels := map[string]string{}
	for i, piece := range stream {
		ds := p.feed(piece)
		fmt.Printf("token %-2d %-34q", i+1, piece)
		if len(ds) == 0 {
			fmt.Print(" (held back)")
		}
		for _, d := range ds {
			fmt.Printf(" %s+=%q", d.kind, d.text)
			channels[d.kind] += d.text
		}
		fmt.Println()
	}
	fmt.Println()
	fmt.Printf("message.reasoning : %q\n", channels["reasoning"])
	fmt.Printf("message.content   : %q\n", channels["content"])
	fmt.Printf("message.tool_calls: %s\n", channels["tool"])
	fmt.Println(`finish_reason     : "tool_calls"`)
}

Output:

token 1  "<th"                              (held back)
token 2  "ink>"                             (held back)
token 3  "The user wants"                   reasoning+="The user wants"
token 4  " weather."                        reasoning+=" weather."
token 5  "</thi"                            (held back)
token 6  "nk>"                              (held back)
token 7  "Let me"                           content+="Let me"
token 8  " check."                          content+=" check."
token 9  "<tool"                            (held back)
token 10 "_call>"                           (held back)
token 11 "{\"name\": \"get_weather\","      (held back)
token 12 " \"arguments\": {\"city\": \"Pune\"}}" (held back)
token 13 "</tool_call>"                     tool+="{\"name\": \"get_weather\", \"arguments\": {\"city\": \"Pune\"}}"

message.reasoning : "The user wants weather."
message.content   : "Let me check."
message.tool_calls: {"name": "get_weather", "arguments": {"city": "Pune"}}
finish_reason     : "tool_calls"

Eight of the thirteen tokens produce no output when they arrive. Some are marker fragments; the rest belong to a tool call withheld until its closing tag, because half a JSON object is not a call. Many real parsers stream argument fragments instead, as the OpenAI protocol allows, which needs JSON-nesting state as well; the hf parser emits each call whole, like this one.


7. Performance implications#

  • Prompt tokens: tool definitions are prefill on every request unless the prefix cache holds them. Stable tool order keeps the hit.
  • Output tokens: reasoning can be most of the generated tokens. Inter-token latency stays the same; time to the first visible answer grows.
  • Constrained calls add grammar work in the engine core per step (18.e); structural tags only constrain the call region, so free text costs nothing extra.
  • Parser CPU is in the API server and grows with streaming concurrency.

8. Production implications#

  • Pin parser names in configuration and test them when you upgrade the model or vLLM; parser names are treated as a stable interface but behaviour fixes land often.
  • Consider --tool-strict-level function for agent traffic from clients that never set strict; it removes malformed call markup without forcing calls.
  • Monitor finish_reason. A rise in length on a reasoning model usually means max_tokens is too small for the thinking.
  • Migrate clients from reasoning_content to reasoning.

9. Common mistakes#

  1. No parser, or the wrong one. Raw call syntax ends up in content.
  2. max_tokens sized for the answer only, on a reasoning model.
  3. Assuming auto gives valid JSON arguments. Without strict or a floor it is unconstrained.
  4. Reordering tools between requests, which breaks the prefix-cache hit.
  5. Using a template that drops tools. The model never sees them.

10. Hands-on exercise#

  1. Add a second tool call after the first in stream. Does the parser return both? What should finish_reason be?
  2. Remove the <think> opening tag from the stream, as if the template had put it in the prompt. What does the parser do, and how would you fix it for such a model?
  3. On a real server, send the same tool-calling request with tool_choice "auto" and "required", then "auto" with strict: true on the tool. Compare latency and the arguments.
  4. Start a server with --tool-strict-level parameter and send a request whose tool schema the model tends to violate. Does the output change?

11. Interview questions#

  1. How do tool definitions reach the model?
  2. What is the mechanical difference between tool_choice: "auto" and "required" in v0.32.0?
  3. Why must a streaming parser sometimes hold back text it has already received?
  4. Why is the grammar switched on only after reasoning ends?
  5. What does --tool-strict-level function constrain, and what does it leave free?

12. Further reading#

Checked on 12 November 2026.

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in