chat_utils.py 18 KB

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