utils.py 5.68 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3

4
from collections.abc import Iterable
5

6
7
8
9
10
11
12
from vllm.entrypoints.openai.protocol import (
    ChatCompletionRequest,
    DeltaMessage,
    ExtractedToolCallInformation,
    FunctionCall,
    ToolCall,
)
13
14
15
16
17
from vllm.entrypoints.openai.tool_parsers import ToolParser


class StreamingToolReconstructor:
    def __init__(self, assert_one_tool_per_delta: bool = True):
18
        self.tool_calls: list[ToolCall] = []
19
20
21
22
23
24
25
26
        self.other_content: str = ""
        self._assert_one_tool_per_delta = assert_one_tool_per_delta

    def append_delta(self, delta: DeltaMessage):
        if delta.content is not None:
            self.other_content += delta.content
        else:
            assert delta.tool_calls, (
27
28
                "Streaming results should have either content or tool calls (or both)"
            )
29
30
31
32
33
34
        if self._assert_one_tool_per_delta:
            # Note: This isn't strictly required by the API and may not be
            # possible to adhere to depending on the token space and number of
            # tokens per streamed response from the model, but it is required
            # by tool_use tests, so we enforce it here by default also.
            assert len(delta.tool_calls) < 2, (
35
36
                "Streaming should include only one tool call per update."
            )
37
        for call_delta in delta.tool_calls:
38
            assert call_delta.type is None or call_delta.type == "function", (
39
                "Streaming tool calls should only emit function calls. Got "
40
41
42
43
44
45
46
                f"{call_delta.type}"
            )
            current_tool_call = (
                self.tool_calls[call_delta.index]
                if call_delta.index < len(self.tool_calls)
                else None
            )
47
            if current_tool_call:
48
                assert not call_delta.function.name, (
49
                    "Streaming tool calls should emit the full function name "
50
51
52
                    f"exactly once. Got {call_delta.function.name}"
                )
                assert not call_delta.id, (
53
                    "Streaming tool calls must emit function id only once. Got "
54
55
56
                    f"{call_delta.id}"
                )
                assert call_delta.index == len(self.tool_calls) - 1, (
57
                    f"Incorrect index for tool delta. Got {call_delta.index}, "
58
59
60
                    f"expected {len(self.tool_calls) - 1}"
                )
                current_tool_call.function.arguments += call_delta.function.arguments
61
62
            else:
                assert call_delta.id is not None, (
63
64
                    "Streaming tool calls must have an id on first appearance"
                )
65
                assert call_delta.function.name is not None, (
66
67
                    "Streaming tool calls must have a function name on first appearance"
                )
68
69
                assert call_delta.index == len(self.tool_calls), (
                    f"Incorrect index for tool delta. Got {call_delta.index}, "
70
71
                    f"expected {len(self.tool_calls)}"
                )
72
                self.tool_calls.append(
73
74
75
76
77
78
79
80
                    ToolCall(
                        id=call_delta.id,
                        function=FunctionCall(
                            name=call_delta.function.name,
                            arguments=call_delta.function.arguments or "",
                        ),
                    )
                )
81
82
83
84
85


def run_tool_extraction(
    tool_parser: ToolParser,
    model_output: str,
86
    request: ChatCompletionRequest | None = None,
87
88
    streaming: bool = False,
    assert_one_tool_per_delta: bool = True,
89
) -> tuple[str | None, list[ToolCall]]:
90
91
92
93
94
    if streaming:
        reconstructor = run_tool_extraction_streaming(
            tool_parser,
            model_output,
            request,
95
96
            assert_one_tool_per_delta=assert_one_tool_per_delta,
        )
97
98
        return reconstructor.other_content or None, reconstructor.tool_calls
    else:
99
        extracted = run_tool_extraction_nonstreaming(tool_parser, model_output, request)
100
101
102
103
104
105
106
        assert extracted.tools_called == bool(extracted.tool_calls)
        return extracted.content, extracted.tool_calls


def run_tool_extraction_nonstreaming(
    tool_parser: ToolParser,
    model_output: str,
107
    request: ChatCompletionRequest | None = None,
108
109
110
111
112
113
114
115
) -> ExtractedToolCallInformation:
    request = request or ChatCompletionRequest(messages=[], model="test-model")
    return tool_parser.extract_tool_calls(model_output, request)


def run_tool_extraction_streaming(
    tool_parser: ToolParser,
    model_deltas: Iterable[str],
116
    request: ChatCompletionRequest | None = None,
117
118
119
120
    assert_one_tool_per_delta: bool = True,
) -> StreamingToolReconstructor:
    request = request or ChatCompletionRequest(messages=[], model="test-model")
    reconstructor = StreamingToolReconstructor(
121
122
        assert_one_tool_per_delta=assert_one_tool_per_delta
    )
123
    previous_text = ""
124
    previous_tokens: list[int] = []
125
126
127
128
129
130
131
132
133
    for delta in model_deltas:
        token_delta = [
            tool_parser.vocab.get(token)
            for token in tool_parser.model_tokenizer.tokenize(delta)
            if token in tool_parser.vocab
        ]
        current_text = previous_text + delta
        current_tokens = previous_tokens + token_delta
        delta_message = tool_parser.extract_tool_calls_streaming(
134
135
136
137
138
139
140
141
            previous_text,
            current_text,
            delta,
            previous_tokens,
            current_tokens,
            token_delta,
            request,
        )
142
143
144
145
146
        if delta_message is not None:
            reconstructor.append_delta(delta_message)
        previous_text = current_text
        previous_tokens = current_tokens
    return reconstructor