OpenAI Chat Completion Client For Multimodal

OpenAI Chat Completion Client For Multimodal#

Source: examples/openai_chat_completion_client_for_multimodal.py.

  1"""An example showing how to use vLLM to serve multimodal models 
  2and run online inference with OpenAI client.
  3
  4Launch the vLLM server with the following command:
  5
  6(single image inference with Llava)
  7vllm serve llava-hf/llava-1.5-7b-hf --chat-template template_llava.jinja
  8
  9(multi-image inference with Phi-3.5-vision-instruct)
 10vllm serve microsoft/Phi-3.5-vision-instruct --task generate \
 11    --trust-remote-code --max-model-len 4096 --limit-mm-per-prompt image=2
 12
 13(audio inference with Ultravox)
 14vllm serve fixie-ai/ultravox-v0_3 --max-model-len 4096
 15"""
 16import base64
 17
 18import requests
 19from openai import OpenAI
 20
 21from vllm.utils import FlexibleArgumentParser
 22
 23# Modify OpenAI's API key and API base to use vLLM's API server.
 24openai_api_key = "EMPTY"
 25openai_api_base = "http://localhost:8000/v1"
 26
 27client = OpenAI(
 28    # defaults to os.environ.get("OPENAI_API_KEY")
 29    api_key=openai_api_key,
 30    base_url=openai_api_base,
 31)
 32
 33models = client.models.list()
 34model = models.data[0].id
 35
 36
 37def encode_base64_content_from_url(content_url: str) -> str:
 38    """Encode a content retrieved from a remote url to base64 format."""
 39
 40    with requests.get(content_url) as response:
 41        response.raise_for_status()
 42        result = base64.b64encode(response.content).decode('utf-8')
 43
 44    return result
 45
 46
 47# Text-only inference
 48def run_text_only() -> None:
 49    chat_completion = client.chat.completions.create(
 50        messages=[{
 51            "role": "user",
 52            "content": "What's the capital of France?"
 53        }],
 54        model=model,
 55        max_completion_tokens=64,
 56    )
 57
 58    result = chat_completion.choices[0].message.content
 59    print("Chat completion output:", result)
 60
 61
 62# Single-image input inference
 63def run_single_image() -> None:
 64
 65    ## Use image url in the payload
 66    image_url = "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg"
 67    chat_completion_from_url = client.chat.completions.create(
 68        messages=[{
 69            "role":
 70            "user",
 71            "content": [
 72                {
 73                    "type": "text",
 74                    "text": "What's in this image?"
 75                },
 76                {
 77                    "type": "image_url",
 78                    "image_url": {
 79                        "url": image_url
 80                    },
 81                },
 82            ],
 83        }],
 84        model=model,
 85        max_completion_tokens=64,
 86    )
 87
 88    result = chat_completion_from_url.choices[0].message.content
 89    print("Chat completion output from image url:", result)
 90
 91    ## Use base64 encoded image in the payload
 92    image_base64 = encode_base64_content_from_url(image_url)
 93    chat_completion_from_base64 = client.chat.completions.create(
 94        messages=[{
 95            "role":
 96            "user",
 97            "content": [
 98                {
 99                    "type": "text",
100                    "text": "What's in this image?"
101                },
102                {
103                    "type": "image_url",
104                    "image_url": {
105                        "url": f"data:image/jpeg;base64,{image_base64}"
106                    },
107                },
108            ],
109        }],
110        model=model,
111        max_completion_tokens=64,
112    )
113
114    result = chat_completion_from_base64.choices[0].message.content
115    print("Chat completion output from base64 encoded image:", result)
116
117
118# Multi-image input inference
119def run_multi_image() -> None:
120    image_url_duck = "https://upload.wikimedia.org/wikipedia/commons/d/da/2015_Kaczka_krzy%C5%BCowka_w_wodzie_%28samiec%29.jpg"
121    image_url_lion = "https://upload.wikimedia.org/wikipedia/commons/7/77/002_The_lion_king_Snyggve_in_the_Serengeti_National_Park_Photo_by_Giles_Laurent.jpg"
122    chat_completion_from_url = client.chat.completions.create(
123        messages=[{
124            "role":
125            "user",
126            "content": [
127                {
128                    "type": "text",
129                    "text": "What are the animals in these images?"
130                },
131                {
132                    "type": "image_url",
133                    "image_url": {
134                        "url": image_url_duck
135                    },
136                },
137                {
138                    "type": "image_url",
139                    "image_url": {
140                        "url": image_url_lion
141                    },
142                },
143            ],
144        }],
145        model=model,
146        max_completion_tokens=64,
147    )
148
149    result = chat_completion_from_url.choices[0].message.content
150    print("Chat completion output:", result)
151
152
153# Video input inference
154def run_video() -> None:
155    video_url = "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerFun.mp4"
156    video_base64 = encode_base64_content_from_url(video_url)
157
158    ## Use video url in the payload
159    chat_completion_from_url = client.chat.completions.create(
160        messages=[{
161            "role":
162            "user",
163            "content": [
164                {
165                    "type": "text",
166                    "text": "What's in this video?"
167                },
168                {
169                    "type": "video_url",
170                    "video_url": {
171                        "url": video_url
172                    },
173                },
174            ],
175        }],
176        model=model,
177        max_completion_tokens=64,
178    )
179
180    result = chat_completion_from_url.choices[0].message.content
181    print("Chat completion output from image url:", result)
182
183    ## Use base64 encoded video in the payload
184    chat_completion_from_base64 = client.chat.completions.create(
185        messages=[{
186            "role":
187            "user",
188            "content": [
189                {
190                    "type": "text",
191                    "text": "What's in this video?"
192                },
193                {
194                    "type": "video_url",
195                    "video_url": {
196                        "url": f"data:video/mp4;base64,{video_base64}"
197                    },
198                },
199            ],
200        }],
201        model=model,
202        max_completion_tokens=64,
203    )
204
205    result = chat_completion_from_base64.choices[0].message.content
206    print("Chat completion output from base64 encoded image:", result)
207
208
209# Audio input inference
210def run_audio() -> None:
211    from vllm.assets.audio import AudioAsset
212
213    audio_url = AudioAsset("winning_call").url
214    audio_base64 = encode_base64_content_from_url(audio_url)
215
216    # OpenAI-compatible schema (`input_audio`)
217    chat_completion_from_base64 = client.chat.completions.create(
218        messages=[{
219            "role":
220            "user",
221            "content": [
222                {
223                    "type": "text",
224                    "text": "What's in this audio?"
225                },
226                {
227                    "type": "input_audio",
228                    "input_audio": {
229                        # Any format supported by librosa is supported
230                        "data": audio_base64,
231                        "format": "wav"
232                    },
233                },
234            ],
235        }],
236        model=model,
237        max_completion_tokens=64,
238    )
239
240    result = chat_completion_from_base64.choices[0].message.content
241    print("Chat completion output from input audio:", result)
242
243    # HTTP URL
244    chat_completion_from_url = client.chat.completions.create(
245        messages=[{
246            "role":
247            "user",
248            "content": [
249                {
250                    "type": "text",
251                    "text": "What's in this audio?"
252                },
253                {
254                    "type": "audio_url",
255                    "audio_url": {
256                        # Any format supported by librosa is supported
257                        "url": audio_url
258                    },
259                },
260            ],
261        }],
262        model=model,
263        max_completion_tokens=64,
264    )
265
266    result = chat_completion_from_url.choices[0].message.content
267    print("Chat completion output from audio url:", result)
268
269    # base64 URL
270    chat_completion_from_base64 = client.chat.completions.create(
271        messages=[{
272            "role":
273            "user",
274            "content": [
275                {
276                    "type": "text",
277                    "text": "What's in this audio?"
278                },
279                {
280                    "type": "audio_url",
281                    "audio_url": {
282                        # Any format supported by librosa is supported
283                        "url": f"data:audio/ogg;base64,{audio_base64}"
284                    },
285                },
286            ],
287        }],
288        model=model,
289        max_completion_tokens=64,
290    )
291
292    result = chat_completion_from_base64.choices[0].message.content
293    print("Chat completion output from base64 encoded audio:", result)
294
295
296example_function_map = {
297    "text-only": run_text_only,
298    "single-image": run_single_image,
299    "multi-image": run_multi_image,
300    "video": run_video,
301    "audio": run_audio,
302}
303
304
305def main(args) -> None:
306    chat_type = args.chat_type
307    example_function_map[chat_type]()
308
309
310if __name__ == "__main__":
311    parser = FlexibleArgumentParser(
312        description='Demo on using OpenAI client for online inference with '
313        'multimodal language models served with vLLM.')
314    parser.add_argument('--chat-type',
315                        '-c',
316                        type=str,
317                        default="single-image",
318                        choices=list(example_function_map.keys()),
319                        help='Conversation type with multimodal data.')
320    args = parser.parse_args()
321    main(args)