| 1 | # SPDX-License-Identifier: Apache-2.0 |
| 2 | # SPDX-FileCopyrightText: Copyright contributors to the vLLM project |
| 3 | |
| 4 | """Example online usage of Pooling API for multi vector retrieval. |
| 5 | |
| 6 | Run `vllm serve <model> --runner pooling` |
| 7 | to start up the server in vLLM. e.g. |
| 8 | |
| 9 | vllm serve BAAI/bge-m3 --pooler-config.task token_embed |
| 10 | """ |
| 11 | |
| 12 | import argparse |
| 13 | import pprint |
| 14 | |
| 15 | import requests |
| 16 | import torch |
| 17 | |
| 18 | |
| 19 | def post_http_request(prompt: dict, api_url: str) -> requests.Response: |
| 20 | headers = {"User-Agent": "Test Client"} |
| 21 | response = requests.post(api_url, headers=headers, json=prompt) |
| 22 | return response |
| 23 | |
| 24 | |
| 25 | def parse_args(): |
| 26 | parser = argparse.ArgumentParser() |
| 27 | parser.add_argument("--host", type=str, default="localhost") |
| 28 | parser.add_argument("--port", type=int, default=8000) |
| 29 | parser.add_argument("--model", type=str, default="BAAI/bge-m3") |
| 30 | |
| 31 | return parser.parse_args() |
| 32 | |
| 33 | |
| 34 | def main(args): |
| 35 | pooling_url = f"http://{args.host}:{args.port}/pooling" |
| 36 | score_url = f"http://{args.host}:{args.port}/score" |
| 37 | model_name = args.model |
| 38 | |
| 39 | prompts = [ |
| 40 | "Hello, my name is", |
| 41 | "The president of the United States is", |
| 42 | "The capital of France is", |
| 43 | "The future of AI is", |
| 44 | ] |
| 45 | prompt = {"model": model_name, "input": prompts} |
| 46 | |
| 47 | pooling_response = post_http_request(prompt=prompt, api_url=pooling_url) |
| 48 | for output in pooling_response.json()["data"]: |
| 49 | multi_vector = torch.tensor(output["data"]) |
| 50 | print(multi_vector.shape) |
| 51 | |
| 52 | queries = "What is the capital of France?" |
| 53 | documents = [ |
| 54 | "The capital of Brazil is Brasilia.", |
| 55 | "The capital of France is Paris.", |
| 56 | ] |
| 57 | prompt = {"model": model_name, "queries": queries, "documents": documents} |
| 58 | score_response = post_http_request(prompt=prompt, api_url=score_url) |
| 59 | print("\nPrompt when queries is string and documents is a list:") |
| 60 | pprint.pprint(prompt) |
| 61 | print("\nScore Response:") |
| 62 | pprint.pprint(score_response.json()) |
| 63 | |
| 64 | |
| 65 | if __name__ == "__main__": |
| 66 | args = parse_args() |
| 67 | main(args) |