chat_utils.py 8.25 KB
Newer Older
1
import codecs
2
from dataclasses import dataclass
3
from functools import lru_cache
4
from pathlib import Path
5
from typing import Any, Awaitable, Iterable, List, Optional, Tuple, Union, cast
6

7
8
9
10
11
12
13
14
15
16
17
# yapf conflicts with isort for this block
# yapf: disable
from openai.types.chat import ChatCompletionContentPartImageParam
from openai.types.chat import (
    ChatCompletionContentPartParam as OpenAIChatCompletionContentPartParam)
from openai.types.chat import ChatCompletionContentPartTextParam
from openai.types.chat import (
    ChatCompletionMessageParam as OpenAIChatCompletionMessageParam)
# yapf: enable
# pydantic needs the TypedDict from typing_extensions
from pydantic import ConfigDict
18
from transformers import PreTrainedTokenizer
19
from typing_extensions import Required, TypedDict
20

21
from vllm.config import ModelConfig
22
23
24
from vllm.logger import init_logger
from vllm.multimodal import MultiModalDataDict
from vllm.multimodal.utils import async_get_and_parse_image
25
from vllm.transformers_utils.tokenizer import AnyTokenizer
26
27
28
29

logger = init_logger(__name__)


30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
class CustomChatCompletionContentPartParam(TypedDict, total=False):
    __pydantic_config__ = ConfigDict(extra="allow")  # type: ignore

    type: Required[str]
    """The type of the content part."""


ChatCompletionContentPartParam = Union[OpenAIChatCompletionContentPartParam,
                                       CustomChatCompletionContentPartParam]


class CustomChatCompletionMessageParam(TypedDict, total=False):
    """Enables custom roles in the Chat Completion API."""
    role: Required[str]
    """The role of the message's author."""

    content: Union[str, List[ChatCompletionContentPartParam]]
    """The contents of the message."""

    name: str
    """An optional name for the participant.

    Provides the model information to differentiate between participants of the
    same role.
    """


ChatCompletionMessageParam = Union[OpenAIChatCompletionMessageParam,
                                   CustomChatCompletionMessageParam]


61
# TODO: Make fields ReadOnly once mypy supports it
62
63
64
65
66
67
68
69
class ConversationMessage(TypedDict):
    role: str
    content: str


@dataclass(frozen=True)
class ChatMessageParseResult:
    messages: List[ConversationMessage]
70
    mm_futures: List[Awaitable[MultiModalDataDict]]
71
72


73
74
def load_chat_template(
        chat_template: Optional[Union[Path, str]]) -> Optional[str]:
75
76
77
78
79
80
    if chat_template is None:
        return None
    try:
        with open(chat_template, "r") as f:
            resolved_chat_template = f.read()
    except OSError as e:
81
82
83
        if isinstance(chat_template, Path):
            raise

84
85
86
87
88
89
        JINJA_CHARS = "{}\n"
        if not any(c in chat_template for c in JINJA_CHARS):
            msg = (f"The supplied chat template ({chat_template}) "
                   f"looks like a file path, but it failed to be "
                   f"opened. Reason: {e}")
            raise ValueError(msg) from e
90

91
92
93
        # If opening a file fails, set chat template to be args to
        # ensure we decode so our escape are interpreted correctly
        resolved_chat_template = codecs.decode(chat_template, "unicode_escape")
94

95
96
    logger.info("Using supplied chat template:\n%s", resolved_chat_template)
    return resolved_chat_template
97
98
99


@lru_cache(maxsize=None)
100
101
def _image_token_str(model_config: ModelConfig,
                     tokenizer: PreTrainedTokenizer) -> Optional[str]:
102
103
    # TODO: Let user specify how to insert image tokens into prompt
    # (similar to chat template)
104
    model_type = model_config.hf_config.model_type
105
106
107
    if model_type == "phi3_v":
        # Workaround since this token is not defined in the tokenizer
        return "<|image_1|>"
108
109
110
    if model_type == "minicpmv":
        return "(<image>./</image>)"
    if model_type in ("blip-2", "chatglm", "fuyu", "paligemma"):
111
112
113
        # These models do not use image tokens in the prompt
        return None
    if model_type.startswith("llava"):
114
        return tokenizer.decode(model_config.hf_config.image_token_index)
