【vLLM 学习】API 客户端

vLLM 是一款专为大语言模型推理加速而设计的框架,实现了 KV 缓存内存几乎零浪费,解决了内存管理瓶颈问题。

更多 vLLM 中文文档及教程可访问 →vllm.hyper.ai/

源代码:vllm-project/vllm

ini 复制代码
"""Example Python client for `vllm.entrypoints.api_server`
NOTE: The API server is used only for demonstration and simple performance
benchmarks. It is not intended for production use.
For production use, we recommend `vllm serve` and the OpenAI client API.
"""
"""用于 `vllm.entrypoints.api_server` 的 Python 客户端示例


注意:API 服务器仅用于演示和简单的性能基准测试。它并不适合用于生产环境。
对于生产环境,我们推荐使用 `vllm serve` 和 OpenAI 客户端 API。
"""


import argparse
import json
from typing import Iterable, List

import requests


def clear_line(n: int = 1) -> None:
    LINE_UP = '\033[1A'
    LINE_CLEAR = '\x1b[2K'
 for _ in range(n):
 print(LINE_UP, end=LINE_CLEAR, flush=True)


def post_http_request(prompt: str,
                      api_url: str,
                      n: int = 1,
                      stream: bool = False) -> requests.Response:
    headers = {"User-Agent": "Test Client"}
    pload = {
 "prompt": prompt,
 "n": n,
 "use_beam_search": True,
 "temperature": 0.0,
 "max_tokens": 16,
 "stream": stream,
 }
    response = requests.post(api_url,
                             headers=headers,
                             json=pload,
                             stream=stream)
 return response


def get_streaming_response(response: requests.Response) -> Iterable[List[str]]:
 for chunk in response.iter_lines(chunk_size=8192,
                                     decode_unicode=False,
                                     delimiter=b"\0"):
 if chunk:
            data = json.loads(chunk.decode("utf-8"))
            output = data["text"]
 yield output


def get_response(response: requests.Response) -> List[str]:
    data = json.loads(response.content)
    output = data["text"]
 return output


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--host", type=str, default="localhost")
    parser.add_argument("--port", type=int, default=8000)
    parser.add_argument("--n", type=int, default=4)
    parser.add_argument("--prompt", type=str, default="San Francisco is a")
    parser.add_argument("--stream", action="store_true")
    args = parser.parse_args()
    prompt = args.prompt
    api_url = f"http://{args.host}:{args.port}/generate"
    n = args.n
    stream = args.stream

 print(f"Prompt: {prompt!r}\n", flush=True)
    response = post_http_request(prompt, api_url, n, stream)

 if stream:
        num_printed_lines = 0
 for h in get_streaming_response(response):
            clear_line(num_printed_lines)
            num_printed_lines = 0
 for i, line in enumerate(h):
                num_printed_lines += 1
 print(f"Beam candidate {i}: {line!r}", flush=True)
 else:
        output = get_response(response)
 for i, line in enumerate(output):
 print(f"Beam candidate {i}: {line!r}", flush=True)源代码:vllm-project/vllm
"""Example Python client for `vllm.entrypoints.api_server`
NOTE: The API server is used only for demonstration and simple performance
benchmarks. It is not intended for production use.
For production use, we recommend `vllm serve` and the OpenAI client API.
"""
"""用于 `vllm.entrypoints.api_server` 的 Python 客户端示例


注意:API 服务器仅用于演示和简单的性能基准测试。它并不适合用于生产环境。
对于生产环境,我们推荐使用 `vllm serve` 和 OpenAI 客户端 API。
"""


import argparse
import json
from typing import Iterable, List

import requests


def clear_line(n: int = 1) -> None:
    LINE_UP = '\033[1A'
    LINE_CLEAR = '\x1b[2K'
 for _ in range(n):
 print(LINE_UP, end=LINE_CLEAR, flush=True)


def post_http_request(prompt: str,
                      api_url: str,
                      n: int = 1,
                      stream: bool = False) -> requests.Response:
    headers = {"User-Agent": "Test Client"}
    pload = {
 "prompt": prompt,
 "n": n,
 "use_beam_search": True,
 "temperature": 0.0,
 "max_tokens": 16,
 "stream": stream,
 }
    response = requests.post(api_url,
                             headers=headers,
                             json=pload,
                             stream=stream)
 return response


def get_streaming_response(response: requests.Response) -> Iterable[List[str]]:
 for chunk in response.iter_lines(chunk_size=8192,
                                     decode_unicode=False,
                                     delimiter=b"\0"):
 if chunk:
            data = json.loads(chunk.decode("utf-8"))
            output = data["text"]
 yield output


def get_response(response: requests.Response) -> List[str]:
    data = json.loads(response.content)
    output = data["text"]
 return output


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--host", type=str, default="localhost")
    parser.add_argument("--port", type=int, default=8000)
    parser.add_argument("--n", type=int, default=4)
    parser.add_argument("--prompt", type=str, default="San Francisco is a")
    parser.add_argument("--stream", action="store_true")
    args = parser.parse_args()
    prompt = args.prompt
    api_url = f"http://{args.host}:{args.port}/generate"
    n = args.n
    stream = args.stream

 print(f"Prompt: {prompt!r}\n", flush=True)
    response = post_http_request(prompt, api_url, n, stream)

 if stream:
        num_printed_lines = 0
 for h in get_streaming_response(response):
            clear_line(num_printed_lines)
            num_printed_lines = 0
 for i, line in enumerate(h):
                num_printed_lines += 1
 print(f"Beam candidate {i}: {line!r}", flush=True)
 else:
        output = get_response(response)
 for i, line in enumerate(output):
 print(f"Beam candidate {i}: {line!r}", flush=True)
相关推荐
星期天要睡觉9 分钟前
MySQL 综合练习
数据库·mysql
Y40900114 分钟前
数据库基础知识——聚合函数、分组查询
android·数据库
fsnine15 分钟前
深度学习——残差神经网路
人工智能·深度学习
荼蘼25 分钟前
迁移学习实战:基于 ResNet18 的食物分类
机器学习·分类·迁移学习
和鲸社区1 小时前
《斯坦福CS336》作业1开源,从0手搓大模型|代码复现+免环境配置
人工智能·python·深度学习·计算机视觉·语言模型·自然语言处理·nlp
fanstuck1 小时前
2025 年高教社杯全国大学生数学建模竞赛C 题 NIPT 的时点选择与胎儿的异常判定详解(一)
人工智能·目标检测·数学建模·数据挖掘·aigc
cxr8281 小时前
Claude Code PM 深度实战指南:AI驱动的GitHub项目管理与并行协作
人工智能·驱动开发·github
JosieBook1 小时前
【数据库】MySQL 数据库创建存储过程及使用场景详解
数据库·mysql
处女座_三月1 小时前
改 TDengine 数据库的时间写入限制
数据库·sql·mysql
THMAIL1 小时前
深度学习从入门到精通 - LSTM与GRU深度剖析:破解长序列记忆遗忘困境
人工智能·python·深度学习·算法·机器学习·逻辑回归·lstm