chat_utils.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. import asyncio
  2. import codecs
  3. import json
  4. from abc import ABC, abstractmethod
  5. from collections import defaultdict
  6. from functools import lru_cache, partial
  7. from pathlib import Path
  8. from typing import (Any, Awaitable, Dict, Generic, Iterable, List, Literal,
  9. Mapping, Optional, Tuple, TypeVar, Union, cast)
  10. from loguru import logger
  11. # yapf conflicts with isort for this block
  12. # yapf: disable
  13. from openai.types.chat import (ChatCompletionAssistantMessageParam,
  14. ChatCompletionContentPartImageParam)
  15. from openai.types.chat import (
  16. ChatCompletionContentPartParam as OpenAIChatCompletionContentPartParam)
  17. from openai.types.chat import (ChatCompletionContentPartRefusalParam,
  18. ChatCompletionContentPartTextParam)
  19. from openai.types.chat import (
  20. ChatCompletionMessageParam as OpenAIChatCompletionMessageParam)
  21. from openai.types.chat import (ChatCompletionMessageToolCallParam,
  22. ChatCompletionToolMessageParam)
  23. # yapf: enable
  24. # pydantic needs the TypedDict from typing_extensions
  25. from pydantic import ConfigDict
  26. from transformers import PreTrainedTokenizer, PreTrainedTokenizerFast
  27. from typing_extensions import Required, TypeAlias, TypedDict
  28. from aphrodite.common.config import ModelConfig
  29. from aphrodite.multimodal import MultiModalDataDict
  30. from aphrodite.multimodal.utils import (async_get_and_parse_audio,
  31. async_get_and_parse_image,
  32. get_and_parse_audio,
  33. get_and_parse_image)
  34. from aphrodite.transformers_utils.tokenizer import (AnyTokenizer,
  35. MistralTokenizer)
  36. class AudioURL(TypedDict, total=False):
  37. url: Required[str]
  38. """
  39. Either a URL of the audio or a data URL with base64 encoded audio data.
  40. """
  41. class ChatCompletionContentPartAudioParam(TypedDict, total=False):
  42. audio_url: Required[AudioURL]
  43. type: Required[Literal["audio_url"]]
  44. """The type of the content part."""
  45. class CustomChatCompletionContentPartParam(TypedDict, total=False):
  46. __pydantic_config__ = ConfigDict(extra="allow") # type: ignore
  47. type: Required[str]
  48. """The type of the content part."""
  49. ChatCompletionContentPartParam: TypeAlias = Union[
  50. OpenAIChatCompletionContentPartParam, ChatCompletionContentPartAudioParam,
  51. ChatCompletionContentPartRefusalParam,
  52. CustomChatCompletionContentPartParam]
  53. class CustomChatCompletionMessageParam(TypedDict, total=False):
  54. """Enables custom roles in the Chat Completion API."""
  55. role: Required[str]
  56. """The role of the message's author."""
  57. content: Union[str, List[ChatCompletionContentPartParam]]
  58. """The contents of the message."""
  59. name: str
  60. """An optional name for the participant.
  61. Provides the model information to differentiate between participants of the
  62. same role.
  63. """
  64. tool_call_id: Optional[str]
  65. """Tool call that this message is responding to."""
  66. tool_calls: Optional[Iterable[ChatCompletionMessageToolCallParam]]
  67. """The tool calls generated by the model, such as function calls."""
  68. ChatCompletionMessageParam = Union[OpenAIChatCompletionMessageParam,
  69. CustomChatCompletionMessageParam]
  70. # TODO: Make fields ReadOnly once mypy supports it
  71. class ConversationMessage(TypedDict, total=False):
  72. role: Required[str]
  73. """The role of the message's author."""
  74. content: Optional[str]
  75. """The contents of the message"""
  76. tool_call_id: Optional[str]
  77. """Tool call that this message is responding to."""
  78. name: Optional[str]
  79. """The name of the function to call"""
  80. tool_calls: Optional[Iterable[ChatCompletionMessageToolCallParam]]
  81. """The tool calls generated by the model, such as function calls."""
  82. ModalityStr = Literal["image", "audio", "video"]
  83. _T = TypeVar("_T")
  84. class BaseMultiModalItemTracker(ABC, Generic[_T]):
  85. """
  86. Tracks multi-modal items in a given request and ensures that the number
  87. of multi-modal items in a given request does not exceed the configured
  88. maximum per prompt.
  89. """
  90. def __init__(self, model_config: ModelConfig, tokenizer: AnyTokenizer):
  91. super().__init__()
  92. self._model_config = model_config
  93. self._tokenizer = tokenizer
  94. self._allowed_items = (model_config.multimodal_config.limit_per_prompt
  95. if model_config.multimodal_config else {})
  96. self._consumed_items = {k: 0 for k in self._allowed_items}
  97. self._items: List[_T] = []
  98. @staticmethod
  99. @lru_cache(maxsize=None)
  100. def _cached_token_str(tokenizer: AnyTokenizer, token_index: int) -> str:
  101. return tokenizer.decode(token_index)
  102. def _placeholder_str(self, modality: ModalityStr,
  103. current_count: int) -> Optional[str]:
  104. # TODO: Let user specify how to insert image tokens into prompt
  105. # (similar to chat template)
  106. hf_config = self._model_config.hf_config
  107. model_type = hf_config.model_type
  108. if modality == "image":
  109. if model_type == "phi3_v":
  110. # Workaround since this token is not defined in the tokenizer
  111. return f"<|image_{current_count}|>"
  112. if model_type == "minicpmv":
  113. return "(<image>./</image>)"
  114. if model_type in ("blip-2", "chatglm", "fuyu", "paligemma",
  115. "pixtral"):
  116. # These models do not use image tokens in the prompt
  117. return None
  118. if model_type == "qwen":
  119. return f"Picture {current_count}: <img></img>"
  120. if model_type.startswith("llava"):
  121. return self._cached_token_str(self._tokenizer,
  122. hf_config.image_token_index)
  123. if model_type in ("chameleon", "internvl_chat"):
  124. return "<image>"
  125. if model_type == "qwen2_vl":
  126. return "<|vision_start|><|image_pad|><|vision_end|>"
  127. raise TypeError(f"Unknown model type: {model_type}")
  128. elif modality == "audio":
  129. if model_type == "ultravox":
  130. return "<|reserved_special_token_0|>"
  131. raise TypeError(f"Unknown model type: {model_type}")
  132. elif modality == "video":
  133. if model_type == "qwen2_vl":
  134. return "<|vision_start|><|video_pad|><|vision_end|>"
  135. raise TypeError(f"Unknown model type: {model_type}")
  136. else:
  137. raise TypeError(f"Unknown modality: {modality}")
  138. @staticmethod
  139. def _combine(items: List[MultiModalDataDict]) -> MultiModalDataDict:
  140. mm_lists: Mapping[str, List[object]] = defaultdict(list)
  141. # Merge all the multi-modal items
  142. for single_mm_data in items:
  143. for mm_key, mm_item in single_mm_data.items():
  144. if isinstance(mm_item, list):
  145. mm_lists[mm_key].extend(mm_item)
  146. else:
  147. mm_lists[mm_key].append(mm_item)
  148. # Unpack any single item lists for models that don't expect multiple.
  149. return {
  150. mm_key: mm_list[0] if len(mm_list) == 1 else mm_list
  151. for mm_key, mm_list in mm_lists.items()
  152. }
  153. def add(self, modality: ModalityStr, item: _T) -> Optional[str]:
  154. """
  155. Add a multi-modal item to the current prompt and returns the
  156. placeholder string to use, if any.
  157. """
  158. allowed_count = self._allowed_items.get(modality, 1)
  159. current_count = self._consumed_items.get(modality, 0) + 1
  160. if current_count > allowed_count:
  161. raise ValueError(
  162. f"At most {allowed_count} {modality}(s) may be provided in "
  163. "one request.")
  164. self._consumed_items[modality] = current_count
  165. self._items.append(item)
  166. return self._placeholder_str(modality, current_count)
  167. @abstractmethod
  168. def create_parser(self) -> "BaseMultiModalContentParser":
  169. raise NotImplementedError
  170. class MultiModalItemTracker(BaseMultiModalItemTracker[MultiModalDataDict]):
  171. def all_mm_data(self) -> Optional[MultiModalDataDict]:
  172. return self._combine(self._items) if self._items else None
  173. def create_parser(self) -> "BaseMultiModalContentParser":
  174. return MultiModalContentParser(self)
  175. class AsyncMultiModalItemTracker(
  176. BaseMultiModalItemTracker[Awaitable[MultiModalDataDict]]):
  177. async def all_mm_data(self) -> Optional[MultiModalDataDict]:
  178. if self._items:
  179. items = await asyncio.gather(*self._items)
  180. return self._combine(items)
  181. return None
  182. def create_parser(self) -> "BaseMultiModalContentParser":
  183. return AsyncMultiModalContentParser(self)
  184. class BaseMultiModalContentParser(ABC):
  185. def __init__(self) -> None:
  186. super().__init__()
  187. # multimodal placeholder_string : count
  188. self._placeholder_counts: Dict[str, int] = defaultdict(lambda: 0)
  189. def _add_placeholder(self, placeholder: Optional[str]):
  190. if placeholder:
  191. self._placeholder_counts[placeholder] += 1
  192. def mm_placeholder_counts(self) -> Dict[str, int]:
  193. return dict(self._placeholder_counts)
  194. @abstractmethod
  195. def parse_image(self, image_url: str) -> None:
  196. raise NotImplementedError
  197. @abstractmethod
  198. def parse_audio(self, audio_url: str) -> None:
  199. raise NotImplementedError
  200. class MultiModalContentParser(BaseMultiModalContentParser):
  201. def __init__(self, tracker: MultiModalItemTracker) -> None:
  202. super().__init__()
  203. self._tracker = tracker
  204. def parse_image(self, image_url: str) -> None:
  205. image = get_and_parse_image(image_url)
  206. placeholder = self._tracker.add("image", image)
  207. self._add_placeholder(placeholder)
  208. def parse_audio(self, audio_url: str) -> None:
  209. audio = get_and_parse_audio(audio_url)
  210. placeholder = self._tracker.add("audio", audio)
  211. self._add_placeholder(placeholder)
  212. class AsyncMultiModalContentParser(BaseMultiModalContentParser):
  213. def __init__(self, tracker: AsyncMultiModalItemTracker) -> None:
  214. super().__init__()
  215. self._tracker = tracker
  216. def parse_image(self, image_url: str) -> None:
  217. image_coro = async_get_and_parse_image(image_url)
  218. placeholder = self._tracker.add("image", image_coro)
  219. self._add_placeholder(placeholder)
  220. def parse_audio(self, audio_url: str) -> None:
  221. audio_coro = async_get_and_parse_audio(audio_url)
  222. placeholder = self._tracker.add("audio", audio_coro)
  223. self._add_placeholder(placeholder)
  224. def load_chat_template(
  225. chat_template: Optional[Union[Path, str]]) -> Optional[str]:
  226. if chat_template is None:
  227. return None
  228. try:
  229. with open(chat_template, "r") as f:
  230. resolved_chat_template = f.read()
  231. except OSError as e:
  232. if isinstance(chat_template, Path):
  233. raise
  234. JINJA_CHARS = "{}\n"
  235. if not any(c in chat_template for c in JINJA_CHARS):
  236. msg = (f"The supplied chat template ({chat_template}) "
  237. f"looks like a file path, but it failed to be "
  238. f"opened. Reason: {e}")
  239. raise ValueError(msg) from e
  240. # If opening a file fails, set chat template to be args to
  241. # ensure we decode so our escape are interpreted correctly
  242. resolved_chat_template = codecs.decode(chat_template, "unicode_escape")
  243. logger.info("Using supplied chat template:\n%s", resolved_chat_template)
  244. return resolved_chat_template
  245. # TODO: Let user specify how to insert multimodal tokens into prompt
  246. # (similar to chat template)
  247. def _get_full_multimodal_text_prompt(placeholder_counts: Dict[str, int],
  248. text_prompt: str) -> str:
  249. """Combine multimodal prompts for a multimodal language model."""
  250. # Look through the text prompt to check for missing placeholders
  251. missing_placeholders: List[str] = []
  252. for placeholder in placeholder_counts:
  253. # For any existing placeholder in the text prompt, we leave it as is
  254. placeholder_counts[placeholder] -= text_prompt.count(placeholder)
  255. if placeholder_counts[placeholder] < 0:
  256. raise ValueError(
  257. f"Found more '{placeholder}' placeholders in input prompt than "
  258. "actual multimodal data items.")
  259. missing_placeholders.extend([placeholder] *
  260. placeholder_counts[placeholder])
  261. # NOTE: For now we always add missing placeholders at the front of
  262. # the prompt. This may change to be customizable in the future.
  263. return "\n".join(missing_placeholders + [text_prompt])
  264. # No need to validate using Pydantic again
  265. _TextParser = partial(cast, ChatCompletionContentPartTextParam)
  266. _ImageParser = partial(cast, ChatCompletionContentPartImageParam)
  267. _AudioParser = partial(cast, ChatCompletionContentPartAudioParam)
  268. _RefusalParser = partial(cast, ChatCompletionContentPartRefusalParam)
  269. def _parse_chat_message_content_parts(
  270. role: str,
  271. parts: Iterable[ChatCompletionContentPartParam],
  272. mm_tracker: BaseMultiModalItemTracker,
  273. ) -> List[ConversationMessage]:
  274. texts: List[str] = []
  275. mm_parser = mm_tracker.create_parser()
  276. for part in parts:
  277. part_type = part["type"]
  278. if part_type == "text":
  279. text = _TextParser(part)["text"]
  280. texts.append(text)
  281. elif part_type == "image_url":
  282. image_url = _ImageParser(part)["image_url"]
  283. if image_url.get("detail", "auto") != "auto":
  284. logger.warning(
  285. "'image_url.detail' is currently not supported and "
  286. "will be ignored.")
  287. mm_parser.parse_image(image_url["url"])
  288. elif part_type == "audio_url":
  289. audio_url = _AudioParser(part)["audio_url"]
  290. mm_parser.parse_audio(audio_url["url"])
  291. elif part_type == "refusal":
  292. text = _RefusalParser(part)["refusal"]
  293. texts.append(text)
  294. else:
  295. raise NotImplementedError(f"Unknown part type: {part_type}")
  296. text_prompt = "\n".join(texts)
  297. mm_placeholder_counts = mm_parser.mm_placeholder_counts()
  298. if mm_placeholder_counts:
  299. text_prompt = _get_full_multimodal_text_prompt(mm_placeholder_counts,
  300. text_prompt)
  301. return [ConversationMessage(role=role, content=text_prompt)]
  302. # No need to validate using Pydantic again
  303. _AssistantParser = partial(cast, ChatCompletionAssistantMessageParam)
  304. _ToolParser = partial(cast, ChatCompletionToolMessageParam)
  305. def _parse_chat_message_content(
  306. message: ChatCompletionMessageParam,
  307. mm_tracker: BaseMultiModalItemTracker,
  308. ) -> List[ConversationMessage]:
  309. role = message["role"]
  310. content = message.get("content")
  311. if content is None:
  312. content = []
  313. elif isinstance(content, str):
  314. content = [
  315. ChatCompletionContentPartTextParam(type="text", text=content)
  316. ]
  317. result = _parse_chat_message_content_parts(
  318. role,
  319. content, # type: ignore
  320. mm_tracker,
  321. )
  322. for result_msg in result:
  323. if role == 'assistant':
  324. parsed_msg = _AssistantParser(message)
  325. if "tool_calls" in parsed_msg:
  326. result_msg["tool_calls"] = list(parsed_msg["tool_calls"])
  327. elif role == "tool":
  328. parsed_msg = _ToolParser(message)
  329. if "tool_call_id" in parsed_msg:
  330. result_msg["tool_call_id"] = parsed_msg["tool_call_id"]
  331. if "name" in message and isinstance(message["name"], str):
  332. result_msg["name"] = message["name"]
  333. return result
  334. def _postprocess_messages(messages: List[ConversationMessage]) -> None:
  335. # per the Transformers docs & maintainers, tool call arguments in
  336. # assistant-role messages with tool_calls need to be dicts not JSON str -
  337. # this is how tool-use chat templates will expect them moving forwards
  338. # so, for messages that have tool_calls, parse the string (which we get
  339. # from openAI format) to dict
  340. for message in messages:
  341. if (message["role"] == "assistant" and "tool_calls" in message
  342. and isinstance(message["tool_calls"], list)):
  343. for item in message["tool_calls"]:
  344. item["function"]["arguments"] = json.loads(
  345. item["function"]["arguments"])
  346. def parse_chat_messages(
  347. messages: List[ChatCompletionMessageParam],
  348. model_config: ModelConfig,
  349. tokenizer: AnyTokenizer,
  350. ) -> Tuple[List[ConversationMessage], Optional[MultiModalDataDict]]:
  351. conversation: List[ConversationMessage] = []
  352. mm_tracker = MultiModalItemTracker(model_config, tokenizer)
  353. for msg in messages:
  354. sub_messages = _parse_chat_message_content(msg, mm_tracker)
  355. conversation.extend(sub_messages)
  356. _postprocess_messages(conversation)
  357. return conversation, mm_tracker.all_mm_data()
  358. def parse_chat_messages_futures(
  359. messages: List[ChatCompletionMessageParam],
  360. model_config: ModelConfig,
  361. tokenizer: AnyTokenizer,
  362. ) -> Tuple[List[ConversationMessage], Awaitable[Optional[MultiModalDataDict]]]:
  363. conversation: List[ConversationMessage] = []
  364. mm_tracker = AsyncMultiModalItemTracker(model_config, tokenizer)
  365. for msg in messages:
  366. sub_messages = _parse_chat_message_content(msg, mm_tracker)
  367. conversation.extend(sub_messages)
  368. _postprocess_messages(conversation)
  369. return conversation, mm_tracker.all_mm_data()
  370. def apply_hf_chat_template(
  371. tokenizer: Union[PreTrainedTokenizer, PreTrainedTokenizerFast],
  372. conversation: List[ConversationMessage],
  373. chat_template: Optional[str],
  374. *,
  375. tokenize: bool = False, # Different from HF's default
  376. **kwargs: Any,
  377. ) -> str:
  378. if chat_template is None and tokenizer.chat_template is None:
  379. raise ValueError(
  380. "As of transformers v4.44, default chat template is no longer "
  381. "allowed, so you must provide a chat template if the tokenizer "
  382. "does not define one.")
  383. return tokenizer.apply_chat_template(
  384. conversation=conversation, # type: ignore[arg-type]
  385. chat_template=chat_template,
  386. tokenize=tokenize,
  387. **kwargs,
  388. )
  389. def apply_mistral_chat_template(
  390. tokenizer: MistralTokenizer,
  391. messages: List[ChatCompletionMessageParam],
  392. chat_template: Optional[str] = None,
  393. **kwargs: Any,
  394. ) -> List[int]:
  395. if chat_template is not None:
  396. logger.warning(
  397. "'chat_template' cannot be overridden for mistral tokenizer.")
  398. return tokenizer.apply_chat_template(
  399. messages=messages,
  400. **kwargs,
  401. )