chat_utils.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. import codecs
  2. import tempfile
  3. from dataclasses import dataclass
  4. from functools import lru_cache
  5. from typing import (Awaitable, Iterable, List, Optional, Tuple, Union, cast,
  6. final)
  7. import requests
  8. from loguru import logger
  9. # yapf conflicts with isort for this block
  10. # yapf: disable
  11. from openai.types.chat import ChatCompletionContentPartImageParam
  12. from openai.types.chat import (
  13. ChatCompletionContentPartParam as OpenAIChatCompletionContentPartParam)
  14. from openai.types.chat import ChatCompletionContentPartTextParam
  15. from openai.types.chat import (
  16. ChatCompletionMessageParam as OpenAIChatCompletionMessageParam)
  17. # yapf: enable
  18. # pydantic needs the TypedDict from typing_extensions
  19. from pydantic import ConfigDict
  20. from transformers import PreTrainedTokenizer
  21. from typing_extensions import Required, TypedDict
  22. from aphrodite.common.config import ModelConfig
  23. from aphrodite.multimodal import MultiModalDataDict
  24. from aphrodite.multimodal.utils import async_get_and_parse_image
  25. class CustomChatCompletionContentPartParam(TypedDict, total=False):
  26. __pydantic_config__ = ConfigDict(extra="allow") # type: ignore
  27. type: Required[str]
  28. """The type of the content part."""
  29. ChatCompletionContentPartParam = Union[OpenAIChatCompletionContentPartParam,
  30. CustomChatCompletionContentPartParam]
  31. class CustomChatCompletionMessageParam(TypedDict, total=False):
  32. """Enables custom roles in the Chat Completion API."""
  33. role: Required[str]
  34. """The role of the message's author."""
  35. content: Union[str, List[ChatCompletionContentPartParam]]
  36. """The contents of the message."""
  37. name: str
  38. """An optional name for the participant.
  39. Provides the model information to differentiate between participants of the
  40. same role.
  41. """
  42. ChatCompletionMessageParam = Union[OpenAIChatCompletionMessageParam,
  43. CustomChatCompletionMessageParam]
  44. @final # So that it should be compatible with Dict[str, str]
  45. class ConversationMessage(TypedDict):
  46. role: str
  47. content: str
  48. @dataclass(frozen=True)
  49. class ChatMessageParseResult:
  50. messages: List[ConversationMessage]
  51. mm_futures: List[Awaitable[MultiModalDataDict]]
  52. def load_chat_template(chat_template: Optional[str]) -> Optional[str]:
  53. if chat_template is None:
  54. return None
  55. try:
  56. if chat_template.startswith(('http')):
  57. response = requests.get(chat_template)
  58. temp = tempfile.NamedTemporaryFile(delete=False)
  59. temp.write(response.content)
  60. temp.close()
  61. chat_template = temp.name
  62. with open(chat_template, "r") as f:
  63. resolved_chat_template = f.read()
  64. except OSError as e:
  65. JINJA_CHARS = "{}\n"
  66. if not any(c in chat_template for c in JINJA_CHARS):
  67. msg = (f"The supplied chat template ({chat_template}) "
  68. "looks like a file path, but it failed to be "
  69. f"opened. Reason: {e}")
  70. raise ValueError(msg) from e
  71. # If opening a file fails, set chat template to be args to
  72. # ensure we decode so our escape are interpreted correctly
  73. resolved_chat_template = codecs.decode(chat_template, "unicode_escape")
  74. logger.info(f"Using supplied chat template:\n{resolved_chat_template}")
  75. return resolved_chat_template
  76. @lru_cache(maxsize=None)
  77. def _image_token_str(model_config: ModelConfig,
  78. tokenizer: PreTrainedTokenizer) -> Optional[str]:
  79. # TODO: Let user specify how to insert image tokens into prompt
  80. # (similar to chat template)
  81. model_type = model_config.hf_config.model_type
  82. if model_type == "phi3_v":
  83. # Workaround since this token is not defined in the tokenizer
  84. return "<|image_1|>"
  85. if model_type == "minicpmv":
  86. return "(<image>./</image>)"
  87. if model_type in ("blip-2", "chatglm", "fuyu", "paligemma"):
  88. # These models do not use image tokens in the prompt
  89. return None
  90. if model_type.startswith("llava"):
  91. return tokenizer.decode(model_config.hf_config.image_token_index)
  92. if model_type in ("chameleon", "internvl_chat"):
  93. return "<image>"
  94. raise TypeError(f"Unknown model type: {model_type}")
  95. # TODO: Let user specify how to insert image tokens into prompt
  96. # (similar to chat template)
  97. def _get_full_image_text_prompt(image_token_str: str, text_prompt: str) -> str:
  98. """Combine image and text prompts for vision language model"""
  99. # NOTE: For now we assume all model architectures use the same
  100. # image + text prompt format. This may change in the future.
  101. return f"{image_token_str}\n{text_prompt}"
  102. def _parse_chat_message_content_parts(
  103. role: str,
  104. parts: Iterable[ChatCompletionContentPartParam],
  105. model_config: ModelConfig,
  106. tokenizer: PreTrainedTokenizer,
  107. ) -> ChatMessageParseResult:
  108. texts: List[str] = []
  109. mm_futures: List[Awaitable[MultiModalDataDict]] = []
  110. for part in parts:
  111. part_type = part["type"]
  112. if part_type == "text":
  113. text = cast(ChatCompletionContentPartTextParam, part)["text"]
  114. texts.append(text)
  115. elif part_type == "image_url":
  116. if len(mm_futures) > 0:
  117. raise NotImplementedError(
  118. "Multiple 'image_url' input is currently not supported.")
  119. image_url = cast(ChatCompletionContentPartImageParam,
  120. part)["image_url"]
  121. if image_url.get("detail", "auto") != "auto":
  122. logger.warning(
  123. "'image_url.detail' is currently not supported and "
  124. "will be ignored.")
  125. image_future = async_get_and_parse_image(image_url["url"])
  126. mm_futures.append(image_future)
  127. else:
  128. raise NotImplementedError(f"Unknown part type: {part_type}")
  129. text_prompt = "\n".join(texts)
  130. if mm_futures:
  131. image_token_str = _image_token_str(model_config, tokenizer)
  132. if image_token_str is not None:
  133. if image_token_str in text_prompt:
  134. logger.warning(
  135. "Detected image token string in the text prompt. "
  136. "Skipping prompt formatting.")
  137. else:
  138. text_prompt = _get_full_image_text_prompt(
  139. image_token_str=image_token_str,
  140. text_prompt=text_prompt,
  141. )
  142. messages = [ConversationMessage(role=role, content=text_prompt)]
  143. return ChatMessageParseResult(messages=messages, mm_futures=mm_futures)
  144. def _parse_chat_message_content(
  145. message: ChatCompletionMessageParam,
  146. model_config: ModelConfig,
  147. tokenizer: PreTrainedTokenizer,
  148. ) -> ChatMessageParseResult:
  149. role = message["role"]
  150. content = message.get("content")
  151. if content is None:
  152. return ChatMessageParseResult(messages=[], mm_futures=[])
  153. if isinstance(content, str):
  154. messages = [ConversationMessage(role=role, content=content)]
  155. return ChatMessageParseResult(messages=messages, mm_futures=[])
  156. return _parse_chat_message_content_parts(role, content, model_config,
  157. tokenizer)
  158. def parse_chat_messages(
  159. messages: List[ChatCompletionMessageParam],
  160. model_config: ModelConfig,
  161. tokenizer: PreTrainedTokenizer,
  162. ) -> Tuple[List[ConversationMessage], List[Awaitable[MultiModalDataDict]]]:
  163. conversation: List[ConversationMessage] = []
  164. mm_futures: List[Awaitable[MultiModalDataDict]] = []
  165. for msg in messages:
  166. parse_result = _parse_chat_message_content(msg, model_config,
  167. tokenizer)
  168. conversation.extend(parse_result.messages)
  169. mm_futures.extend(parse_result.mm_futures)
  170. return conversation, mm_futures