| 1 | # SPDX-License-Identifier: Apache-2.0 |
| 2 | # SPDX-FileCopyrightText: Copyright contributors to the vLLM project |
| 3 | |
| 4 | import json |
| 5 | from collections.abc import Sequence |
| 6 | from typing import Any |
| 7 | |
| 8 | import regex as re |
| 9 | from transformers import PreTrainedTokenizerBase |
| 10 | |
| 11 | from vllm.entrypoints.chat_utils import make_tool_call_id |
| 12 | from vllm.entrypoints.generate.base.protocol import ( |
| 13 | DeltaMessage, |
| 14 | ExtractedToolCallInformation, |
| 15 | FunctionCall, |
| 16 | ToolCall, |
| 17 | ) |
| 18 | from vllm.entrypoints.openai.chat_completion.protocol import ( |
| 19 | ChatCompletionRequest, |
| 20 | ) |
| 21 | from vllm.logger import init_logger |
| 22 | from vllm.tool_parsers.abstract_tool_parser import ( |
| 23 | Tool, |
| 24 | ToolParser, |
| 25 | ) |
| 26 | |
| 27 | logger = init_logger(__name__) |
| 28 | |
| 29 | |
| 30 | class Phi4MiniJsonToolParser(ToolParser): |
| 31 | """Tool call parser for phi-4-mini models intended for use with the |
| 32 | examples/tool_chat_template_llama.jinja template. |
| 33 | |
| 34 | Used when --enable-auto-tool-choice --tool-call-parser phi4_mini_json |
| 35 | are all set |
| 36 | """ |
| 37 | |
| 38 | def __init__( |
| 39 | self, |
| 40 | tokenizer: PreTrainedTokenizerBase, |
| 41 | tools: list[Tool] | None = None, |
| 42 | ) -> None: |
| 43 | super().__init__(tokenizer, tools) |
| 44 | |
| 45 | # initialize properties used for state when parsing tool calls in |
| 46 | # streaming mode |
| 47 | self.prev_tool_call_arr: list[dict[str, Any]] = [] |
| 48 | self.current_tool_id: int = -1 |
| 49 | self.streamed_args_for_tool: list[ |
| 50 | str |
| 51 | ] = [] # map what has been streamed for each tool so far to a list |
| 52 | self.bot_token: str = "functools" |
| 53 | |
| 54 | def extract_tool_calls( |
| 55 | self, model_output: str, request: ChatCompletionRequest |
| 56 | ) -> ExtractedToolCallInformation: |
| 57 | """Extract the tool calls from a complete model response.""" |
| 58 | logger.debug("Model output: %s", model_output) |
| 59 | |
| 60 | pattern = r"functools\[(.*?)\]" |
| 61 | matches = re.search(pattern, model_output, re.DOTALL) |
| 62 | |
| 63 | if not matches: |
| 64 | logger.debug("No function calls found") |
| 65 | return ExtractedToolCallInformation( |
| 66 | tools_called=False, tool_calls=[], content=model_output |
| 67 | ) |
| 68 | |
| 69 | try: |
| 70 | function_call_arr: list[dict[str, Any]] = [] |
| 71 | try: |
| 72 | json_content = "[" + matches.group(1) + "]" |
| 73 | |
| 74 | function_call_arr = json.loads(json_content) |
| 75 | logger.debug( |
| 76 | "Successfully extracted %d function calls", len(function_call_arr) |
| 77 | ) |
| 78 | except json.JSONDecodeError as e: |
| 79 | logger.error( |
| 80 | "Failed to parse function calls from model output. Error: %s", |
| 81 | str(e), |
| 82 | ) |
| 83 | |
| 84 | tool_calls: list[ToolCall] = [ |
| 85 | ToolCall( |
| 86 | id=make_tool_call_id(), |
| 87 | type="function", |
| 88 | function=FunctionCall( |
| 89 | name=raw_function_call["name"], |
| 90 | # function call args are JSON but as a string |
| 91 | arguments=json.dumps( |
| 92 | raw_function_call["arguments"] |
| 93 | if "arguments" in raw_function_call |
| 94 | else raw_function_call["parameters"], |
| 95 | ensure_ascii=False, |
| 96 | ), |
| 97 | ), |
| 98 | ) |
| 99 | for raw_function_call in function_call_arr |
| 100 | ] |
| 101 | |
| 102 | # get any content before the tool call |
| 103 | ret = ExtractedToolCallInformation( |
| 104 | tools_called=True, tool_calls=tool_calls, content=None |
| 105 | ) |
| 106 | return ret |
| 107 | |
| 108 | except Exception: |
| 109 | return ExtractedToolCallInformation( |
| 110 | tools_called=False, tool_calls=[], content=model_output |
| 111 | ) |
| 112 | |
| 113 | def extract_tool_calls_streaming( |
| 114 | self, |
| 115 | previous_text: str, |
| 116 | current_text: str, |
| 117 | delta_text: str, |
| 118 | previous_token_ids: Sequence[int], |
| 119 | current_token_ids: Sequence[int], |
| 120 | delta_token_ids: Sequence[int], |
| 121 | request: ChatCompletionRequest, |
| 122 | ) -> DeltaMessage | None: |
| 123 | return None |