From a77998e15718b659135b0728e050468b5db6d648 Mon Sep 17 00:00:00 2001 From: Jackey Hua <107608053+zhendonghua@users.noreply.github.com> Date: Fri, 23 Oct 2026 22:23:22 -0400 Subject: [PATCH] [Feat] openai: parse DeepSeek output through deepseek-recipe (#45907) Co-authored-by: hnyls2002 --- .../srt/entrypoints/openai/chat_encoding.py | 6 +- .../openai/chat_encoding_adapters.py | 90 +++++- .../srt/entrypoints/openai/serving_chat.py | 13 +- .../openai/serving_deepseek_recipe.py | 292 +++++++++++++++++- .../srt/entrypoints/openai/serving_inkling.py | 91 ++---- .../entrypoints/openai/serving_responses.py | 4 + .../srt/parser/deepseek_recipe_output.py | 222 +++++++++++++ .../srt/parser/deepseek_recipe_renderer.py | 62 +++- .../openai/test_serving_deepseek_recipe.py | 108 +++++++ .../openai/test_serving_responses.py | 1 + .../parser/test_deepseek_recipe_renderer.py | 25 +- 11 files changed, 801 insertions(+), 113 deletions(-) create mode 100644 python/sglang/srt/parser/deepseek_recipe_output.py diff --git a/python/sglang/srt/entrypoints/openai/chat_encoding.py b/python/sglang/srt/entrypoints/openai/chat_encoding.py index a153eb8290..c0e81442ba 100644 --- a/python/sglang/srt/entrypoints/openai/chat_encoding.py +++ b/python/sglang/srt/entrypoints/openai/chat_encoding.py @@ -108,10 +108,10 @@ def encode_simple_chat( return render_inkling_messages(messages) if spec in ("dsv4", "dsv41"): - from sglang.srt.parser.deepseek_recipe_renderer import RecipeEncoder + from sglang.srt.parser.deepseek_recipe_renderer import DeepSeekRecipe - encoder = RecipeEncoder.from_hf_tokenizer(spec, tokenizer) - return encoder.encode( + deepseek_recipe = DeepSeekRecipe.from_hf_tokenizer(spec, tokenizer) + return deepseek_recipe.encode( {"messages": list(messages), "thinking": thinking_mode == "thinking"} ) diff --git a/python/sglang/srt/entrypoints/openai/chat_encoding_adapters.py b/python/sglang/srt/entrypoints/openai/chat_encoding_adapters.py index 99801968b5..49e1cbacef 100644 --- a/python/sglang/srt/entrypoints/openai/chat_encoding_adapters.py +++ b/python/sglang/srt/entrypoints/openai/chat_encoding_adapters.py @@ -8,7 +8,11 @@ from typing import TYPE_CHECKING, Any, Callable, Literal, Optional, Protocol import msgspec if TYPE_CHECKING: - from sglang.srt.entrypoints.openai.protocol import ChatCompletionRequest, ToolCall + from sglang.srt.entrypoints.openai.protocol import ( + ChatCompletionRequest, + ResponsesRequest, + ToolCall, + ) from sglang.srt.function_call.core_types import ToolCallItem EncodingBackend = Literal["builtin", "recipe"] @@ -17,6 +21,7 @@ EncodingBackend = Literal["builtin", "recipe"] class ChatOutputHooks(msgspec.Struct, frozen=True, kw_only=True): """Chat-handler policies an output adapter needs, bound to one handler.""" + thinking_requested: Callable[[ChatCompletionRequest], bool] tool_call_parsing_active: Callable[[ChatCompletionRequest], bool] history_tool_calls_count: Callable[[ChatCompletionRequest], int] tool_call_id: Callable[[ToolCallItem, int], str] @@ -54,6 +59,8 @@ class ChatEncodingOutputAdapter(Protocol): def parse_responses_output( self, *, + request: ResponsesRequest, + require_reasoning: bool, output_ids: list[int], finish_reason: Optional[dict[str, Any]], separate_reasoning: bool, @@ -61,7 +68,12 @@ class ChatEncodingOutputAdapter(Protocol): ) -> tuple[str, str, list[ToolCallItem]]: ... def new_responses_stream( - self, *, separate_reasoning: bool, parse_tool_calls: bool + self, + *, + request: ResponsesRequest, + require_reasoning: bool, + separate_reasoning: bool, + parse_tool_calls: bool, ) -> ResponsesOutputStream: ... @@ -94,6 +106,77 @@ class ChatEncodingAdapter(Protocol): ... +def select_new_output_ids( + *, + output_ids: list[int], + num_consumed_tokens: int, + completion_tokens: int, + finish_reason_type: Optional[str], + incremental: bool, +) -> list[int]: + if not incremental: + # Intermediate chunks share the live output list; completion_tokens is + # this chunk's snapshot, so later tokens wait for their own chunk. + return output_ids[num_consumed_tokens:completion_tokens] + if finish_reason_type == "abort": + # The abort chunk re-sends already-streamed tokens. + return output_ids[: max(completion_tokens - num_consumed_tokens, 0)] + return output_ids + + +def token_output_sse_chunks( + *, + chunk_id: str, + created: int, + model: str, + index: int, + usage: Optional[dict[str, Any]], + logprobs: Optional[dict], + reasoning: str, + content: str, + tool_calls: list[ToolCall], +) -> list[str]: + """One streamed step of a token-level output parser: a reasoning chunk, a content + chunk, then one chunk per tool call; the step's logprobs ride on the first.""" + from sglang.srt.entrypoints.openai.protocol import ( + ChatCompletionResponseStreamChoice, + ChatCompletionStreamResponse, + DeltaMessage, + ) + from sglang.srt.entrypoints.openai.sse_utils import build_sse_content + + fields = dict( + chunk_id=chunk_id, created=created, model=model, index=index, usage=usage + ) + chunks = [] + if reasoning: + chunks.append( + build_sse_content(reasoning_content=reasoning, logprobs=logprobs, **fields) + ) + logprobs = None + if content: + chunks.append(build_sse_content(content=content, logprobs=logprobs, **fields)) + logprobs = None + for tool_call in tool_calls: + chunk = ChatCompletionStreamResponse( + id=chunk_id, + created=created, + choices=[ + ChatCompletionResponseStreamChoice( + index=index, + delta=DeltaMessage(tool_calls=[tool_call]), + finish_reason=None, + ) + ], + model=model, + usage=usage, + ) + chunks.append(f"data: {chunk.model_dump_json()}\n\n") + if logprobs is not None: + chunks.append(build_sse_content(logprobs=logprobs, **fields)) + return chunks + + class ChatEncodingAdapterContext(msgspec.Struct, frozen=True, kw_only=True): """Everything a builder may read; a builder takes only what its encoding needs. @@ -151,6 +234,9 @@ def _build_deepseek_recipe( return DeepSeekRecipeChatEncodingAdapter( chat_encoding_spec=ctx.chat_encoding_spec, tokenizer=ctx.tokenizer, + reasoning_parser=ctx.reasoning_parser, + tool_call_parser=ctx.tool_call_parser, + chat_hooks=ctx.chat_hooks, default_chat_template_kwargs=ctx.default_chat_template_kwargs, ) diff --git a/python/sglang/srt/entrypoints/openai/serving_chat.py b/python/sglang/srt/entrypoints/openai/serving_chat.py index 341a12f8b4..986badd29c 100644 --- a/python/sglang/srt/entrypoints/openai/serving_chat.py +++ b/python/sglang/srt/entrypoints/openai/serving_chat.py @@ -492,6 +492,7 @@ class OpenAIServingChat(OpenAIServingBase): reasoning_parser=self.reasoning_parser, tool_call_parser=self.tool_call_parser, chat_hooks=chat_encoding_adapters.ChatOutputHooks( + thinking_requested=self._thinking_requested, tool_call_parsing_active=self._tool_call_parsing_active, history_tool_calls_count=self._get_history_tool_calls_cnt, tool_call_id=self._process_tool_call_id, @@ -1554,11 +1555,10 @@ class OpenAIServingChat(OpenAIServingBase): template_content_format = self.template_manager.jinja_template_content_format # Try custom encoding first (override in subclass for custom renderers) - thinking_requested = (request.chat_template_kwargs or {}).get( - "thinking", envs.SGLANG_DEFAULT_THINKING.get() - ) thinking_mode = ( - ThinkingMode.THINKING if thinking_requested else ThinkingMode.CHAT + ThinkingMode.THINKING + if self._thinking_requested(request) + else ThinkingMode.CHAT ) messages = [msg.model_dump() for msg in request.messages] strict_tool_call_arguments = ( @@ -2963,6 +2963,11 @@ class OpenAIServingChat(OpenAIServingBase): chat_template_kwargs[toggle_param] = enabled request.chat_template_kwargs = chat_template_kwargs + def _thinking_requested(self, request: ChatCompletionRequest) -> bool: + return (request.chat_template_kwargs or {}).get( + "thinking", envs.SGLANG_DEFAULT_THINKING.get() + ) + def _get_reasoning_from_request(self, request: ChatCompletionRequest) -> bool: """Determine whether reasoning mode should be enabled for this request. diff --git a/python/sglang/srt/entrypoints/openai/serving_deepseek_recipe.py b/python/sglang/srt/entrypoints/openai/serving_deepseek_recipe.py index fbe9b910e0..e1dfa7f8c8 100644 --- a/python/sglang/srt/entrypoints/openai/serving_deepseek_recipe.py +++ b/python/sglang/srt/entrypoints/openai/serving_deepseek_recipe.py @@ -1,30 +1,56 @@ """DeepSeek-V4 / V4.1 serving glue for the ``dsv4`` / ``dsv41`` chat encoding -specs: prompt encoding through deepseek-recipe under SGLang's request semantics.""" +specs: prompt encoding and output parsing through deepseek-recipe under SGLang's +request semantics.""" from __future__ import annotations +from collections.abc import Sequence from typing import TYPE_CHECKING, Any, Optional, Union +from sglang.srt.entrypoints.openai.chat_encoding_adapters import ( + select_new_output_ids, + token_output_sse_chunks, +) +from sglang.srt.entrypoints.openai.protocol import ( + FunctionResponse, + ToolCall, +) from sglang.srt.environ import envs +from sglang.srt.function_call.core_types import ToolCallItem +from sglang.srt.parser.deepseek_recipe_output import ( + DeepSeekRecipeOutputParser, + RecipeToolCall, + RecipeToolCallDelta, + whole_tool_calls, +) from sglang.srt.parser.deepseek_recipe_renderer import ( - RecipeEncoder, + DeepSeekRecipe, parse_effort_budget, ) +from sglang.srt.runtime_context import get_serving from sglang.srt.utils import ImageData if TYPE_CHECKING: - from sglang.srt.entrypoints.openai.protocol import ChatCompletionRequest + from sglang.srt.entrypoints.openai.chat_encoding_adapters import ChatOutputHooks + from sglang.srt.entrypoints.openai.protocol import ( + ChatCompletionRequest, + ResponsesRequest, + ) DEFAULT_EFFORT_ENVS = { "dsv4": envs.SGLANG_DSV4_REASONING_EFFORT, "dsv41": envs.SGLANG_DSV41_REASONING_EFFORT, } +PARSERS = { + "dsv4": ("deepseek-v4", "deepseekv4"), + "dsv41": ("deepseek-v41", "deepseekv41"), +} +JSON_RESPONSE_FORMATS = ("json_object", "json_schema") class DeepSeekRecipeChatEncodingAdapter: # recipe sorts tool results by call order, so images come from its render. collects_openai_media = False - output = None strict_tool_call_arguments = False # recipe serializes object arguments itself. def __init__( @@ -32,10 +58,15 @@ class DeepSeekRecipeChatEncodingAdapter: *, chat_encoding_spec: str, tokenizer: Any, + reasoning_parser: Optional[str], + tool_call_parser: Optional[str], + chat_hooks: ChatOutputHooks, default_chat_template_kwargs: Optional[dict[str, Any]], ): self._spec = chat_encoding_spec - self.encoder = RecipeEncoder.from_hf_tokenizer(chat_encoding_spec, tokenizer) + self.deepseek_recipe = DeepSeekRecipe.from_hf_tokenizer( + chat_encoding_spec, tokenizer + ) raw = (DEFAULT_EFFORT_ENVS[chat_encoding_spec].get() or "").strip() self._default_effort = int(raw) if raw.isdigit() else raw or None # Encoded at boot, so a bad server default fails startup, not requests. @@ -44,6 +75,27 @@ class DeepSeekRecipeChatEncodingAdapter: {"messages": [{"role": "user", "content": ""}], "thinking": True}, effort=defaults.get("reasoning_effort"), ) + # recipe parses the output once a DeepSeek parser is configured; other + # parsers keep the text path. + reasoning_name, tool_name = PARSERS[chat_encoding_spec] + self._token_output = ( + reasoning_parser == reasoning_name or tool_call_parser == tool_name + ) + if self._token_output and ( + reasoning_parser not in (None, reasoning_name) + or tool_call_parser not in (None, tool_name) + ): + raise ValueError( + f"--reasoning-parser {reasoning_name} and --tool-call-parser " + f"{tool_name} cannot be mixed with other parsers, got " + f"{reasoning_parser!r} and {tool_call_parser!r}" + ) + self._separate_reasoning = reasoning_parser is not None + self._hooks = chat_hooks + + @property + def output(self) -> Optional[DeepSeekRecipeChatEncodingAdapter]: + return self if self._token_output else None def encode_messages( self, @@ -59,13 +111,8 @@ class DeepSeekRecipeChatEncodingAdapter: wire_messages = wire["messages"] continue_final = request.continue_final_message task_prefix = None - # SGLang's trailing-assistant rule, as `_handle_last_assistant_message`. - last = wire_messages[-1] if wire_messages else None - if ( - last - and last["role"] == "assistant" - and isinstance(last.get("content"), str) - ): + last = _trailing_assistant_turn(wire_messages) + if last is not None: if not continue_final: wire_messages[-1] = {"role": "user", "content": last["content"]} elif request.task is not None: @@ -100,7 +147,7 @@ class DeepSeekRecipeChatEncodingAdapter: ) image_data.extend(ImageData(url=url) for url in image_urls) if task_prefix: - prompt_ids += self.encoder.encode_text(task_prefix) + prompt_ids += self.deepseek_recipe.encode_text(task_prefix) return prompt_ids def _encode( @@ -122,6 +169,223 @@ class DeepSeekRecipeChatEncodingAdapter: budget = parse_effort_budget(effort) elif effort is not None: body["reasoning_effort"] = effort - return self.encoder.encode( + return self.deepseek_recipe.encode( body, task=task, effort_budget=budget, image_urls=image_urls ) + + def parse_chat_response( + self, + *, + request: ChatCompletionRequest, + output_ids: list[int], + finish_reason: dict[str, Any], + ) -> tuple[Optional[str], str, Optional[list[ToolCall]], dict[str, Any]]: + delta = self._new_output_parser(request).finish( + output_ids, finish_reason, keep_matched_stop=request.no_stop_trim + ) + calls = whole_tool_calls(delta) + if not calls: + return delta.reasoning or None, delta.content, None, finish_reason + history_tool_calls_cnt = self._hooks.history_tool_calls_count(request) + tool_calls = [ + ToolCall( + id=self._tool_call_id(call.index, call.name, history_tool_calls_cnt), + index=call.index, + function=FunctionResponse(name=call.name, arguments=call.arguments), + ) + for call in calls + ] + if finish_reason["type"] == "stop": + finish_reason = {**finish_reason, "type": "tool_calls", "matched": None} + return delta.reasoning or None, delta.content, tool_calls, finish_reason + + def stream_chat_chunks( + self, + *, + content: dict[str, Any], + index: int, + request: ChatCompletionRequest, + created: int, + parser_dict: dict[int, Any], + has_tool_calls: dict[int, bool], + choice_logprobs: Optional[dict], + finish_reason_type: Optional[str], + usage: Optional[dict[str, Any]], + ) -> list[str]: + if index not in parser_dict: + parser_dict[index] = self._new_output_parser(request) + parser = parser_dict[index] + new_output_ids = select_new_output_ids( + output_ids=content["output_ids"], + num_consumed_tokens=parser.num_consumed_tokens, + completion_tokens=content["meta_info"]["completion_tokens"], + finish_reason_type=finish_reason_type, + incremental=get_serving().incremental_streaming_output, + ) + if finish_reason_type is None: + delta = parser.feed(new_output_ids) + else: + delta = parser.finish( + new_output_ids, + content["meta_info"]["finish_reason"], + keep_matched_stop=request.no_stop_trim, + ) + + history_tool_calls_cnt = self._hooks.history_tool_calls_count(request) + if delta.tool_calls: + has_tool_calls[index] = True + return token_output_sse_chunks( + chunk_id=content["meta_info"]["id"], + created=created, + model=request.model, + index=index, + usage=usage, + logprobs=choice_logprobs, + reasoning=delta.reasoning, + content=delta.content, + tool_calls=[ + ToolCall( + # The first piece of a call names it; later pieces extend its + # arguments. + id=( + self._tool_call_id( + piece.index, piece.name, history_tool_calls_cnt + ) + if piece.name is not None + else None + ), + index=piece.index, + function=FunctionResponse( + name=piece.name, arguments=piece.arguments + ), + ) + for piece in delta.tool_calls + ], + ) + + def parse_responses_output( + self, + *, + request: ResponsesRequest, + require_reasoning: bool, + output_ids: list[int], + finish_reason: Optional[dict[str, Any]], + separate_reasoning: bool, + parse_tool_calls: bool, + ) -> tuple[str, str, list[ToolCallItem]]: + parser = self._new_responses_parser( + request, require_reasoning, separate_reasoning, parse_tool_calls + ) + delta = parser.finish(output_ids, finish_reason or {"type": "stop"}) + return delta.reasoning, delta.content, _tool_call_items(whole_tool_calls(delta)) + + def new_responses_stream( + self, + *, + request: ResponsesRequest, + require_reasoning: bool, + separate_reasoning: bool, + parse_tool_calls: bool, + ) -> DeepSeekRecipeResponsesStream: + return DeepSeekRecipeResponsesStream( + self._new_responses_parser( + request, require_reasoning, separate_reasoning, parse_tool_calls + ) + ) + + def _new_output_parser( + self, request: ChatCompletionRequest + ) -> DeepSeekRecipeOutputParser: + response_format = request.response_format + continued = ( + _trailing_assistant_turn( + [ + message.model_dump(exclude_unset=True, by_alias=True, mode="json") + for message in request.messages[-1:] + ] + ) + if request.continue_final_message + else None + ) + return DeepSeekRecipeOutputParser( + self.deepseek_recipe, + thinking_stage=self.deepseek_recipe.parse_start( + thinking=self._hooks.thinking_requested(request), + task=request.task, + continued=continued, + ), + parse_tool_calls=request.task is None + and self._hooks.tool_call_parsing_active(request), + parse_json_output=response_format is not None + and response_format.type in JSON_RESPONSE_FORMATS, + separate_reasoning=self._separate_reasoning and request.separate_reasoning, + stream_reasoning=request.stream_reasoning, + stop=_stop_strings(request.stop), + ) + + def _new_responses_parser( + self, + request: ResponsesRequest, + require_reasoning: bool, + separate_reasoning: bool, + parse_tool_calls: bool, + ) -> DeepSeekRecipeOutputParser: + return DeepSeekRecipeOutputParser( + self.deepseek_recipe, + thinking_stage=self.deepseek_recipe.parse_start(thinking=require_reasoning), + parse_tool_calls=parse_tool_calls, + separate_reasoning=separate_reasoning, + stop=_stop_strings(request.stop), + ) + + def _tool_call_id(self, index: int, name: str, history_tool_calls_cnt: int) -> str: + return self._hooks.tool_call_id( + ToolCallItem(tool_index=index, name=name, parameters=""), + history_tool_calls_cnt, + ) + + +class DeepSeekRecipeResponsesStream: + def __init__(self, parser: DeepSeekRecipeOutputParser): + self._parser = parser + self._incremental = get_serving().incremental_streaming_output + + def step( + self, chunk: dict[str, Any], finish_reason: Optional[dict[str, Any]] + ) -> tuple[str, str, list[ToolCallItem]]: + new_output_ids = select_new_output_ids( + output_ids=chunk.get("output_ids") or [], + num_consumed_tokens=self._parser.num_consumed_tokens, + completion_tokens=chunk["meta_info"]["completion_tokens"], + finish_reason_type=finish_reason["type"] if finish_reason else None, + incremental=self._incremental, + ) + if finish_reason is None: + delta = self._parser.feed(new_output_ids) + else: + delta = self._parser.finish(new_output_ids, finish_reason) + return delta.reasoning, delta.content, _tool_call_items(delta.tool_calls) + + +def _trailing_assistant_turn( + messages: list[dict[str, Any]], +) -> Optional[dict[str, Any]]: + """The trailing text turn SGLang continues or, without continue_final_message, + re-sends as a user turn (as `_handle_last_assistant_message`).""" + last = messages[-1] if messages else None + if last and last["role"] == "assistant" and isinstance(last.get("content"), str): + return last + return None + + +def _stop_strings(stop: Union[str, list[str], None]) -> list[str]: + return [stop] if isinstance(stop, str) else stop or [] + + +def _tool_call_items( + calls: Sequence[Union[RecipeToolCall, RecipeToolCallDelta]], +) -> list[ToolCallItem]: + return [ + ToolCallItem(tool_index=call.index, name=call.name, parameters=call.arguments) + for call in calls + ] diff --git a/python/sglang/srt/entrypoints/openai/serving_inkling.py b/python/sglang/srt/entrypoints/openai/serving_inkling.py index acfb8ba297..5545a0829f 100644 --- a/python/sglang/srt/entrypoints/openai/serving_inkling.py +++ b/python/sglang/srt/entrypoints/openai/serving_inkling.py @@ -6,15 +6,16 @@ from __future__ import annotations import math from typing import TYPE_CHECKING, Any, Optional +from sglang.srt.entrypoints.openai.chat_encoding_adapters import ( + select_new_output_ids, + token_output_sse_chunks, +) from sglang.srt.entrypoints.openai.protocol import ( ChatCompletionRequest, - ChatCompletionResponseStreamChoice, - ChatCompletionStreamResponse, - DeltaMessage, FunctionResponse, + ResponsesRequest, ToolCall, ) -from sglang.srt.entrypoints.openai.sse_utils import build_sse_content from sglang.srt.function_call.core_types import ToolCallItem from sglang.srt.parser.inkling_output import ( InklingOutputDelta, @@ -144,60 +145,29 @@ class InklingChatEncodingAdapter: keep_matched_stop=request.no_stop_trim, ) - chunk_fields = dict( + history_tool_calls_cnt = self._hooks.history_tool_calls_count(request) + if delta.tool_calls: + has_tool_calls[index] = True + return token_output_sse_chunks( chunk_id=content["meta_info"]["id"], created=created, model=request.model, index=index, usage=usage, + logprobs=choice_logprobs, + reasoning=delta.reasoning, + content=delta.content, + tool_calls=[ + self._tool_call(call, history_tool_calls_cnt) + for call in delta.tool_calls + ], ) - chunks = [] - remaining_logprobs = choice_logprobs - if delta.reasoning: - chunks.append( - build_sse_content( - reasoning_content=delta.reasoning, - logprobs=remaining_logprobs, - **chunk_fields, - ) - ) - remaining_logprobs = None - if delta.content: - chunks.append( - build_sse_content( - content=delta.content, logprobs=remaining_logprobs, **chunk_fields - ) - ) - remaining_logprobs = None - history_tool_calls_cnt = self._hooks.history_tool_calls_count(request) - for call in delta.tool_calls: - has_tool_calls[index] = True - tool_call_chunk = ChatCompletionStreamResponse( - id=content["meta_info"]["id"], - created=chunk_fields["created"], - choices=[ - ChatCompletionResponseStreamChoice( - index=index, - delta=DeltaMessage( - tool_calls=[self._tool_call(call, history_tool_calls_cnt)] - ), - finish_reason=None, - ) - ], - model=request.model, - usage=usage, - ) - chunks.append(f"data: {tool_call_chunk.model_dump_json()}\n\n") - if remaining_logprobs is not None: - chunks.append( - build_sse_content(logprobs=remaining_logprobs, **chunk_fields) - ) - return chunks - def parse_responses_output( self, *, + request: ResponsesRequest, + require_reasoning: bool, output_ids: list[int], finish_reason: dict[str, Any] | None, separate_reasoning: bool, @@ -214,7 +184,12 @@ class InklingChatEncodingAdapter: return delta.reasoning, delta.content, _tool_call_items(delta) def new_responses_stream( - self, *, separate_reasoning: bool, parse_tool_calls: bool + self, + *, + request: ResponsesRequest, + require_reasoning: bool, + separate_reasoning: bool, + parse_tool_calls: bool, ) -> InklingResponsesStream: return InklingResponsesStream( separate_reasoning=separate_reasoning, parse_tool_calls=parse_tool_calls @@ -280,24 +255,6 @@ def _tool_call_items(delta: InklingOutputDelta) -> list[ToolCallItem]: ] -def select_new_output_ids( - *, - output_ids: list[int], - num_consumed_tokens: int, - completion_tokens: int, - finish_reason_type: str | None, - incremental: bool, -) -> list[int]: - if not incremental: - # Intermediate chunks share the live output list; completion_tokens is - # this chunk's snapshot, so later tokens wait for their own chunk. - return output_ids[num_consumed_tokens:completion_tokens] - if finish_reason_type == "abort": - # The abort chunk re-sends already-streamed tokens. - return output_ids[: max(completion_tokens - num_consumed_tokens, 0)] - return output_ids - - _TOKENIZER_PROBE = "Hello, 世界! def f(x): return x**2" diff --git a/python/sglang/srt/entrypoints/openai/serving_responses.py b/python/sglang/srt/entrypoints/openai/serving_responses.py index 0021fc596f..2f1f8279ab 100644 --- a/python/sglang/srt/entrypoints/openai/serving_responses.py +++ b/python/sglang/srt/entrypoints/openai/serving_responses.py @@ -1073,6 +1073,8 @@ class OpenAIServingResponses(OpenAIServingChat): if encoding_output is not None: required_json = self._uses_required_tool_json(request, chat_tools) reasoning_content, content, calls = encoding_output.parse_responses_output( + request=request, + require_reasoning=require_reasoning, output_ids=output_ids or [], finish_reason=finish_reason, separate_reasoning=bool(self.reasoning_parser), @@ -2224,6 +2226,8 @@ class OpenAIServingResponses(OpenAIServingChat): encoding_output = self._encoding_output() token_stream = ( encoding_output.new_responses_stream( + request=request, + require_reasoning=require_reasoning, separate_reasoning=bool(self.reasoning_parser), parse_tool_calls=( self._tool_call_parsing_enabled(request, chat_tools) diff --git a/python/sglang/srt/parser/deepseek_recipe_output.py b/python/sglang/srt/parser/deepseek_recipe_output.py new file mode 100644 index 0000000000..619e39c9be --- /dev/null +++ b/python/sglang/srt/parser/deepseek_recipe_output.py @@ -0,0 +1,222 @@ +"""Token-level output parsing for DeepSeek-V4 / V4.1 through deepseek-recipe's +StreamProcessor: `` and the DSML tags are recognized by token ID, as the API +parses them, and tool-call arguments arrive as the API streams them.""" + +from __future__ import annotations + +import json +from collections.abc import Sequence +from typing import Any, Optional + +import msgspec + +from sglang.srt.parser.deepseek_recipe_renderer import ( + DeepSeekRecipe, + load_deepseek_recipe, +) + + +class RecipeToolCallDelta(msgspec.Struct, frozen=True): + """A piece of one call's JSON arguments; the first piece also names the call.""" + + index: int + arguments: str + name: Optional[str] = None + + +class RecipeOutputDelta(msgspec.Struct, frozen=True): + reasoning: str = "" + content: str = "" + tool_calls: tuple[RecipeToolCallDelta, ...] = () + + def merge(self, other: RecipeOutputDelta) -> RecipeOutputDelta: + return RecipeOutputDelta( + reasoning=self.reasoning + other.reasoning, + content=self.content + other.content, + tool_calls=self.tool_calls + other.tool_calls, + ) + + +class RecipeToolCall(msgspec.Struct, frozen=True): + index: int + name: str + arguments: str + + +def whole_tool_calls(delta: RecipeOutputDelta) -> list[RecipeToolCall]: + calls: dict[int, list[str]] = {} + for piece in delta.tool_calls: + if piece.name is not None: + calls[piece.index] = [piece.name, piece.arguments] + else: + calls[piece.index][1] += piece.arguments + return [ + RecipeToolCall(index=index, name=name, arguments=arguments) + for index, (name, arguments) in sorted(calls.items()) + ] + + +class DeepSeekRecipeOutputParser: + """One choice's output through recipe's StreamProcessor, fed the engine's token + ids. Stops stay SGLang's: the scheduler matches them and `finish` cuts the match. + `thinking_stage` is recipe's ThinkingInitialStage, None after a non-thinking + prompt.""" + + def __init__( + self, + deepseek_recipe: DeepSeekRecipe, + *, + thinking_stage: Any, + parse_tool_calls: bool, + parse_json_output: bool = False, + separate_reasoning: bool = True, + stream_reasoning: bool = True, + stop: Sequence[str] = (), + ): + recipe = load_deepseek_recipe() + options = recipe.ParsingOptions( + parse_tool_calls=parse_tool_calls, + parse_json_output=parse_json_output, + thinking_initial_stage=thinking_stage, + special_tokens=deepseek_recipe.special_tokens, + ) + # The generator only frames chunks; what is parsed follows `options`. + request = recipe.ConversationRequest( + recipe.Conversation(), deepseek_recipe.model_version + ) + generator = recipe.ChatCompletionRequest.chunk_generator( + request, "", deepseek_recipe.model + ) + self._recipe = recipe + self._processor = recipe.StreamProcessor( + generator, options, deepseek_recipe.tokenizer + ) + self._hf_tokenizer = deepseek_recipe.hf_tokenizer + self._reasoning_as_content = not separate_reasoning + self._hold_reasoning = separate_reasoning and not stream_reasoning + self._held_reasoning = "" + # Ids a stop string may still start in wait until the scheduler rules it + # out, so a matched stop is cut before recipe has emitted any of it. + self._stop_hold_chars = max(map(len, stop), default=1) - 1 + self._pending_ids: list[int] = [] + self.num_consumed_tokens = 0 + + def feed(self, token_ids: Sequence[int]) -> RecipeOutputDelta: + self.num_consumed_tokens += len(token_ids) + if self._processor.finished: + return RecipeOutputDelta() + self._pending_ids += token_ids + ready = self._release_pending_ids() + if not ready: + return RecipeOutputDelta() + return self._deltas( + self._processor.push(self._recipe.InferenceChunk.tokens(ready)) + ) + + def _release_pending_ids(self) -> list[int]: + held = len(self._pending_ids) + while held > 0 and self._stop_hold_chars > len( + self._hf_tokenizer.decode( + self._pending_ids[held:], skip_special_tokens=False + ) + ): + held -= 1 + ready, self._pending_ids = self._pending_ids[:held], self._pending_ids[held:] + return ready + + def finish( + self, + token_ids: Sequence[int], + finish_reason: dict[str, Any], + *, + keep_matched_stop: bool = False, + ) -> RecipeOutputDelta: + """The last engine chunk: its ids, less the matched stop, and its reason.""" + self.num_consumed_tokens += len(token_ids) + if self._processor.finished: + return RecipeOutputDelta() # a sticky finish_reason re-sent + token_ids = self._pending_ids + list(token_ids) + self._pending_ids = [] + matched = finish_reason.get("matched") + if isinstance(matched, str): + token_ids = self._cut_at_stop_string( + token_ids, matched, keep_stop=keep_matched_stop + ) + elif ( + isinstance(matched, int) + and not keep_matched_stop + and token_ids + and token_ids[-1] == matched + ): + token_ids = token_ids[:-1] + chunks = ( + self._processor.push(self._recipe.InferenceChunk.tokens(token_ids)) + if token_ids + else [] + ) + if not self._processor.finished: + reason = { + "stop": self._recipe.InferenceFinishReason.Stop, + "length": self._recipe.InferenceFinishReason.Length, + }.get(finish_reason["type"]) + if reason is None: # abort: flush the parse without a backend finish + chunks += self._processor.finish() + else: + chunks += self._processor.push( + self._recipe.InferenceChunk.finish(reason) + ) + return self._deltas(chunks) + + def _cut_at_stop_string( + self, token_ids: list[int], stop: str, *, keep_stop: bool + ) -> list[int]: + # The scheduler matched `stop` in the decoded text and ended on the token + # completing it; the earliest match ending there starts at most + # len(stop) - 1 characters before that token. + decode = self._hf_tokenizer.decode + start = len(token_ids) - 1 + last = decode(token_ids[start:], skip_special_tokens=False) + text = last + while start > 0 and (stop not in text or len(text) - len(last) < len(stop) - 1): + start -= 1 + text = decode(token_ids[start:], skip_special_tokens=False) + cut = text.find(stop) + if cut == -1: + return token_ids + if keep_stop: + cut += len(stop) + return ( + token_ids[:start] + + self._hf_tokenizer.encode(text[:cut], add_special_tokens=False).ids + ) + + def _deltas(self, chunks: list[Any]) -> RecipeOutputDelta: + delta = RecipeOutputDelta() + for chunk in chunks: + choice = json.loads(chunk.to_json())["choices"][0] + piece = choice["delta"] + if piece.get("role"): # the handler emits its own role chunk + continue + reasoning = piece.get("reasoning_content") or "" + content = piece.get("content") or "" + tool_calls = tuple( + RecipeToolCallDelta( + index=call["index"], + arguments=call["function"]["arguments"], + name=call["function"].get("name"), + ) + for call in piece.get("tool_calls") or () + ) + if self._reasoning_as_content: + content, reasoning = reasoning + content, "" + if self._hold_reasoning: + self._held_reasoning += reasoning + reasoning = "" + if content or tool_calls or choice["finish_reason"]: + reasoning, self._held_reasoning = self._held_reasoning, "" + delta = delta.merge( + RecipeOutputDelta( + reasoning=reasoning, content=content, tool_calls=tool_calls + ) + ) + return delta diff --git a/python/sglang/srt/parser/deepseek_recipe_renderer.py b/python/sglang/srt/parser/deepseek_recipe_renderer.py index 0a44dabf4e..964c655455 100644 --- a/python/sglang/srt/parser/deepseek_recipe_renderer.py +++ b/python/sglang/srt/parser/deepseek_recipe_renderer.py @@ -29,6 +29,8 @@ TASK_TOKENS = { "title": "<|title|>", "read_url": "<|read_url|>", } +# `action` follows the generation header; the other tasks replace it. +TASKS_AFTER_HEADER = ("action",) # V4.1 renders an integer budget as this line; recipe's "high" tier is budget 75. BUDGET_TIER, BUDGET_TIER_VALUE = "high", 75 BUDGET_LINE = "Reasoning Effort: {budget}" @@ -100,7 +102,7 @@ def _error_message(body: Any) -> str: return str(body) -class RecipeEncoder: +class DeepSeekRecipe: """`tokenizer` is the checkpoint's `tokenizers.Tokenizer`; recipe encodes prompts with its own copy of it, and the SGLang extensions splice ids from the original.""" @@ -108,21 +110,25 @@ class RecipeEncoder: recipe = load_deepseek_recipe() self.model = MODEL_NAMES[chat_encoding_spec] self.hf_tokenizer = tokenizer - special = recipe.SpecialTokens(image=IMAGE_TOKEN) - self._options = recipe.ConversionOptions().with_special_tokens(special) - encoding = ( - recipe.DeepseekV4Encoding() - if chat_encoding_spec == "dsv4" - else recipe.DeepseekV41Encoding() - ) - self._encoding = encoding.with_special_tokens(special).with_tokenizer( - recipe.Tokenizer.from_str(tokenizer.to_str()) + self.special_tokens = recipe.SpecialTokens(image=IMAGE_TOKEN) + self._options = recipe.ConversionOptions().with_special_tokens( + self.special_tokens ) + if chat_encoding_spec == "dsv4": + encoding = recipe.DeepseekV4Encoding() + self.model_version = recipe.ModelVersion.DeepseekV4Pro + else: + encoding = recipe.DeepseekV41Encoding() + self.model_version = recipe.ModelVersion.DeepseekV41Flash + self.tokenizer = recipe.Tokenizer.from_str(tokenizer.to_str()) + self._encoding = encoding.with_special_tokens( + self.special_tokens + ).with_tokenizer(self.tokenizer) @classmethod def from_hf_tokenizer( cls, chat_encoding_spec: str, tokenizer: Any - ) -> RecipeEncoder: + ) -> DeepSeekRecipe: backend = getattr(tokenizer, "backend_tokenizer", None) if backend is None: raise ValueError( @@ -161,6 +167,38 @@ class RecipeEncoder: prompt_ids = self._attach_task(prompt_ids, task, body["thinking"]) return prompt_ids + def parse_start( + self, + *, + thinking: bool, + task: Optional[str] = None, + continued: Optional[dict[str, Any]] = None, + ) -> Any: + """Where output parsing begins after the prompt `encode` renders for these + settings, as recipe's ThinkingInitialStage; None when the output is answer + only. `continued` is the final assistant message the prompt continues.""" + if not thinking or (task is not None and task not in TASKS_AFTER_HEADER): + return None + recipe = load_deepseek_recipe() + if continued is None: + return recipe.ThinkingInitialStage.ReasoningStart + if task is not None: + # The continued prefix follows the task token. + return recipe.ThinkingInitialStage.ContentContinuation + body = pre_normalize( + { + "messages": [{"role": "user", "content": ""}, continued], + "thinking": True, + "continue_final_message": True, + } + ) + body["model"] = self.model + try: + converted = recipe.ChatCompletionRequest(body).convert(self._options) + except recipe.ConversionError as error: + raise ValueError(_error_message(error.body)) from error + return converted.parsing_options.thinking_initial_stage + def encode_text(self, text: str) -> list[int]: return self.hf_tokenizer.encode(text, add_special_tokens=False).ids @@ -194,6 +232,6 @@ class RecipeEncoder: "task requires the conversation to end with a user message" ) task_id = self.hf_tokenizer.token_to_id(TASK_TOKENS[task]) - if task == "action": + if task in TASKS_AFTER_HEADER: return prompt_ids + [task_id] return prompt_ids[: -len(header)] + [task_id] diff --git a/test/registered/unit/entrypoints/openai/test_serving_deepseek_recipe.py b/test/registered/unit/entrypoints/openai/test_serving_deepseek_recipe.py index 97e83a7935..934edf424f 100644 --- a/test/registered/unit/entrypoints/openai/test_serving_deepseek_recipe.py +++ b/test/registered/unit/entrypoints/openai/test_serving_deepseek_recipe.py @@ -1,3 +1,4 @@ +import json import unittest from types import SimpleNamespace @@ -74,6 +75,7 @@ class TestAdapterRegistry(CustomTestCase): reasoning_parser=None, tool_call_parser=None, chat_hooks=registry.ChatOutputHooks( + thinking_requested=lambda request: False, tool_call_parsing_active=lambda request: False, history_tool_calls_count=lambda request: 0, tool_call_id=lambda item, index: "", @@ -293,6 +295,112 @@ class TestHandlerRequestSemantics(CustomTestCase): titled = self._prompt(chat, task="title").prompt_ids self.assertEqual(titled[-1], self._token("<|title|>")) + def _parse(self, chat, text, *, matched=None, **fields): + from sglang.srt.entrypoints.openai.protocol import ChatCompletionRequest + + eos = self._token("<|end▁of▁sentence|>") + request = ChatCompletionRequest( + messages=fields.pop("messages", [{"role": "user", "content": "hi"}]), + **fields, + ) + output_ids = self.tokenizer.encode(text, add_special_tokens=False) + if matched is None: + output_ids.append(eos) + reasoning, content, tool_calls, _ = chat._encoding_output().parse_chat_response( + request=request, + output_ids=output_ids, + finish_reason={"type": "stop", "matched": matched or eos}, + ) + return reasoning, content, tool_calls + + def test_output_parsing_starts_where_the_prompt_ends(self): + chat = _serving(self, self.tokenizer) + thinking = {"chat_template_kwargs": {"thinking": True}} + answer = "Let me think.Hello" + self.assertEqual( + self._parse(chat, answer, **thinking)[:2], ("Let me think.", "Hello") + ) + # Thinking is off by default and a task replaces the thinking header, + # so the output is all answer. + self.assertIsNone(self._parse(chat, answer)[0]) + self.assertEqual( + self._parse(chat, "A title", task="title", **thinking)[:2], + (None, "A title"), + ) + continued = [ + {"role": "user", "content": "hi"}, + {"role": "assistant", "content": "Hello"}, + ] + self.assertEqual( + self._parse( + chat, + " world", + messages=continued, + continue_final_message=True, + **thinking, + )[:2], + (None, " world"), + ) + + def test_streamed_tool_call(self): + from sglang.srt.entrypoints.openai.protocol import ChatCompletionRequest + + chat = _serving(self, self.tokenizer) + tools = [ + { + "type": "function", + "function": { + "name": "get_weather", + "parameters": { + "type": "object", + "properties": {"city": {"type": "string"}}, + }, + }, + } + ] + request = ChatCompletionRequest( + messages=[{"role": "user", "content": "weather?"}], tools=tools + ) + output_ids = self.tokenizer.encode( + "Sure.\n\n<|DSML| calls>\n" + '<|DSML| invoke name="get_weather">\n' + '<|DSML| parameter name="city" string="true">Paris\n' + "\n", + add_special_tokens=False, + ) + [self._token("<|end▁of▁sentence|>")] + finish = {"type": "stop", "matched": output_ids[-1]} + parsers, has_tool_calls, calls = {}, {}, [] + for end in range(1, len(output_ids) + 1): + last = end == len(output_ids) + for chunk in chat._encoding_output().stream_chat_chunks( + content={ + "output_ids": output_ids[:end], + "meta_info": { + "id": "chat", + "completion_tokens": end, + "finish_reason": finish if last else None, + }, + }, + index=0, + request=request, + created=0, + parser_dict=parsers, + has_tool_calls=has_tool_calls, + choice_logprobs=None, + finish_reason_type="stop" if last else None, + usage=None, + ): + delta = json.loads(chunk.removeprefix("data: "))["choices"][0]["delta"] + calls += delta.get("tool_calls") or [] + self.assertTrue(has_tool_calls[0]) + # SGLang names the call; recipe streams its arguments. + self.assertRegex(calls[0]["id"], r"^call_[0-9a-f]{24}$") + self.assertEqual(calls[0]["function"]["name"], "get_weather") + self.assertEqual( + json.loads("".join(call["function"]["arguments"] for call in calls)), + {"city": "Paris"}, + ) + if __name__ == "__main__": unittest.main() diff --git a/test/registered/unit/entrypoints/openai/test_serving_responses.py b/test/registered/unit/entrypoints/openai/test_serving_responses.py index 13ac0bd13d..a9036a72da 100644 --- a/test/registered/unit/entrypoints/openai/test_serving_responses.py +++ b/test/registered/unit/entrypoints/openai/test_serving_responses.py @@ -1421,6 +1421,7 @@ class ChatEncodingAdapterDispatchTestCase(CustomTestCase): from sglang.srt.entrypoints.openai import chat_encoding_adapters return chat_encoding_adapters.ChatOutputHooks( + thinking_requested=Mock(), tool_call_parsing_active=Mock(), history_tool_calls_count=Mock(), tool_call_id=Mock(), diff --git a/test/registered/unit/parser/test_deepseek_recipe_renderer.py b/test/registered/unit/parser/test_deepseek_recipe_renderer.py index 6d59d1e3ad..d8b83e8c09 100644 --- a/test/registered/unit/parser/test_deepseek_recipe_renderer.py +++ b/test/registered/unit/parser/test_deepseek_recipe_renderer.py @@ -117,28 +117,28 @@ class TestEffortBudget(CustomTestCase): renderer.parse_effort_budget(value) -class TestRecipeEncoder(CustomTestCase): +class TestDeepSeekRecipe(CustomTestCase): @classmethod def setUpClass(cls): super().setUpClass() from tokenizers import Tokenizer cls.tokenizer = Tokenizer.from_file(_tokenizer_file()) - cls.encoder = renderer.RecipeEncoder("dsv41", cls.tokenizer) + cls.deepseek_recipe = renderer.DeepSeekRecipe("dsv41", cls.tokenizer) def _ids(self, *tokens): return [self.tokenizer.token_to_id(token) for token in tokens] def test_encodes_with_the_served_vocabulary(self): self.assertEqual( - self.encoder.encode( + self.deepseek_recipe.encode( {"messages": [{"role": "user", "content": ""}], "thinking": False} ), self._ids( "<|begin▁of▁sentence|>", "<|User|>", "<|Assistant|>", "" ), ) - thinking = self.encoder.encode( + thinking = self.deepseek_recipe.encode( {"messages": [{"role": "user", "content": "hi"}], "thinking": True} ) self.assertEqual(thinking[-2:], self._ids("<|Assistant|>", "")) @@ -149,7 +149,7 @@ class TestRecipeEncoder(CustomTestCase): "messages": [{"role": "user", "content": "hello"}], "thinking": thinking, } - plain = self.encoder.encode(body) + plain = self.deepseek_recipe.encode(body) for task, token in renderer.TASK_TOKENS.items(): with self.subTest(thinking=thinking, task=task): expected = ( @@ -157,7 +157,9 @@ class TestRecipeEncoder(CustomTestCase): if task == "action" else plain[:-2] + self._ids(token) ) - self.assertEqual(self.encoder.encode(body, task=task), expected) + self.assertEqual( + self.deepseek_recipe.encode(body, task=task), expected + ) continued = { "messages": [ {"role": "user", "content": "count"}, @@ -167,12 +169,12 @@ class TestRecipeEncoder(CustomTestCase): "continue_final_message": True, } with self.assertRaisesRegex(ValueError, "end with a user message"): - self.encoder.encode(continued, task="query") + self.deepseek_recipe.encode(continued, task="query") def test_effort_budget_rewrites_the_effort_line(self): body = {"messages": [{"role": "user", "content": "hi"}], "thinking": True} high = self.tokenizer.decode( - self.encoder.encode({**body, "reasoning_effort": "high"}), + self.deepseek_recipe.encode({**body, "reasoning_effort": "high"}), skip_special_tokens=False, ) self.assertIn("Reasoning Effort: 75 (range 1-100", high) @@ -182,18 +184,19 @@ class TestRecipeEncoder(CustomTestCase): "Reasoning Effort: 75 ", f"Reasoning Effort: {budget} ", 1 ) self.assertEqual( - self.encoder.encode(body, effort_budget=budget), + self.deepseek_recipe.encode(body, effort_budget=budget), self.tokenizer.encode(expected, add_special_tokens=False).ids, ) # Chat mode renders no effort line, so the budget changes nothing. chat = {"messages": [{"role": "user", "content": "hi"}], "thinking": False} self.assertEqual( - self.encoder.encode(chat, effort_budget=30), self.encoder.encode(chat) + self.deepseek_recipe.encode(chat, effort_budget=30), + self.deepseek_recipe.encode(chat), ) def test_api_validation_surfaces_as_value_error(self): with self.assertRaises(ValueError): - self.encoder.encode( + self.deepseek_recipe.encode( { "messages": [{"role": "user", "content": "hi"}], "thinking": True,