Skip to content
Closed
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 17 additions & 3 deletions python/sglang/srt/function_call/function_call_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@
from sglang.srt.function_call.utils import (
_get_tool_schema_defs,
get_json_schema_constraint,
get_json_schema_properties,
)

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -116,6 +117,17 @@ def __init__(self, tools: List[Tool], tool_call_parser: str, tokenizer=None):

self.detector = detector
self.tools = tools
self.detector_tools: List[Tool] = []
for tool in tools:
parameters = tool.function.parameters
if isinstance(parameters, dict):
properties = get_json_schema_properties(parameters)
if properties != parameters.get("properties", {}):
function = tool.function.model_copy(
update={"parameters": parameters | {"properties": properties}}
)
tool = tool.model_copy(update={"function": function})
self.detector_tools.append(tool)
self.tool_strict_level = envs.SGLANG_TOOL_STRICT_LEVEL.get()

def has_tool_call(self, text: str) -> bool:
Expand Down Expand Up @@ -148,7 +160,7 @@ def parse_non_stream(self, full_text: str) -> Tuple[str, list[ToolCallItem]]:
if not self.tools:
return full_text, []
has_tool_call = self.detector.has_tool_call(full_text)
parsed_result = self.detector.detect_and_parse(full_text, self.tools)
parsed_result = self.detector.detect_and_parse(full_text, self.detector_tools)
tool_call_list = parsed_result.calls
if tool_call_list or has_tool_call:
return parsed_result.normal_text, tool_call_list
Expand All @@ -172,7 +184,9 @@ def parse_stream_chunk(self, chunk_text: str) -> Tuple[str, list[ToolCallItem]]:
final_normal_text = ""
final_calls = []

sp_result = self.detector.parse_streaming_increment(chunk_text, self.tools)
sp_result = self.detector.parse_streaming_increment(
chunk_text, self.detector_tools
)
if sp_result.normal_text:
final_normal_text = sp_result.normal_text
if sp_result.calls:
Expand All @@ -189,7 +203,7 @@ def parse_stream_end(self) -> Tuple[str, list[ToolCallItem]]:
"""
if not self.tools:
return "", []
sp_result = self.detector.finish(self.tools)
sp_result = self.detector.finish(self.detector_tools)
return sp_result.normal_text, sp_result.calls

def get_legacy_structural_tag(
Expand Down
2 changes: 1 addition & 1 deletion python/sglang/srt/function_call/glm47_moe_detector.py
Original file line number Diff line number Diff line change
Expand Up @@ -613,7 +613,7 @@ def _finalize_tool_call(
self._last_arguments += "{}"
self.streamed_args_for_tool[self.current_tool_id] += "{}"
self._sent_empty_object = True
elif not self._last_arguments.endswith("}") and not self._sent_empty_object:
elif not self._sent_empty_object:
# Need to close brace
calls.append(
ToolCallItem(
Expand Down
2 changes: 1 addition & 1 deletion python/sglang/srt/function_call/glm4_moe_detector.py
Original file line number Diff line number Diff line change
Expand Up @@ -566,7 +566,7 @@ def parse_streaming_increment(
)
)
self._last_arguments += empty_object
elif not self._last_arguments.endswith("}"):
else:
closing_brace = "}"
calls.append(
ToolCallItem(
Expand Down
43 changes: 6 additions & 37 deletions python/sglang/srt/function_call/kimik3_structural_tag.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Any, Dict, List, Literal, Optional, Set, Tuple, Union
from typing import Any, Dict, List, Literal, Optional, Tuple, Union

from xgrammar import StructuralTag
from xgrammar.structural_tag import (
Expand Down Expand Up @@ -29,6 +29,7 @@
TOOLS_CLOSE,
TOOLS_OPEN,
)
from sglang.srt.function_call.utils import resolve_local_json_schema_refs

_JSON_TYPES = (
"string",
Expand Down Expand Up @@ -108,41 +109,16 @@ def _matches_json_type(value: Any, json_type: str) -> bool:
)


def _resolve_local_ref(
ref: str, root_schema: Dict[str, Any]
) -> Optional[Union[bool, Dict[str, Any]]]:
if not ref.startswith("#/"):
return None
value: Any = root_schema
for part in ref[2:].split("/"):
key = part.replace("~1", "/").replace("~0", "~")
if not isinstance(value, dict) or key not in value:
return None
value = value[key]
if isinstance(value, (bool, dict)):
return value
return None


def _schema_types(
schema: Union[bool, Dict[str, Any]],
root_schema: Dict[str, Any],
seen_refs: Optional[Set[str]] = None,
) -> List[str]:
schema = resolve_local_json_schema_refs(schema, root_schema)
if schema is False:
return []
if schema is True:
return list(_JSON_TYPES)

ref = schema.get("$ref")
if isinstance(ref, str):
seen_refs = set() if seen_refs is None else set(seen_refs)
if ref not in seen_refs:
target = _resolve_local_ref(ref, root_schema)
if target is not None:
seen_refs.add(ref)
return _schema_types(target, root_schema, seen_refs)

schema_type = schema.get("type")
if isinstance(schema_type, str):
return [schema_type] if schema_type in _JSON_TYPES else list(_JSON_TYPES)
Expand All @@ -156,14 +132,14 @@ def _schema_types(
item
for option in options
if isinstance(option, (bool, dict))
for item in _schema_types(option, root_schema, seen_refs)
for item in _schema_types(option, root_schema)
}
return [item for item in _JSON_TYPES if item in option_types]

options = schema.get("allOf")
if isinstance(options, list):
type_sets = [
set(_schema_types(option, root_schema, seen_refs))
set(_schema_types(option, root_schema))
for option in options
if isinstance(option, (bool, dict))
]
Expand Down Expand Up @@ -214,17 +190,10 @@ def _restrict_schema_type(
json_type: str,
root_schema: Dict[str, Any],
) -> Union[bool, Dict[str, Any]]:
schema = resolve_local_json_schema_refs(schema, root_schema)
if not isinstance(schema, dict):
return {"type": json_type} if schema else False

ref = schema.get("$ref")
if isinstance(ref, str):
target = _resolve_local_ref(ref, root_schema)
if target is not None:
return _with_root_definitions(
_restrict_schema_type(target, json_type, root_schema), root_schema
)

result = dict(schema)
schema_type = result.get("type")
if isinstance(schema_type, list):
Expand Down
69 changes: 69 additions & 0 deletions python/sglang/srt/function_call/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,75 @@ def _get_tool_schema(tool: Tool) -> dict:
}


def resolve_local_json_schema_refs(
schema: Any,
root_schema: Dict[str, Any],
seen_refs: frozenset[str] = frozenset(),
) -> Any:
"""Resolve local references along a schema's type-inference paths."""
if not isinstance(schema, dict):
return schema

