|
| 1 | +# |
| 2 | +# Copyright 2023 The LLM-on-Ray Authors. |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | +# |
| 16 | +from typing import List, Union |
| 17 | + |
| 18 | +from llm_on_ray.inference.api_openai_backend.openai_protocol import ChatMessage |
| 19 | + |
| 20 | + |
| 21 | +class ChatTemplatePreprocess: |
| 22 | + def __init__(self, predictor) -> None: |
| 23 | + self.predictor = predictor |
| 24 | + |
| 25 | + def get_prompt(self, input: List, is_mllm=False): |
| 26 | + """Generate response based on input.""" |
| 27 | + if self.predictor.infer_conf.model_description.chat_template is not None: |
| 28 | + self.predictor.tokenizer.chat_template = ( |
| 29 | + self.predictor.infer_conf.model_description.chat_template |
| 30 | + ) |
| 31 | + elif self.predictor.tokenizer.chat_template is None: |
| 32 | + self.predictor.tokenizer.chat_template = ( |
| 33 | + self.predictor.infer_conf.model_description.default_chat_template |
| 34 | + ) |
| 35 | + |
| 36 | + if is_mllm: |
| 37 | + if isinstance(input, List): |
| 38 | + if isinstance(input, list) and input and isinstance(input[0], ChatMessage): |
| 39 | + messages = [] |
| 40 | + for chat_message in input: |
| 41 | + message = { |
| 42 | + "role": chat_message.role, |
| 43 | + "content": chat_message.content, |
| 44 | + } |
| 45 | + messages.append(message) |
| 46 | + texts, images = self._extract_messages(messages) |
| 47 | + elif isinstance(input, list) and input and isinstance(input[0], dict): |
| 48 | + texts, images = self._extract_messages(input) |
| 49 | + elif isinstance(input, list) and input and isinstance(input[0], list): |
| 50 | + texts, images = [self._extract_messages(p) for p in input] |
| 51 | + |
| 52 | + image = self._prepare_image(images) |
| 53 | + prompt = self.predictor.tokenizer.apply_chat_template(texts, tokenize=False) |
| 54 | + return prompt, image |
| 55 | + else: |
| 56 | + if isinstance(input, list) and input and isinstance(input[0], dict): |
| 57 | + prompt = self.predictor.tokenizer.apply_chat_template(input, tokenize=False) |
| 58 | + elif isinstance(input, list) and input and isinstance(input[0], list): |
| 59 | + prompt = [ |
| 60 | + self.predictor.tokenizer.apply_chat_template(t, tokenize=False) for t in input |
| 61 | + ] |
| 62 | + elif isinstance(input, list) and input and isinstance(input[0], ChatMessage): |
| 63 | + messages = [] |
| 64 | + for chat_message in input: |
| 65 | + message = {"role": chat_message.role, "content": chat_message.content} |
| 66 | + messages.append(message) |
| 67 | + prompt = self.predictor.tokenizer.apply_chat_template(messages, tokenize=False) |
| 68 | + elif isinstance(input, list) and input and isinstance(input[0], str): |
| 69 | + prompt = input |
| 70 | + elif isinstance(input, str): |
| 71 | + prompt = input |
| 72 | + else: |
| 73 | + raise TypeError( |
| 74 | + f"Unsupported type {type(input)} for text. Expected dict or list of dicts." |
| 75 | + ) |
| 76 | + return prompt |
| 77 | + |
| 78 | + def _extract_messages(self, messages): |
| 79 | + texts, images = [], [] |
| 80 | + for message in messages: |
| 81 | + if message["role"] == "user" and isinstance(message["content"], list): |
| 82 | + texts.append({"role": "user", "content": message["content"][0]["text"]}) |
| 83 | + images.append( |
| 84 | + {"role": "user", "content": message["content"][1]["image_url"]["url"]} |
| 85 | + ) |
| 86 | + else: |
| 87 | + texts.append(message) |
| 88 | + return texts, images |
| 89 | + |
| 90 | + def _prepare_image(self, messages: list): |
| 91 | + """Prepare image from history messages.""" |
| 92 | + from PIL import Image |
| 93 | + import requests |
| 94 | + from io import BytesIO |
| 95 | + import base64 |
| 96 | + import re |
| 97 | + |
| 98 | + # prepare images |
| 99 | + images: List = [] |
| 100 | + if isinstance(messages[0], List): |
| 101 | + for i in range(len(messages)): |
| 102 | + for msg in messages[i]: |
| 103 | + msg = dict(msg) |
| 104 | + content = msg["content"] |
| 105 | + if "url" not in content: |
| 106 | + continue |
| 107 | + is_data = len(re.findall("^data:image/.+;base64,", content["url"])) > 0 |
| 108 | + if is_data: |
| 109 | + encoded_str = re.sub("^data:image/.+;base64,", "", content["url"]) |
| 110 | + images[i].append(Image.open(BytesIO(base64.b64decode(encoded_str)))) |
| 111 | + else: |
| 112 | + images[i].append(Image.open(requests.get(content["url"], stream=True).raw)) |
| 113 | + elif isinstance(messages[0], dict): |
| 114 | + for msg in messages: |
| 115 | + msg = dict(msg) |
| 116 | + content = msg["content"] |
| 117 | + if "url" not in content: |
| 118 | + continue |
| 119 | + is_data = len(re.findall("^data:image/.+;base64,", content["url"])) > 0 |
| 120 | + if is_data: |
| 121 | + encoded_str = re.sub("^data:image/.+;base64,", "", content["url"]) |
| 122 | + images.append(Image.open(BytesIO(base64.b64decode(encoded_str)))) |
| 123 | + else: |
| 124 | + images.append(Image.open(requests.get(content["url"], stream=True).raw)) |
| 125 | + |
| 126 | + return images |
0 commit comments