| 1 | # SPDX-License-Identifier: Apache-2.0 |
| 2 | # SPDX-FileCopyrightText: Copyright contributors to the vLLM project |
| 3 | """Example Python client for embedding API using vLLM API server |
| 4 | NOTE: |
| 5 | start a supported embeddings model server with `vllm serve`, e.g. |
| 6 | vllm serve intfloat/e5-small |
| 7 | """ |
| 8 | |
| 9 | import argparse |
| 10 | |
| 11 | import pybase64 as base64 |
| 12 | import requests |
| 13 | import torch |
| 14 | |
| 15 | from vllm.utils.serial_utils import EMBED_DTYPES, ENDIANNESS, binary2tensor |
| 16 | |
| 17 | |
| 18 | def post_http_request(prompt: dict, api_url: str) -> requests.Response: |
| 19 | headers = {"User-Agent": "Test Client"} |
| 20 | response = requests.post(api_url, headers=headers, json=prompt) |
| 21 | return response |
| 22 | |
| 23 | |
| 24 | def parse_args(): |
| 25 | parse = argparse.ArgumentParser() |
| 26 | parse.add_argument("--host", type=str, default="localhost") |
| 27 | parse.add_argument("--port", type=int, default=8000) |
| 28 | return parse.parse_args() |
| 29 | |
| 30 | |
| 31 | def main(args): |
| 32 | base_url = f"http://{args.host}:{args.port}" |
| 33 | models_url = base_url + "/v1/models" |
| 34 | embeddings_url = base_url + "/v1/embeddings" |
| 35 | |
| 36 | response = requests.get(models_url) |
| 37 | model = response.json()["data"][0]["id"] |
| 38 | |
| 39 | input_texts = [ |
| 40 | "The best thing about vLLM is that it supports many different models", |
| 41 | ] * 2 |
| 42 | |
| 43 | # The OpenAI client does not support the embed_dtype and endianness parameters. |
| 44 | for embed_dtype in EMBED_DTYPES: |
| 45 | for endianness in ENDIANNESS: |
| 46 | prompt = { |
| 47 | "model": model, |
| 48 | "input": input_texts, |
| 49 | "encoding_format": "base64", |
| 50 | "embed_dtype": embed_dtype, |
| 51 | "endianness": endianness, |
| 52 | } |
| 53 | response = post_http_request(prompt=prompt, api_url=embeddings_url) |
| 54 | |
| 55 | embedding = [] |
| 56 | for data in response.json()["data"]: |
| 57 | binary = base64.b64decode(data["embedding"]) |
| 58 | tensor = binary2tensor(binary, (-1,), embed_dtype, endianness) |
| 59 | embedding.append(tensor.to(torch.float32)) |
| 60 | embedding = torch.stack(embedding) |
| 61 | print(embed_dtype, endianness, embedding.shape) |
| 62 | |
| 63 | |
| 64 | if __name__ == "__main__": |
| 65 | args = parse_args() |
| 66 | main(args) |