ref = schema.get("$ref")
if isinstance(ref, str) and ref in seen_refs:
schema = {key: value for key, value in schema.items() if key != "$ref"}
ref = None
if isinstance(ref, str) and ref.startswith("#/"):
target: Any = root_schema
for part in ref[2:].split("/"):
key = part.replace("~1", "/").replace("~0", "~")
if not isinstance(target, dict) or key not in target:
break
target = target[key]
else:
siblings = {key: value for key, value in schema.items() if key != "$ref"}
schema = {"allOf": [target, siblings]} if siblings else target
return resolve_local_json_schema_refs(
schema, root_schema, seen_refs | {ref}
)

return schema | {
keyword: [
resolve_local_json_schema_refs(branch, root_schema, seen_refs)
for branch in schema[keyword]
]
for keyword in ("anyOf", "oneOf", "allOf")
if keyword in schema
}


def get_json_schema_properties(
schema: Any,
root_schema: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
"""Collect properties declared directly or in root schema combinators."""
if root_schema is None:
if not isinstance(schema, dict):
return {}
root_schema = schema
schema = resolve_local_json_schema_refs(schema, root_schema)
if not isinstance(schema, dict):
return {}

direct_properties = {
name: resolve_local_json_schema_refs(property_schema, root_schema)
for name, property_schema in schema.get("properties", {}).items()
}
properties = direct_properties.copy()

for keyword in ("anyOf", "oneOf", "allOf"):
for branch in schema.get(keyword, []):
branch_properties = get_json_schema_properties(branch, root_schema)
Comment thread
xeophon marked this conversation as resolved.
Resolved
for name, property_schema in branch_properties.items():
if name in direct_properties:
continue
Comment thread
xeophon marked this conversation as resolved.
Resolved
if name in properties and properties[name] != property_schema:
properties[name] = {keyword: [properties[name], property_schema]}
else:
properties[name] = property_schema
Comment thread
xeophon marked this conversation as resolved.
Resolved
return properties


def infer_type_from_json_schema(schema: Dict[str, Any]) -> Optional[str]:
"""
Infer the primary type of a parameter from JSON Schema.
Expand Down
Loading
Loading