115
    if model_type in ("chameleon", "internvl_chat"):
116
        return "<image>"
117
    raise TypeError(f"Unknown model type: {model_type}")
118
119
120
121


# TODO: Let user specify how to insert image tokens into prompt
# (similar to chat template)
122
def _get_full_image_text_prompt(image_token_str: str, text_prompt: str) -> str:
123
124
125
126
127
128
129
130
131
132
    """Combine image and text prompts for vision language model"""

    # NOTE: For now we assume all model architectures use the same
    # image + text prompt format. This may change in the future.
    return f"{image_token_str}\n{text_prompt}"


def _parse_chat_message_content_parts(
    role: str,
    parts: Iterable[ChatCompletionContentPartParam],
133
134
    model_config: ModelConfig,
    tokenizer: PreTrainedTokenizer,
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
) -> ChatMessageParseResult:
    texts: List[str] = []
    mm_futures: List[Awaitable[MultiModalDataDict]] = []

    for part in parts:
        part_type = part["type"]
        if part_type == "text":
            text = cast(ChatCompletionContentPartTextParam, part)["text"]
            texts.append(text)
        elif part_type == "image_url":
            if len(mm_futures) > 0:
                raise NotImplementedError(
                    "Multiple 'image_url' input is currently not supported.")

            image_url = cast(ChatCompletionContentPartImageParam,
                             part)["image_url"]

            if image_url.get("detail", "auto") != "auto":
                logger.warning(
                    "'image_url.detail' is currently not supported and "
                    "will be ignored.")

            image_future = async_get_and_parse_image(image_url["url"])
            mm_futures.append(image_future)
        else:
            raise NotImplementedError(f"Unknown part type: {part_type}")

    text_prompt = "\n".join(texts)

    if mm_futures:
165
        image_token_str = _image_token_str(model_config, tokenizer)
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
        if image_token_str is not None:
            if image_token_str in text_prompt:
                logger.warning(
                    "Detected image token string in the text prompt. "
                    "Skipping prompt formatting.")
            else:
                text_prompt = _get_full_image_text_prompt(
                    image_token_str=image_token_str,
                    text_prompt=text_prompt,
                )

    messages = [ConversationMessage(role=role, content=text_prompt)]

    return ChatMessageParseResult(messages=messages, mm_futures=mm_futures)


182
def _parse_chat_message_content(
183
    message: ChatCompletionMessageParam,
184
185
    model_config: ModelConfig,
    tokenizer: PreTrainedTokenizer,
186
187
188
189
190
191
192
193
194
195
) -> ChatMessageParseResult:
    role = message["role"]
    content = message.get("content")

    if content is None:
        return ChatMessageParseResult(messages=[], mm_futures=[])
    if isinstance(content, str):
        messages = [ConversationMessage(role=role, content=content)]
        return ChatMessageParseResult(messages=messages, mm_futures=[])

196
197
    return _parse_chat_message_content_parts(role, content, model_config,
                                             tokenizer)
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215


def parse_chat_messages(
    messages: List[ChatCompletionMessageParam],
    model_config: ModelConfig,
    tokenizer: PreTrainedTokenizer,
) -> Tuple[List[ConversationMessage], List[Awaitable[MultiModalDataDict]]]:
    conversation: List[ConversationMessage] = []
    mm_futures: List[Awaitable[MultiModalDataDict]] = []

    for msg in messages:
        parse_result = _parse_chat_message_content(msg, model_config,
                                                   tokenizer)

        conversation.extend(parse_result.messages)
        mm_futures.extend(parse_result.mm_futures)

    return conversation, mm_futures
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240


def apply_chat_template(
    tokenizer: AnyTokenizer,
    conversation: List[ConversationMessage],
    chat_template: Optional[str],
    *,
    tokenize: bool = False,  # Different from HF's default
    **kwargs: Any,
) -> str:
    if chat_template is None and tokenizer.chat_template is None:
        raise ValueError(
            "As of transformers v4.44, default chat template is no longer "
            "allowed, so you must provide a chat template if the tokenizer "
            "does not define one.")

    prompt = tokenizer.apply_chat_template(
        conversation=conversation,
        chat_template=chat_template,
        tokenize=tokenize,
        **kwargs,
    )
    assert isinstance(prompt, str)

    return prompt