Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
101 changes: 101 additions & 0 deletions tests/entrypoints/tool_parsers/test_functiongemma_tool_parser.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import json

import pytest
import regex as re

from tests.utils import RemoteOpenAIServer

MODEL = "unsloth/functiongemma-270m-it"
START = "<start_function_call>"
END = "<end_function_call>"
TOOLS = [
{
"type": "function",
"function": {
"name": name,
"description": name,
"parameters": {"type": "object", "properties": {}},
},
}
for name in ("set_alarm", "get_weather", "get_time")
]


@pytest.fixture(scope="module")
def server():
args = [
"--enforce-eager",
"--enable-auto-tool-choice",
"--tool-call-parser",
"functiongemma",
"--max-model-len",
"2048",
"--max-num-seqs",
"2",
"--gpu-memory-utilization",
"0.05",
]
with RemoteOpenAIServer(MODEL, args, max_wait_seconds=480) as server:
yield server


def _tool_calls(server, output, stream, stream_interval=None):
"""Pin the model output with a regex, so only serving and parsing are tested."""
extra_body = {"structured_outputs": {"regex": re.escape(output)}}
if stream_interval is not None:
extra_body["stream_interval"] = stream_interval
with server.get_client() as client:
response = client.chat.completions.create(
model=MODEL,
messages=[{"role": "user", "content": "Call the tools."}],
tools=TOOLS,
tool_choice="auto",
temperature=0,
max_tokens=128,
stream=stream,
extra_body=extra_body,
)
if not stream:
calls = response.choices[0].message.tool_calls or []
return [(c.function.name, json.loads(c.function.arguments)) for c in calls]
streamed: dict[int, dict] = {}
for chunk in response:
for call in chunk.choices[0].delta.tool_calls or []:
entry = streamed.setdefault(call.index, {"name": None, "args": ""})
entry["name"] = entry["name"] or call.function.name
entry["args"] += call.function.arguments or ""
return [(e["name"], json.loads(e["args"])) for _, e in sorted(streamed.items())]


@pytest.mark.parametrize("stream", [False, True])
@pytest.mark.parametrize(
("args", "expected"),
[
(
"days:[<escape>mon<escape>],enabled:true,hour:7",
{"days": ["mon"], "enabled": True, "hour": 7},
),
("", {}),
],
ids=["non_string_arguments", "no_arguments"],
)
def test_arguments_reach_the_client(server, stream, args, expected):
output = f"{START}call:set_alarm{{{args}}}{END}"
assert _tool_calls(server, output, stream) == [("set_alarm", expected)]


@pytest.mark.parametrize("stream_interval", [2, 3, 4])
def test_streamed_call_closes_when_next_call_starts_in_same_delta(
server, stream_interval
):
"""These intervals merge the first call's end tag and the second's start tag."""
output = (
f"{START}call:get_weather{{city:<escape>Paris<escape>}}{END}"
f"{START}call:get_time{{tz:<escape>UTC<escape>}}{END}"
)
assert _tool_calls(server, output, True, stream_interval) == [
("get_weather", {"city": "Paris"}),
("get_time", {"tz": "UTC"}),
]
167 changes: 167 additions & 0 deletions tests/tool_parsers/test_functiongemma_tool_parser.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project

import json
from unittest.mock import MagicMock

import pytest
import regex as re

from vllm.entrypoints.openai.chat_completion.protocol import ChatCompletionRequest
from vllm.tool_parsers.functiongemma_tool_parser import FunctionGemmaToolParser
Expand Down Expand Up @@ -121,6 +123,171 @@ def test_argument_with_spaces(self, parser):
assert result == {"message": "Hello World"}


# Rendered by the model's chat template (``format_argument``): only strings are
# ``<escape>``-delimited; booleans, numbers, arrays and objects are bare.
TEMPLATE_CALL = (
"<start_function_call>call:set_alarm{"
"days:[<escape>mon<escape>,<escape>tue<escape>],enabled:true,hour:7,"
"label:<escape>Wake up<escape>,snooze:{minutes:5}}"
"<end_function_call>"
)
TEMPLATE_ARGS = {
"days": ["mon", "tue"],
"enabled": True,
"hour": 7,
"label": "Wake up",
"snooze": {"minutes": 5},
}

_START = "<start_function_call>"
_END = "<end_function_call>"
_TAG_RE = re.compile(f"({_START}|{_END})")


def _chunks(text: str, size: int) -> list[str]:
"""Split ``text`` into ``size``-character chunks, keeping the tags whole.

The tags are single special tokens, so a delta never splits them.
"""
chunks = []
for part in _TAG_RE.split(text):
if _TAG_RE.fullmatch(part):
chunks.append(part)
else:
chunks.extend(part[i : i + size] for i in range(0, len(part), size))
return [chunk for chunk in chunks if chunk]


def _stream(parser, request, text: str, size: int) -> list[tuple[str, dict]]:
return _stream_deltas(parser, request, _chunks(text, size))


