API Client

Source vllm-project/vllm.

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