API Client#

Source vllm-project/vllm.

 1"""Example Python client for `vllm.entrypoints.api_server`
 2NOTE: The API server is used only for demonstration and simple performance
 3benchmarks. It is not intended for production use.
 4For production use, we recommend `vllm serve` and the OpenAI client API.
 5"""
 6
 7import argparse
 8import json
 9from typing import Iterable, List
10
11import requests
12
13
14def clear_line(n: int = 1) -> None:
15    LINE_UP = '\033[1A'
16    LINE_CLEAR = '\x1b[2K'
17    for _ in range(n):
18        print(LINE_UP, end=LINE_CLEAR, flush=True)
19
20
21def post_http_request(prompt: str,
22                      api_url: str,
23                      n: int = 1,
24                      stream: bool = False) -> requests.Response:
25    headers = {"User-Agent": "Test Client"}
26    pload = {
27        "prompt": prompt,
28        "n": n,
29        "use_beam_search": True,
30        "temperature": 0.0,
31        "max_tokens": 16,
32        "stream": stream,
33    }
34    response = requests.post(api_url, headers=headers, json=pload, stream=True)
35    return response
36
37
38def get_streaming_response(response: requests.Response) -> Iterable[List[str]]:
39    for chunk in response.iter_lines(chunk_size=8192,
40                                     decode_unicode=False,
41                                     delimiter=b"\0"):
42        if chunk:
43            data = json.loads(chunk.decode("utf-8"))
44            output = data["text"]
45            yield output
46
47
48def get_response(response: requests.Response) -> List[str]:
49    data = json.loads(response.content)
50    output = data["text"]
51    return output
52
53
54if __name__ == "__main__":
55    parser = argparse.ArgumentParser()
56    parser.add_argument("--host", type=str, default="localhost")
57    parser.add_argument("--port", type=int, default=8000)
58    parser.add_argument("--n", type=int, default=4)
59    parser.add_argument("--prompt", type=str, default="San Francisco is a")
60    parser.add_argument("--stream", action="store_true")
61    args = parser.parse_args()
62    prompt = args.prompt
63    api_url = f"http://{args.host}:{args.port}/generate"
64    n = args.n
65    stream = args.stream
66
67    print(f"Prompt: {prompt!r}\n", flush=True)
68    response = post_http_request(prompt, api_url, n, stream)
69
70    if stream:
71        num_printed_lines = 0
72        for h in get_streaming_response(response):
73            clear_line(num_printed_lines)
74            num_printed_lines = 0
75            for i, line in enumerate(h):
76                num_printed_lines += 1
77                print(f"Beam candidate {i}: {line!r}", flush=True)
78    else:
79        output = get_response(response)
80        for i, line in enumerate(output):
81            print(f"Beam candidate {i}: {line!r}", flush=True)