def _stream_deltas(parser, request, deltas: list[str]) -> list[tuple[str, dict]]:
"""Reassemble streamed tool calls as a client would: by index."""
previous = ""
calls: dict[int, dict] = {}
for i, chunk in enumerate(deltas, start=1):
current = previous + chunk
delta = parser.extract_tool_calls_streaming(
previous, current, chunk, [], [i], [i], request
)
previous = current
for call in (delta.tool_calls if delta else None) or []:
entry = calls.setdefault(call.index, {"name": None, "arguments": ""})
if call.function.name:
entry["name"] = call.function.name
entry["arguments"] += call.function.arguments or ""
return [
(entry["name"], json.loads(entry["arguments"]))
for _, entry in sorted(calls.items())
]


class TestTemplateArgumentTypes:
"""Regression tests for #63983: bare (non-string) arguments were dropped."""

def test_non_streaming_keeps_every_argument(self, parser, mock_request):
result = parser.extract_tool_calls(TEMPLATE_CALL, mock_request)

assert result.tools_called is True
assert json.loads(result.tool_calls[0].function.arguments) == TEMPLATE_ARGS

@pytest.mark.parametrize("size", [1, 3, 1000])
def test_streaming_keeps_every_argument(self, parser, mock_request, size):
assert _stream(parser, mock_request, TEMPLATE_CALL, size) == [
("set_alarm", TEMPLATE_ARGS)
]

@pytest.mark.parametrize("size", [1, 1000])
def test_streaming_multiple_arguments_reassemble_to_json(
self, parser, mock_request, size
):
"""The closing brace is held back until the call ends, so the
concatenated deltas of a multi-argument call form one JSON object."""
text = (
"<start_function_call>call:get_weather{"
"location:<escape>San Francisco<escape>,unit:<escape>celsius<escape>}"
"<end_function_call>"
"<start_function_call>call:set_alarm{hour:7,snooze:{minutes:5}}"
"<end_function_call>"
)
assert _stream(parser, mock_request, text, size) == [
("get_weather", {"location": "San Francisco", "unit": "celsius"}),
("set_alarm", {"hour": 7, "snooze": {"minutes": 5}}),
]

@pytest.mark.parametrize(
"first_call_deltas",
[
["city:<escape>Paris<escape>", "}", _END + _START],
["city:<escape>Paris<escape>", "}" + _END + _START],
["city:<escape>Paris<escape>}" + _END + _START],
],
)
def test_streaming_closes_call_when_next_starts_in_same_delta(
self, parser, mock_request, first_call_deltas
):
"""Deltas merge when the client falls behind the engine, so one call's
end tag can share a delta with the next call's start tag."""
deltas = [
_START,
"call:get_weather{",
*first_call_deltas,
"call:get_time{",
"tz:<escape>UTC<escape>",
"}",
_END,
]
assert _stream_deltas(parser, mock_request, deltas) == [
("get_weather", {"city": "Paris"}),
("get_time", {"tz": "UTC"}),
]

@pytest.mark.parametrize("size", [1, 1000])
def test_streaming_call_without_arguments_sends_empty_object(
self, parser, mock_request, size
):
text = f"{_START}call:get_time{{}}{_END}"
assert _stream(parser, mock_request, text, size) == [("get_time", {})]

def test_escaped_strings_keep_delimiters(self, parser):
args = "note:<escape>a, b: {c} [d]<escape>,count:2"
assert parser._parse_arguments(args) == {"note": "a, b: {c} [d]", "count": 2}

def test_nested_containers_and_literals(self, parser):
args = "cfg:{on:false,ids:[1,[2,3],{k:<escape>v<escape>}],none:None},f:1.5"
assert parser._parse_arguments(args) == {
"cfg": {"on": False, "ids": [1, [2, 3], {"k": "v"}], "none": None},
"f": 1.5,
}

@pytest.mark.parametrize(
("prefix", "expected"),
[
("hour:7", {}),
("hour:7,", {"hour": 7}),
("hour:7,label:<escape>Wake", {"hour": 7}),
("hour:7,days:[<escape>mon<escape>", {"hour": 7}),
("hour:7,snooze:{minutes:5", {"hour": 7}),
("hour:7,snooze:{minutes:5}", {"hour": 7, "snooze": {"minutes": 5}}),
],
)
def test_partial_parsing_holds_back_incomplete_values(
self, parser, prefix, expected
):
assert parser._parse_arguments(prefix, partial=True) == expected

@pytest.mark.parametrize(
"args",
["a:1,items:[1}", "a:1,cfg:{x:1]", "a:1,b:,c:2", "a:1,b:}"],
)
@pytest.mark.parametrize("partial", [False, True])
def test_mismatched_delimiters_stop_parsing(self, parser, args, partial):
"""A stray closing brace must not spin the parser; the arguments
parsed before it are kept and the rest is dropped."""
assert parser._parse_arguments(args, partial=partial) == {"a": 1}


class TestAdjustRequest:
def test_skip_special_tokens_disabled(self, parser, mock_request):
mock_request.tools = [{"type": "function", "function": {"name": "test"}}]
Expand Down
Loading