| 1 | # SPDX-License-Identifier: Apache-2.0 |
| 2 | # SPDX-FileCopyrightText: Copyright contributors to the vLLM project |
| 3 | """Example Python client for classification API using vLLM API server |
| 4 | NOTE: |
| 5 | start a supported classification model server with `vllm serve`, e.g. |
| 6 | vllm serve jason9693/Qwen2.5-1.5B-apeach |
| 7 | """ |
| 8 | |
| 9 | import argparse |
| 10 | import pprint |
| 11 | |
| 12 | import requests |
| 13 | |
| 14 | headers = {"accept": "application/json", "Content-Type": "application/json"} |
| 15 | |
| 16 | |
| 17 | def parse_args(): |
| 18 | parse = argparse.ArgumentParser() |
| 19 | parse.add_argument("--host", type=str, default="localhost") |
| 20 | parse.add_argument("--port", type=int, default=8000) |
| 21 | return parse.parse_args() |
| 22 | |
| 23 | |
| 24 | def main(args): |
| 25 | base_url = f"http://{args.host}:{args.port}" |
| 26 | models_url = base_url + "/v1/models" |
| 27 | classify_url = base_url + "/classify" |
| 28 | tokenize_url = base_url + "/tokenize" |
| 29 | |
| 30 | response = requests.get(models_url, headers=headers) |
| 31 | model = response.json()["data"][0]["id"] |
| 32 | |
| 33 | # /classify can accept str as input |
| 34 | prompts = [ |
| 35 | "Hello, my name is", |
| 36 | "The president of the United States is", |
| 37 | "The capital of France is", |
| 38 | "The future of AI is", |
| 39 | ] |
| 40 | |
| 41 | payload = { |
| 42 | "model": model, |
| 43 | "input": prompts, |
| 44 | } |
| 45 | response = requests.post(classify_url, headers=headers, json=payload) |
| 46 | pprint.pprint(response.json()) |
| 47 | |
| 48 | # /classify can accept token ids as input |
| 49 | token_ids = [] |
| 50 | for prompt in prompts: |
| 51 | response = requests.post( |
| 52 | tokenize_url, |
| 53 | json={"model": model, "prompt": prompt}, |
| 54 | ) |
| 55 | token_ids.append(response.json()["tokens"]) |
| 56 | |
| 57 | payload = { |
| 58 | "model": model, |
| 59 | "input": token_ids, |
| 60 | } |
| 61 | response = requests.post(classify_url, headers=headers, json=payload) |
| 62 | pprint.pprint(response.json()) |
| 63 | |
| 64 | |
| 65 | if __name__ == "__main__": |
| 66 | args = parse_args() |
| 67 | main(args) |