-
Notifications
You must be signed in to change notification settings - Fork 208
/
multimodalqna.py
335 lines (302 loc) · 14.4 KB
/
multimodalqna.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
# Copyright (C) 2024 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import base64
import json
import os
from io import BytesIO
import requests
from comps import MegaServiceEndpoint, MicroService, ServiceOrchestrator, ServiceRoleType, ServiceType
from comps.cores.proto.api_protocol import (
ChatCompletionRequest,
ChatCompletionResponse,
ChatCompletionResponseChoice,
ChatMessage,
UsageInfo,
)
from comps.cores.proto.docarray import ImageDoc, LLMParams, TextDoc, TextImageDoc
from fastapi import Request
from fastapi.responses import JSONResponse, StreamingResponse
from PIL import Image
MEGA_SERVICE_PORT = int(os.getenv("MEGA_SERVICE_PORT", 8888))
MM_EMBEDDING_SERVICE_HOST_IP = os.getenv("MM_EMBEDDING_SERVICE_HOST_IP", "0.0.0.0")
MM_EMBEDDING_PORT_MICROSERVICE = int(os.getenv("MM_EMBEDDING_PORT_MICROSERVICE", 6000))
MM_RETRIEVER_SERVICE_HOST_IP = os.getenv("MM_RETRIEVER_SERVICE_HOST_IP", "0.0.0.0")
MM_RETRIEVER_SERVICE_PORT = int(os.getenv("MM_RETRIEVER_SERVICE_PORT", 7000))
LVM_SERVICE_HOST_IP = os.getenv("LVM_SERVICE_HOST_IP", "0.0.0.0")
LVM_SERVICE_PORT = int(os.getenv("LVM_SERVICE_PORT", 9399))
WHISPER_SERVER_ENDPOINT = os.getenv("WHISPER_SERVER_ENDPOINT", "http://0.0.0.0:7066/v1/asr")
def align_inputs(self, inputs, cur_node, runtime_graph, llm_parameters_dict, **kwargs):
if self.services[cur_node].service_type == ServiceType.EMBEDDING:
if "text" in inputs and "image" in inputs:
text_doc = TextDoc(text=inputs["text"])
image_doc = ImageDoc(base64_image=inputs["image"])
inputs = TextImageDoc(text=text_doc, image=image_doc).dict()
elif "image" in inputs:
inputs = ImageDoc(base64_image=inputs["image"]).dict()
elif "text" in inputs:
inputs = TextDoc(text=inputs["text"]).dict()
return inputs
class MultimodalQnAService:
def __init__(self, host="0.0.0.0", port=8000):
self.host = host
self.port = port
ServiceOrchestrator.align_inputs = align_inputs
self.lvm_megaservice = ServiceOrchestrator()
self.megaservice = ServiceOrchestrator()
self.endpoint = str(MegaServiceEndpoint.MULTIMODAL_QNA)
def add_remote_service(self):
mm_embedding = MicroService(
name="embedding",
host=MM_EMBEDDING_SERVICE_HOST_IP,
port=MM_EMBEDDING_PORT_MICROSERVICE,
endpoint="/v1/embeddings",
use_remote_service=True,
service_type=ServiceType.EMBEDDING,
)
mm_retriever = MicroService(
name="retriever",
host=MM_RETRIEVER_SERVICE_HOST_IP,
port=MM_RETRIEVER_SERVICE_PORT,
endpoint="/v1/retrieval",
use_remote_service=True,
service_type=ServiceType.RETRIEVER,
)
lvm = MicroService(
name="lvm",
host=LVM_SERVICE_HOST_IP,
port=LVM_SERVICE_PORT,
endpoint="/v1/lvm",
use_remote_service=True,
service_type=ServiceType.LVM,
)
# for mmrag megaservice
self.megaservice.add(mm_embedding).add(mm_retriever).add(lvm)
self.megaservice.flow_to(mm_embedding, mm_retriever)
self.megaservice.flow_to(mm_retriever, lvm)
# for lvm megaservice
self.lvm_megaservice.add(lvm)
def _handle_message(self, messages):
images = []
audios = []
b64_types = {}
messages_dicts = []
decoded_audio_input = ""
if isinstance(messages, str):
prompt = messages
else:
messages_dict = {}
system_prompt = ""
prompt = ""
for message in messages:
msg_role = message["role"]
messages_dict = {}
if msg_role == "system":
system_prompt = message["content"]
elif msg_role == "user":
if type(message["content"]) == list:
# separate each media type and store accordingly
text = ""
text_list = [item["text"] for item in message["content"] if item["type"] == "text"]
text += "\n".join(text_list)
image_list = [
item["image_url"]["url"] for item in message["content"] if item["type"] == "image_url"
]
audios = [item["audio"] for item in message["content"] if item["type"] == "audio"]
if audios:
# translate audio to text. From this point forward, audio is treated like text
decoded_audio_input = self.convert_audio_to_text(audios)
b64_types["audio"] = decoded_audio_input
if text and not audios and not image_list:
messages_dict[msg_role] = text
elif audios and not text and not image_list:
messages_dict[msg_role] = decoded_audio_input
else:
messages_dict[msg_role] = (text, decoded_audio_input, image_list)
else:
messages_dict[msg_role] = message["content"]
messages_dicts.append(messages_dict)
elif msg_role == "assistant":
messages_dict[msg_role] = message["content"]
messages_dicts.append(messages_dict)
else:
raise ValueError(f"Unknown role: {msg_role}")
if system_prompt:
prompt = system_prompt + "\n"
for i, messages_dict in enumerate(messages_dicts):
for role, message in messages_dict.items():
if isinstance(message, tuple):
text, decoded_audio_input, image_list = message
if i == 0:
# do not add role for the very first message.
# this will be added by llava_server
if text:
prompt += text + "\n"
elif decoded_audio_input:
prompt += decoded_audio_input + "\n"
else:
if text:
prompt += role.upper() + ": " + text + "\n"
elif decoded_audio_input:
prompt += role.upper() + ": " + decoded_audio_input + "\n"
else:
prompt += role.upper() + ":"
if image_list:
for img in image_list:
# URL
if img.startswith("http://") or img.startswith("https://"):
response = requests.get(img)
image = Image.open(BytesIO(response.content)).convert("RGBA")
image_bytes = BytesIO()
image.save(image_bytes, format="PNG")
img_b64_str = base64.b64encode(image_bytes.getvalue()).decode()
# Local Path
elif os.path.exists(img):
image = Image.open(img).convert("RGBA")
image_bytes = BytesIO()
image.save(image_bytes, format="PNG")
img_b64_str = base64.b64encode(image_bytes.getvalue()).decode()
# Bytes
else:
img_b64_str = img
images.append(img_b64_str)
elif isinstance(message, str):
if i == 0:
# do not add role for the very first message.
# this will be added by llava_server
if message:
prompt += message + "\n"
else:
if message:
prompt += role.upper() + ": " + message + "\n"
else:
prompt += role.upper() + ":"
if images:
b64_types["image"] = images
# If the query has multiple media types, return all types
if prompt and b64_types:
return prompt, b64_types
else:
return prompt
def convert_audio_to_text(self, audio):
# translate audio to text by passing in base64 encoded audio to ASR
if isinstance(audio, dict):
input_dict = {"audio": audio["audio"][0]}
else:
input_dict = {"audio": audio[0]}
response = requests.post(WHISPER_SERVER_ENDPOINT, data=json.dumps(input_dict))
if response.status_code != 200:
return JSONResponse(
status_code=503, content={"message": "Unable to convert audio to text. {}".format(response.text)}
)
response = response.json()
return response["asr_result"]
async def handle_request(self, request: Request):
data = await request.json()
stream_opt = bool(data.get("stream", False))
if stream_opt:
print("[ MultimodalQnAService ] stream=True not used, this has not support stream yet!")
stream_opt = False
chat_request = ChatCompletionRequest.model_validate(data)
# Multimodal RAG QnA With Videos has not yet accepts image as input during QnA.
num_messages = len(data["messages"]) if isinstance(data["messages"], list) else 1
messages = self._handle_message(chat_request.messages)
decoded_audio_input = ""
if num_messages > 1:
# This is a follow up query, go to LVM
cur_megaservice = self.lvm_megaservice
if isinstance(messages, tuple):
prompt, b64_types = messages
if "audio" in b64_types:
# for metadata storage purposes
decoded_audio_input = b64_types["audio"]
if "image" in b64_types:
initial_inputs = {"prompt": prompt, "image": b64_types["image"][0]}
else:
initial_inputs = {"prompt": prompt, "image": ""}
else:
prompt = messages
initial_inputs = {"prompt": prompt, "image": ""}
else:
# This is the first query. Ignore image input
cur_megaservice = self.megaservice
if isinstance(messages, tuple):
prompt, b64_types = messages
if "audio" in b64_types:
# for metadata storage purposes
decoded_audio_input = b64_types["audio"]
else:
prompt = messages
initial_inputs = {"text": prompt}
parameters = LLMParams(
max_new_tokens=chat_request.max_tokens if chat_request.max_tokens else 1024,
top_k=chat_request.top_k if chat_request.top_k else 10,
top_p=chat_request.top_p if chat_request.top_p else 0.95,
temperature=chat_request.temperature if chat_request.temperature else 0.01,
frequency_penalty=chat_request.frequency_penalty if chat_request.frequency_penalty else 0.0,
presence_penalty=chat_request.presence_penalty if chat_request.presence_penalty else 0.0,
repetition_penalty=chat_request.repetition_penalty if chat_request.repetition_penalty else 1.03,
stream=stream_opt,
chat_template=chat_request.chat_template if chat_request.chat_template else None,
)
result_dict, runtime_graph = await cur_megaservice.schedule(
initial_inputs=initial_inputs, llm_parameters=parameters
)
for node, response in result_dict.items():
# the last microservice in this megaservice is LVM.
# checking if LVM returns StreamingResponse
# Currently, LVM with LLAVA has not yet supported stream.
# @TODO: Will need to test this once LVM with LLAVA supports stream
if (
isinstance(response, StreamingResponse)
and node == runtime_graph.all_leaves()[-1]
and self.megaservice.services[node].service_type == ServiceType.LVM
):
return response
last_node = runtime_graph.all_leaves()[-1]
if "text" in result_dict[last_node].keys():
response = result_dict[last_node]["text"]
else:
# text is not in response message
# something wrong, for example due to empty retrieval results
if "detail" in result_dict[last_node].keys():
response = result_dict[last_node]["detail"]
else:
response = "The server failed to generate an answer to your query!"
if "metadata" in result_dict[last_node].keys():
# from retrieval results
metadata = result_dict[last_node]["metadata"]
if decoded_audio_input:
metadata["audio"] = decoded_audio_input
else:
# follow-up question, no retrieval
if decoded_audio_input:
metadata = {"audio": decoded_audio_input}
else:
metadata = None
choices = []
usage = UsageInfo()
choices.append(
ChatCompletionResponseChoice(
index=0,
message=ChatMessage(role="assistant", content=response),
finish_reason="stop",
metadata=metadata,
)
)
return ChatCompletionResponse(model="multimodalqna", choices=choices, usage=usage)
def start(self):
self.service = MicroService(
self.__class__.__name__,
service_role=ServiceRoleType.MEGASERVICE,
host=self.host,
port=self.port,
endpoint=self.endpoint,
input_datatype=ChatCompletionRequest,
output_datatype=ChatCompletionResponse,
)
self.service.add_route(self.endpoint, self.handle_request, methods=["POST"])
self.service.start()
if __name__ == "__main__":
mmragwithvideos = MultimodalQnAService(port=MEGA_SERVICE_PORT)
mmragwithvideos.add_remote_service()
mmragwithvideos.start()