OpenAI 兼容服务器#

vLLM 提供了一个 HTTP 服务器,实现了 OpenAI 的 Completions APIChat API 以及更多!

您可以通过 vllm serve 命令或通过 Docker 启动服务器

vllm serve NousResearch/Meta-Llama-3-8B-Instruct --dtype auto --api-key token-abc123

要调用服务器,您可以使用 官方 OpenAI Python 客户端,或任何其他 HTTP 客户端。

from openai import OpenAI
client = OpenAI(
    base_url="https://127.0.0.1:8000/v1",
    api_key="token-abc123",
)

completion = client.chat.completions.create(
  model="NousResearch/Meta-Llama-3-8B-Instruct",
  messages=[
    {"role": "user", "content": "Hello!"}
  ]
)

print(completion.choices[0].message)

支持的 API#

我们目前支持以下 OpenAI API

此外,我们还有以下自定义 API

聊天模板#

为了使语言模型支持聊天协议,vLLM 要求模型在其 tokenizer 配置中包含聊天模板。聊天模板是一个 Jinja2 模板,用于指定角色、消息和其他特定于聊天的 token 如何在输入中编码。

可以在 NousResearch/Meta-Llama-3-8B-Instruct 的示例聊天模板 中找到 here

有些模型即使经过指令/聊天微调,也不提供聊天模板。对于这些模型,您可以在 --chat-template 参数中使用聊天模板的文件路径或字符串形式的模板手动指定其聊天模板。如果没有聊天模板,服务器将无法处理聊天,并且所有聊天请求都会出错。

vllm serve <model> --chat-template ./path-to-chat-template.jinja

vLLM 社区为流行的模型提供了一组聊天模板。您可以在 examples 目录下找到它们。

随着多模态聊天 API 的加入,OpenAI 规范现在接受新格式的聊天消息,该格式指定了 typetext 字段。下面提供了一个示例

completion = client.chat.completions.create(
  model="NousResearch/Meta-Llama-3-8B-Instruct",
  messages=[
    {"role": "user", "content": [{"type": "text", "text": "Classify this sentiment: vLLM is wonderful!"}]}
  ]
)

大多数 LLM 的聊天模板都期望 content 字段是一个字符串,但有些较新的模型(如 meta-llama/Llama-Guard-3-1B)期望内容根据请求中的 OpenAI 模式进行格式化。vLLM 提供尽力支持以自动检测到这一点,这将被记录为类似 “检测到聊天模板内容格式为…” 的字符串,并在内部转换传入的请求以匹配检测到的格式,该格式可以是以下之一

  • "string":一个字符串。

    • 示例:"Hello world"

  • "openai":字典列表,类似于 OpenAI 模式。

    • 示例:[{"type": "text", "text": "Hello world!"}]

如果结果不是您期望的那样,您可以设置 --chat-template-content-format CLI 参数来覆盖要使用的格式。

额外参数#

vLLM 支持一组不属于 OpenAI API 的参数。为了使用它们,您可以将它们作为额外参数传递到 OpenAI 客户端中。或者,如果您直接使用 HTTP 调用,则可以直接将它们合并到 JSON 有效负载中。

completion = client.chat.completions.create(
  model="NousResearch/Meta-Llama-3-8B-Instruct",
  messages=[
    {"role": "user", "content": "Classify this sentiment: vLLM is wonderful!"}
  ],
  extra_body={
    "guided_choice": ["positive", "negative"]
  }
)

额外 HTTP 标头#

目前仅支持 X-Request-Id HTTP 请求标头。可以使用 --enable-request-id-headers 启用它。

请注意,启用标头可能会在高 QPS 速率下显着影响性能。因此,我们建议在路由器级别(例如,通过 Istio)而不是在 vLLM 层中实施 HTTP 标头。有关更多详细信息,请参阅 此 PR

completion = client.chat.completions.create(
  model="NousResearch/Meta-Llama-3-8B-Instruct",
  messages=[
    {"role": "user", "content": "Classify this sentiment: vLLM is wonderful!"}
  ],
  extra_headers={
    "x-request-id": "sentiment-classification-00001",
  }
)
print(completion._request_id)

completion = client.completions.create(
  model="NousResearch/Meta-Llama-3-8B-Instruct",
  prompt="A robot may not injure a human being",
  extra_headers={
    "x-request-id": "completion-test",
  }
)
print(completion._request_id)

CLI 参考#

vllm serve#

vllm serve 命令用于启动 OpenAI 兼容服务器。

usage: vllm serve [-h] [--host HOST] [--port PORT]
                  [--uvicorn-log-level {debug,info,warning,error,critical,trace}]
                  [--allow-credentials] [--allowed-origins ALLOWED_ORIGINS]
                  [--allowed-methods ALLOWED_METHODS]
                  [--allowed-headers ALLOWED_HEADERS] [--api-key API_KEY]
                  [--lora-modules LORA_MODULES [LORA_MODULES ...]]
                  [--prompt-adapters PROMPT_ADAPTERS [PROMPT_ADAPTERS ...]]
                  [--chat-template CHAT_TEMPLATE]
                  [--chat-template-content-format {auto,string,openai}]
                  [--response-role RESPONSE_ROLE] [--ssl-keyfile SSL_KEYFILE]
                  [--ssl-certfile SSL_CERTFILE] [--ssl-ca-certs SSL_CA_CERTS]
                  [--enable-ssl-refresh] [--ssl-cert-reqs SSL_CERT_REQS]
                  [--root-path ROOT_PATH] [--middleware MIDDLEWARE]
                  [--return-tokens-as-token-ids]
                  [--disable-frontend-multiprocessing]
                  [--enable-request-id-headers] [--enable-auto-tool-choice]
                  [--enable-reasoning] [--reasoning-parser {deepseek_r1}]
                  [--tool-call-parser {granite-20b-fc,granite,hermes,internlm,jamba,llama3_json,mistral,pythonic} or name registered in --tool-parser-plugin]
                  [--tool-parser-plugin TOOL_PARSER_PLUGIN] [--model MODEL]
                  [--task {auto,generate,embedding,embed,classify,score,reward,transcription}]
                  [--tokenizer TOKENIZER] [--skip-tokenizer-init]
                  [--revision REVISION] [--code-revision CODE_REVISION]
                  [--tokenizer-revision TOKENIZER_REVISION]
                  [--tokenizer-mode {auto,slow,mistral,custom}]
                  [--trust-remote-code]
                  [--allowed-local-media-path ALLOWED_LOCAL_MEDIA_PATH]
                  [--download-dir DOWNLOAD_DIR]
                  [--load-format {auto,pt,safetensors,npcache,dummy,tensorizer,sharded_state,gguf,bitsandbytes,mistral,runai_streamer}]
                  [--config-format {auto,hf,mistral}]
                  [--dtype {auto,half,float16,bfloat16,float,float32}]
                  [--kv-cache-dtype {auto,fp8,fp8_e5m2,fp8_e4m3}]
                  [--max-model-len MAX_MODEL_LEN]
                  [--guided-decoding-backend GUIDED_DECODING_BACKEND]
                  [--logits-processor-pattern LOGITS_PROCESSOR_PATTERN]
                  [--model-impl {auto,vllm,transformers}]
                  [--distributed-executor-backend {ray,mp,uni,external_launcher}]
                  [--pipeline-parallel-size PIPELINE_PARALLEL_SIZE]
                  [--tensor-parallel-size TENSOR_PARALLEL_SIZE]
                  [--max-parallel-loading-workers MAX_PARALLEL_LOADING_WORKERS]
                  [--ray-workers-use-nsight] [--block-size {8,16,32,64,128}]
                  [--enable-prefix-caching | --no-enable-prefix-caching]
                  [--disable-sliding-window] [--use-v2-block-manager]
                  [--num-lookahead-slots NUM_LOOKAHEAD_SLOTS] [--seed SEED]
                  [--swap-space SWAP_SPACE] [--cpu-offload-gb CPU_OFFLOAD_GB]
                  [--gpu-memory-utilization GPU_MEMORY_UTILIZATION]
                  [--num-gpu-blocks-override NUM_GPU_BLOCKS_OVERRIDE]
                  [--max-num-batched-tokens MAX_NUM_BATCHED_TOKENS]
                  [--max-num-partial-prefills MAX_NUM_PARTIAL_PREFILLS]
                  [--max-long-partial-prefills MAX_LONG_PARTIAL_PREFILLS]
                  [--long-prefill-token-threshold LONG_PREFILL_TOKEN_THRESHOLD]
                  [--max-num-seqs MAX_NUM_SEQS] [--max-logprobs MAX_LOGPROBS]
                  [--disable-log-stats]
                  [--quantization {aqlm,awq,deepspeedfp,tpu_int8,fp8,ptpc_fp8,fbgemm_fp8,modelopt,marlin,gguf,gptq_marlin_24,gptq_marlin,awq_marlin,gptq,compressed-tensors,bitsandbytes,qqq,hqq,experts_int8,neuron_quant,ipex,quark,moe_wna16,None}]
                  [--rope-scaling ROPE_SCALING] [--rope-theta ROPE_THETA]
                  [--hf-overrides HF_OVERRIDES] [--enforce-eager]
                  [--max-seq-len-to-capture MAX_SEQ_LEN_TO_CAPTURE]
                  [--disable-custom-all-reduce]
                  [--tokenizer-pool-size TOKENIZER_POOL_SIZE]
                  [--tokenizer-pool-type TOKENIZER_POOL_TYPE]
                  [--tokenizer-pool-extra-config TOKENIZER_POOL_EXTRA_CONFIG]
                  [--limit-mm-per-prompt LIMIT_MM_PER_PROMPT]
                  [--mm-processor-kwargs MM_PROCESSOR_KWARGS]
                  [--disable-mm-preprocessor-cache] [--enable-lora]
                  [--enable-lora-bias] [--max-loras MAX_LORAS]
                  [--max-lora-rank MAX_LORA_RANK]
                  [--lora-extra-vocab-size LORA_EXTRA_VOCAB_SIZE]
                  [--lora-dtype {auto,float16,bfloat16}]
                  [--long-lora-scaling-factors LONG_LORA_SCALING_FACTORS]
                  [--max-cpu-loras MAX_CPU_LORAS] [--fully-sharded-loras]
                  [--enable-prompt-adapter]
                  [--max-prompt-adapters MAX_PROMPT_ADAPTERS]
                  [--max-prompt-adapter-token MAX_PROMPT_ADAPTER_TOKEN]
                  [--device {auto,cuda,neuron,cpu,openvino,tpu,xpu,hpu}]
                  [--num-scheduler-steps NUM_SCHEDULER_STEPS]
                  [--multi-step-stream-outputs [MULTI_STEP_STREAM_OUTPUTS]]
                  [--scheduler-delay-factor SCHEDULER_DELAY_FACTOR]
                  [--enable-chunked-prefill [ENABLE_CHUNKED_PREFILL]]
                  [--speculative-model SPECULATIVE_MODEL]
                  [--speculative-model-quantization {aqlm,awq,deepspeedfp,tpu_int8,fp8,ptpc_fp8,fbgemm_fp8,modelopt,marlin,gguf,gptq_marlin_24,gptq_marlin,awq_marlin,gptq,compressed-tensors,bitsandbytes,qqq,hqq,experts_int8,neuron_quant,ipex,quark,moe_wna16,None}]
                  [--num-speculative-tokens NUM_SPECULATIVE_TOKENS]
                  [--speculative-disable-mqa-scorer]
                  [--speculative-draft-tensor-parallel-size SPECULATIVE_DRAFT_TENSOR_PARALLEL_SIZE]
                  [--speculative-max-model-len SPECULATIVE_MAX_MODEL_LEN]
                  [--speculative-disable-by-batch-size SPECULATIVE_DISABLE_BY_BATCH_SIZE]
                  [--ngram-prompt-lookup-max NGRAM_PROMPT_LOOKUP_MAX]
                  [--ngram-prompt-lookup-min NGRAM_PROMPT_LOOKUP_MIN]
                  [--spec-decoding-acceptance-method {rejection_sampler,typical_acceptance_sampler}]
                  [--typical-acceptance-sampler-posterior-threshold TYPICAL_ACCEPTANCE_SAMPLER_POSTERIOR_THRESHOLD]
                  [--typical-acceptance-sampler-posterior-alpha TYPICAL_ACCEPTANCE_SAMPLER_POSTERIOR_ALPHA]
                  [--disable-logprobs-during-spec-decoding [DISABLE_LOGPROBS_DURING_SPEC_DECODING]]
                  [--model-loader-extra-config MODEL_LOADER_EXTRA_CONFIG]
                  [--ignore-patterns IGNORE_PATTERNS]
                  [--preemption-mode PREEMPTION_MODE]
                  [--served-model-name SERVED_MODEL_NAME [SERVED_MODEL_NAME ...]]
                  [--qlora-adapter-name-or-path QLORA_ADAPTER_NAME_OR_PATH]
                  [--show-hidden-metrics-for-version SHOW_HIDDEN_METRICS_FOR_VERSION]
                  [--otlp-traces-endpoint OTLP_TRACES_ENDPOINT]
                  [--collect-detailed-traces COLLECT_DETAILED_TRACES]
                  [--disable-async-output-proc]
                  [--scheduling-policy {fcfs,priority}]
                  [--scheduler-cls SCHEDULER_CLS]
                  [--override-neuron-config OVERRIDE_NEURON_CONFIG]
                  [--override-pooler-config OVERRIDE_POOLER_CONFIG]
                  [--compilation-config COMPILATION_CONFIG]
                  [--kv-transfer-config KV_TRANSFER_CONFIG]
                  [--worker-cls WORKER_CLS]
                  [--generation-config GENERATION_CONFIG]
                  [--override-generation-config OVERRIDE_GENERATION_CONFIG]
                  [--enable-sleep-mode] [--calculate-kv-scales]
                  [--additional-config ADDITIONAL_CONFIG]
                  [--disable-log-requests] [--max-log-len MAX_LOG_LEN]
                  [--disable-fastapi-docs] [--enable-prompt-tokens-details]

命名参数#

--host

主机名。

--port

端口号。

默认值:8000

--uvicorn-log-level

可能选项:debug, info, warning, error, critical, trace

uvicorn 的日志级别。

默认值:“info”

--allow-credentials

允许凭据。

默认值:False

--allowed-origins

允许的来源。

默认值:[‘*’]

--allowed-methods

允许的方法。

默认值:[‘*’]

--allowed-headers

允许的标头。

默认值:[‘*’]

--api-key

如果提供,服务器将要求在标头中提供此密钥。

--lora-modules

LoRA 模块配置,格式为 ‘name=path’ 或 JSON 格式。示例(旧格式):'name=path' 示例(新格式):{"name": "name", "path": "lora_path", "base_model_name": "id"}

--prompt-adapters

提示适配器配置,格式为 name=path。可以指定多个适配器。

--chat-template

指定模型的聊天模板的文件路径或单行形式的模板。

--chat-template-content-format

可能选项:auto, string, openai

在聊天模板中呈现消息内容的格式。

  • “string” 将内容呈现为字符串。示例:"Hello World"

  • “openai” 将内容呈现为字典列表,类似于 OpenAI 模式。示例:[{"type": "text", "text": "Hello world!"}]

默认值:“auto”

--response-role

如果 request.add_generation_prompt=true,则返回的角色名称。

默认值:assistant

--ssl-keyfile

SSL 密钥文件的文件路径。

--ssl-certfile

SSL 证书文件的文件路径。

--ssl-ca-certs

CA 证书文件。

--enable-ssl-refresh

当 SSL 证书文件更改时刷新 SSL 上下文

默认值:False

--ssl-cert-reqs

是否需要客户端证书(请参阅 stdlib ssl 模块)。

默认值:0

--root-path

当应用程序位于基于路径路由代理之后时,FastAPI root_path。

--middleware

要应用于应用程序的其他 ASGI 中间件。我们接受多个 –middleware 参数。该值应为导入路径。如果提供了函数,vLLM 将使用 @app.middleware('http') 将其添加到服务器。如果提供了类,vLLM 将使用 app.add_middleware() 将其添加到服务器。

默认值:[]

--return-tokens-as-token-ids

当指定 --max-logprobs 时,将单个 token 表示为 ‘token_id:{token_id}’ 形式的字符串,以便可以识别不可 JSON 编码的 token。

默认值:False

--disable-frontend-multiprocessing

如果指定,将在与模型服务引擎相同的进程中运行 OpenAI 前端服务器。

默认值:False

--enable-request-id-headers

如果指定,API 服务器将在响应中添加 X-Request-Id 标头。注意:在高 QPS 下,这会降低性能。

默认值:False

--enable-auto-tool-choice

为支持的模型启用自动工具选择。使用 --tool-call-parser 指定要使用的解析器。

默认值:False

--enable-reasoning

是否为模型启用 reasoning_content。如果启用,模型将能够生成推理内容。

默认值:False

--reasoning-parser

根据您使用的模型选择推理解析器。这用于将推理内容解析为 OpenAI API 格式。--enable-reasoning 需要此项。

--tool-call-parser

根据您使用的模型选择工具调用解析器。这用于将模型生成的工具调用解析为 OpenAI API 格式。--enable-auto-tool-choice 需要此项。

--tool-parser-plugin

指定用于将模型生成的工具解析为 OpenAI API 格式的工具解析器插件,此插件中注册的名称可以在 --tool-call-parser 中使用。

默认值:“”

--model

要使用的 huggingface 模型的名称或路径。

默认值:“facebook/opt-125m”

--task

可能选项:auto, generate, embedding, embed, classify, score, reward, transcription

模型要使用的任务。即使同一模型可以用于多个任务,每个 vLLM 实例也仅支持一项任务。当模型仅支持一项任务时,可以使用 "auto" 来选择它;否则,您必须明确指定要使用的任务。

默认值:“auto”

--tokenizer

要使用的 huggingface tokenizer 的名称或路径。如果未指定,将使用模型名称或路径。

--skip-tokenizer-init

跳过 tokenizer 和 detokenizer 的初始化。

默认值:False

--revision

要使用的特定模型版本。它可以是分支名称、标签名称或提交 ID。如果未指定,将使用默认版本。

--code-revision

要用于 Hugging Face Hub 上模型代码的特定修订版本。它可以是分支名称、标签名称或提交 ID。如果未指定,将使用默认版本。

--tokenizer-revision

要使用的 huggingface tokenizer 的修订版本。它可以是分支名称、标签名称或提交 ID。如果未指定,将使用默认版本。

--tokenizer-mode

可能选项:auto, slow, mistral, custom

tokenizer 模式。

  • “auto” 将在可用时使用快速 tokenizer。

  • “slow” 将始终使用慢速 tokenizer。

  • “mistral” 将始终使用 mistral_common tokenizer。

  • “custom” 将使用 –tokenizer 选择预注册的 tokenizer。

默认值:“auto”

--trust-remote-code

信任来自 huggingface 的远程代码。

默认值:False

--allowed-local-media-path

允许 API 请求从服务器文件系统指定的目录读取本地图像或视频。这存在安全风险。仅应在受信任的环境中启用。

--download-dir

下载和加载权重的目录,默认为 huggingface 的默认缓存目录。

--load-format

可能选项:auto, pt, safetensors, npcache, dummy, tensorizer, sharded_state, gguf, bitsandbytes, mistral, runai_streamer

要加载的模型权重的格式。

  • “auto” 将尝试加载 safetensors 格式的权重,如果 safetensors 格式不可用,则回退到 pytorch bin 格式。

  • “pt” 将加载 pytorch bin 格式的权重。

  • “safetensors” 将加载 safetensors 格式的权重。

  • “npcache” 将加载 pytorch 格式的权重,并存储 numpy 缓存以加速加载。

  • “dummy” 将使用随机值初始化权重,这主要用于性能分析。

  • “tensorizer” 将使用 CoreWeave 的 tensorizer 加载权重。有关更多信息,请参阅“示例”部分中的“张量化 vLLM 模型”脚本。

  • “runai_streamer” 将使用 Run:aiModel Streamer 加载 Safetensors 权重

  • “bitsandbytes” 将使用 bitsandbytes 量化加载权重。

默认值:“auto”

--config-format

可能选项:auto, hf, mistral

要加载的模型配置的格式。

  • “auto” 将尝试加载 hf 格式的配置,如果不可用,则尝试加载 mistral 格式

默认值:“ConfigFormat.AUTO”

--dtype

可能选项:auto, half, float16, bfloat16, float, float32

模型权重和激活的数据类型。

  • “auto” 将对 FP32 和 FP16 模型使用 FP16 精度,对 BF16 模型使用 BF16 精度。

  • “half” 用于 FP16。推荐用于 AWQ 量化。

  • “float16” 与 “half” 相同。

  • “bfloat16” 用于在精度和范围之间取得平衡。

  • “float” 是 FP32 精度的简写。

  • “float32” 用于 FP32 精度。

默认值:“auto”

--kv-cache-dtype

可能选项:auto, fp8, fp8_e5m2, fp8_e4m3

kv 缓存存储的数据类型。如果为 “auto”,将使用模型数据类型。CUDA 11.8+ 支持 fp8 (=fp8_e4m3) 和 fp8_e5m2。ROCm (AMD GPU) 支持 fp8 (=fp8_e4m3)

默认值:“auto”

--max-model-len

模型上下文长度。如果未指定,将自动从模型配置中派生。

--guided-decoding-backend

默认情况下,哪个引擎将用于引导解码(JSON 模式/正则表达式等)。目前支持 outlines-dev/outlinesmlc-ai/xgrammarnoamgat/lm-format-enforcer。可以通过 guided_decoding_backend 参数按请求覆盖。后端特定选项可以在后端名称后的冒号后以逗号分隔的列表提供。有效的后端和所有可用选项为:[xgrammar:no-fallback, outlines:no-fallback, lm-format-enforcer:no-fallback]

默认值:“xgrammar”

--logits-processor-pattern

可选的正则表达式模式,用于指定可以通过 logits_processors 额外完成参数传递的有效 logits 处理器限定名称。默认为 None,表示不允许任何处理器。

--model-impl

可能选项:auto, vllm, transformers

要使用的模型的实现方式。

  • “auto” 将尝试使用 vLLM 实现(如果存在),如果 vLLM 实现不可用,则回退到 Transformers 实现。

  • “vllm” 将使用 vLLM 模型实现。

  • “transformers” 将使用 Transformers 模型实现。

默认值:“auto”

--distributed-executor-backend

可能选项:ray, mp, uni, external_launcher

用于分布式模型工作程序的后端,可以是 “ray” 或 “mp”(多进程)。如果 pipeline_parallel_size 和 tensor_parallel_size 的乘积小于或等于可用 GPU 的数量,“mp” 将用于在单个主机上保持处理。否则,如果安装了 Ray,则默认为 “ray”,否则将失败。请注意,tpu 仅支持 Ray 用于分布式推理。

--pipeline-parallel-size, -pp

管道并行阶段数。

默认值:1

--tensor-parallel-size, -tp

张量并行副本数。

默认值:1

--max-parallel-loading-workers

在多个批次中顺序加载模型,以避免在使用张量并行和大型模型时出现 RAM OOM。

--ray-workers-use-nsight

如果指定,则使用 nsight 分析 Ray 工作程序。

默认值:False

--block-size

可能选项:8, 16, 32, 64, 128

token 块大小,用于 token 的连续块。在 neuron 设备上,此项将被忽略,并设置为 --max-model-len。在 CUDA 设备上,仅支持最大为 32 的块大小。在 HPU 设备上,块大小默认为 128。

--enable-prefix-caching, --no-enable-prefix-caching

启用自动前缀缓存。使用 --no-enable-prefix-caching 显式禁用。

--disable-sliding-window

禁用滑动窗口,限制为滑动窗口大小。

默认值:False

--use-v2-block-manager

[已弃用] 块管理器 v1 已被删除,SelfAttnBlockSpaceManager(即块管理器 v2)现在是默认设置。将此标志设置为 True 或 False 对 vLLM 行为没有影响。

默认值:True

--num-lookahead-slots

推测解码所需的实验性调度配置。将来将被推测配置取代;它目前存在是为了启用正确性测试。

默认值:0

--seed

操作的随机种子。

默认值:0

--swap-space

每个 GPU 的 CPU 交换空间大小 (GiB)。

默认值:4

--cpu-offload-gb

每个 GPU 要卸载到 CPU 的空间大小 (GiB)。默认值为 0,表示不卸载。直观上,此参数可以看作是增加 GPU 内存大小的虚拟方式。例如,如果您有一个 24 GB GPU 并将其设置为 10,则实际上可以将其视为 34 GB GPU。然后,您可以加载一个 13B 模型,该模型具有 BF16 权重,至少需要 26GB GPU 内存。请注意,这需要快速的 CPU-GPU 互连,因为模型的一部分在每个模型前向传递中从 CPU 内存动态加载到 GPU 内存。

默认值:0

--gpu-memory-utilization

用于模型执行器的 GPU 内存比例,范围为 0 到 1。例如,值为 0.5 表示 GPU 内存利用率为 50%。如果未指定,将使用默认值 0.9。这是一个按实例限制,仅适用于当前的 vLLM 实例。如果您在同一 GPU 上运行另一个 vLLM 实例,则无关紧要。例如,如果您在同一 GPU 上运行两个 vLLM 实例,则可以将每个实例的 GPU 内存利用率设置为 0.5。

默认值:0.9

--num-gpu-blocks-override

如果指定,则忽略 GPU 性能分析结果,并使用此 GPU 块数。用于测试抢占。

--max-num-batched-tokens

每次迭代的最大批处理 token 数。

--max-num-partial-prefills

对于分块预填充,最大并发部分预填充数。默认为 1

默认值:1

--max-long-partial-prefills

对于分块预填充,提示长度超过 –long-prefill-token-threshold 的最大提示数将并发预填充。将此值设置得小于 –max-num-partial-prefills 将允许较短的提示在某些情况下跳过较长提示的队列,从而提高延迟。默认为 1。

默认值:1

--long-prefill-token-threshold

对于分块预填充,如果提示长度超过此 token 数,则该请求被视为长请求。默认为模型上下文长度的 4%。

默认值:0

--max-num-seqs

每次迭代的最大序列数。

--max-logprobs

要返回的最大对数概率数,logprobs 在 SamplingParams 中指定。

默认值:20

--disable-log-stats

禁用日志统计信息。

默认值:False

--quantization, -q

可能选项:aqlm, awq, deepspeedfp, tpu_int8, fp8, ptpc_fp8, fbgemm_fp8, modelopt, marlin, gguf, gptq_marlin_24, gptq_marlin, awq_marlin, gptq, compressed-tensors, bitsandbytes, qqq, hqq, experts_int8, neuron_quant, ipex, quark, moe_wna16, None

用于量化权重的方法。如果为 None,我们首先检查模型配置文件中的 quantization_config 属性。如果为 None,我们假设模型权重未量化,并使用 dtype 来确定权重的数据类型。

--rope-scaling

JSON 格式的 RoPE 缩放配置。例如,{"rope_type":"dynamic","factor":2.0}

--rope-theta

RoPE theta。与 rope_scaling 一起使用。在某些情况下,更改 RoPE theta 可以提高缩放模型的性能。

--hf-overrides

HuggingFace 配置的额外参数。这应该是一个 JSON 字符串,将被解析为字典。

--enforce-eager

始终使用 eager 模式 PyTorch。如果为 False,将混合使用 eager 模式和 CUDA 图,以获得最大的性能和灵活性。

默认值:False

--max-seq-len-to-capture

CUDA 图覆盖的最大序列长度。当序列的上下文长度大于此值时,我们将回退到 eager 模式。此外,对于编码器-解码器模型,如果编码器输入的序列长度大于此值,我们将回退到 eager 模式。

默认值:8192

--disable-custom-all-reduce

请参阅 ParallelConfig。

默认值:False

--tokenizer-pool-size

用于异步 token 化的 tokenizer 池的大小。如果为 0,将使用同步 token 化。

默认值:0

--tokenizer-pool-type

用于异步 token 化的 tokenizer 池的类型。如果 tokenizer_pool_size 为 0,则忽略此项。

默认值:“ray”

--tokenizer-pool-extra-config

tokenizer 池的额外配置。这应该是一个 JSON 字符串,将被解析为字典。如果 tokenizer_pool_size 为 0,则忽略此项。

--limit-mm-per-prompt

对于每个多模态插件,限制每个提示允许的输入实例数。期望一个逗号分隔的项目列表,例如:image=16,video=2 允许每个提示最多 16 个图像和 2 个视频。默认为每种模态 1 个。

--mm-processor-kwargs

多模态输入映射/处理的覆盖,例如,图像处理器。例如:{"num_crops": 4}

--disable-mm-preprocessor-cache

如果为 true,则禁用多模态预处理器/映射器的缓存。(不推荐)

默认值:False

--enable-lora

如果为 True,则启用 LoRA 适配器的处理。

默认值:False

--enable-lora-bias

如果为 True,则启用 LoRA 适配器的偏置。

默认值:False

--max-loras

单个批次中的最大 LoRA 数。

默认值:1

--max-lora-rank

最大 LoRA 秩。

默认值:16

--lora-extra-vocab-size

LoRA 适配器中可能存在的额外词汇表的最大大小(添加到基本模型词汇表)。

默认值:256

--lora-dtype

可能选项:auto, float16, bfloat16

LoRA 的数据类型。如果为 auto,将默认为基本模型 dtype。

默认值:“auto”

--long-lora-scaling-factors

指定多个缩放因子(可以与基本模型缩放因子不同 - 请参阅例如 Long LoRA),以允许同时使用使用这些缩放因子训练的多个 LoRA 适配器。如果未指定,则仅允许使用使用基本模型缩放因子训练的适配器。

--max-cpu-loras

CPU 内存中存储 LoRA 的最大数量。必须 >= max_loras。默认为 max_loras。

--fully-sharded-loras

默认情况下,只有一半的 LoRA 计算通过张量并行进行分片。启用此选项将使用完全分片层。在高序列长度、最大秩或张量并行大小时,这可能会更快。

默认值:False

--enable-prompt-adapter

如果为 True,则启用 PromptAdapters 的处理。

默认值:False

--max-prompt-adapters

一个批次中 PromptAdapters 的最大数量。

默认值:1

--max-prompt-adapter-token

PromptAdapters 令牌的最大数量

默认值:0

--device

可选值:auto, cuda, neuron, cpu, openvino, tpu, xpu, hpu

vLLM 执行的设备类型。

默认值:“auto”

--num-scheduler-steps

每个调度器调用中最大正向步骤数。

默认值:1

--multi-step-stream-outputs

如果为 False,则多步将在所有步骤结束时流式传输输出

默认值:True

--scheduler-delay-factor

在调度下一个提示之前,应用延迟(延迟因子乘以先前的提示延迟)。

默认值:0.0

--enable-chunked-prefill

如果设置,预填充请求可以根据 max_num_batched_tokens 进行分块。

--speculative-model

在推测解码中使用的草稿模型名称。

--speculative-model-quantization

可能选项:aqlm, awq, deepspeedfp, tpu_int8, fp8, ptpc_fp8, fbgemm_fp8, modelopt, marlin, gguf, gptq_marlin_24, gptq_marlin, awq_marlin, gptq, compressed-tensors, bitsandbytes, qqq, hqq, experts_int8, neuron_quant, ipex, quark, moe_wna16, None

用于量化推测模型权重的方法。如果为 None,我们首先检查模型配置文件中的 quantization_config 属性。如果为 None,我们假设模型权重未量化,并使用 dtype 来确定权重的​​数据类型。

--num-speculative-tokens

在推测解码中从草稿模型采样的推测令牌数量。

--speculative-disable-mqa-scorer

如果设置为 True,则 MQA 评分器将在推测中禁用,并回退到批量扩展

默认值:False

--speculative-draft-tensor-parallel-size, -spec-draft-tp

推测解码中草稿模型的张量并行副本数。

--speculative-max-model-len

草稿模型支持的最大序列长度。超过此长度的序列将跳过推测。

--speculative-disable-by-batch-size

如果入队请求的数量大于此值,则禁用新传入请求的推测解码。

--ngram-prompt-lookup-max

推测解码中 ngram 提示查找的最大窗口大小。

--ngram-prompt-lookup-min

推测解码中 ngram 提示查找的最小窗口大小。

--spec-decoding-acceptance-method

可选值:rejection_sampler, typical_acceptance_sampler

指定在推测解码期间用于草稿令牌验证的接受方法。支持两种类型的接受例程:1) RejectionSampler,它不允许更改草稿令牌的接受率,2) TypicalAcceptanceSampler,它是可配置的,允许以较低质量为代价获得更高的接受率,反之亦然。

默认值:“rejection_sampler”

--typical-acceptance-sampler-posterior-threshold

设置接受令牌的后验概率的下限阈值。TypicalAcceptanceSampler 使用此阈值在推测解码期间做出采样决策。默认为 0.09

--typical-acceptance-sampler-posterior-alpha

TypicalAcceptanceSampler 中用于令牌接受的基于熵的阈值的缩放因子。通常默认为 –typical-acceptance-sampler-posterior-threshold 的平方根,即 0.3

--disable-logprobs-during-spec-decoding

如果设置为 True,则在推测解码期间不返回令牌对数概率。如果设置为 False,则根据 SamplingParams 中的设置返回对数概率。如果未指定,则默认为 True。在推测解码期间禁用对数概率会减少延迟,因为它跳过了提案采样、目标采样以及在确定接受的令牌之后的对数概率计算。

--model-loader-extra-config

模型加载器的额外配置。这将传递给与所选 load_format 对应的模型加载器。这应该是一个 JSON 字符串,将被解析为字典。

--ignore-patterns

加载模型时要忽略的模式。默认为 original/**/*,以避免重复加载 llama 的检查点。

默认值:[]

--preemption-mode

如果为“recompute”,则引擎通过重新计算执行抢占;如果为“swap”,则引擎通过块交换执行抢占。

--served-model-name

API 中使用的模型名称。如果提供多个名称,服务器将响应任何提供的名称。响应的模型字段中的模型名称将是列表中的第一个名称。如果未指定,模型名称将与 --model 参数相同。请注意,此名称也将用于 prometheus 指标的 model_name 标签内容中,如果提供多个名称,指标标签将采用第一个名称。

--qlora-adapter-name-or-path

QLoRA 适配器的名称或路径。

--show-hidden-metrics-for-version

启用自指定版本以来已隐藏的已弃用 Prometheus 指标。例如,如果先前已弃用的指标自 v0.7.0 版本以来已被隐藏,您可以使用 –show-hidden-metrics-for-version=0.7 作为临时应急措施,同时迁移到新指标。该指标很可能在即将发布的版本中完全删除。

--otlp-traces-endpoint

OpenTelemetry 跟踪将发送到的目标 URL。

--collect-detailed-traces

有效选项为 model,worker,all。仅当设置了 --otlp-traces-endpoint 时,设置此选项才有意义。如果设置,它将收集指定模块的详细跟踪信息。这涉及使用可能代价高昂和/或阻塞的操作,因此可能会对性能产生影响。

--disable-async-output-proc

禁用异步输出处理。这可能会导致性能降低。

默认值:False

--scheduling-policy

可选值:fcfs, priority

要使用的调度策略。“fcfs”(先进先出,即请求按到达顺序处理;默认)或“priority”(请求根据给定的优先级(值越低表示越早处理)和到达时间来处理任何并列情况)。

默认值:“fcfs”

--scheduler-cls

要使用的调度器类。“vllm.core.scheduler.Scheduler”是默认调度器。可以是直接的类,也可以是“mod.custom_class”形式的类路径。

默认值:“vllm.core.scheduler.Scheduler”

--override-neuron-config

覆盖或设置 neuron 设备配置。例如:{"cast_logits_dtype": "bloat16"}

--override-pooler-config

覆盖或设置池化模型的池化方法。例如:{"pooling_type": "mean", "normalize": false}

--compilation-config, -O

模型的 torch.compile 配置。当它是一个数字(0、1、2、3)时,它将被解释为优化级别。注意:级别 0 是没有任何优化的默认级别。级别 1 和 2 仅供内部测试使用。级别 3 是推荐用于生产的级别。要指定完整的编译配置,请使用 JSON 字符串。按照传统编译器的约定,也支持使用 -O 而不带空格。-O3 等效于 -O 3。

--kv-transfer-config

分布式 KV 缓存传输的配置。应为 JSON 字符串。

--worker-cls

用于分布式执行的工作程序类。

默认值:“auto”

--generation-config

生成配置的文件夹路径。默认为 None,不加载生成配置,将使用 vLLM 默认值。如果设置为“auto”,则将从模型路径加载生成配置。如果设置为文件夹路径,则将从指定的文件夹路径加载生成配置。如果在生成配置中指定了 max_new_tokens,则它会为所有请求设置服务器范围的输出令牌数量限制。

--override-generation-config

以 JSON 格式覆盖或设置生成配置。例如:{"temperature": 0.5}。如果与 –generation-config=auto 一起使用,则覆盖参数将与模型中的默认配置合并。如果 generation-config 为 None,则仅使用覆盖参数。

--enable-sleep-mode

为引擎启用睡眠模式。(仅支持 cuda 平台)

默认值:False

--calculate-kv-scales

当 kv-cache-dtype 为 fp8 时,这将启用 k_scale 和 v_scale 的动态计算。如果 calculate-kv-scales 为 false,则将从模型检查点加载比例(如果可用)。否则,比例将默认为 1.0。

默认值:False

--additional-config

JSON 格式的指定平台的其他配置。不同的平台可能支持不同的配置。确保配置对于您使用的平台有效。输入格式类似于“{“config_key”:”config_value”}”

--disable-log-requests

禁用请求日志记录。

默认值:False

--max-log-len

日志中打印的最大提示字符数或提示 ID 号。

默认值:无限制

--disable-fastapi-docs

禁用 FastAPI 的 OpenAPI 模式、Swagger UI 和 ReDoc 端点。

默认值:False

--enable-prompt-tokens-details

如果设置为 True,则在 usage 中启用 prompt_tokens_details。

默认值:False

配置文件#

您可以通过 YAML 配置文件加载 CLI 参数。参数名称必须是 上面 概述的长格式。

例如

# config.yaml

host: "127.0.0.1"
port: 6379
uvicorn-log-level: "info"

要使用上述配置文件

vllm serve SOME_MODEL --config config.yaml

注意

如果同时使用命令行和配置文件提供参数,则以命令行中的值为准。优先级顺序为 命令行 > 配置文件值 > 默认值

API 参考#

Completions API#

我们的 Completions API 与 OpenAI 的 Completions API 兼容;您可以使用 官方 OpenAI Python 客户端 与之交互。

代码示例:examples/online_serving/openai_completion_client.py

额外参数#

支持以下 采样参数

    use_beam_search: bool = False
    top_k: Optional[int] = None
    min_p: Optional[float] = None
    repetition_penalty: Optional[float] = None
    length_penalty: float = 1.0
    stop_token_ids: Optional[List[int]] = Field(default_factory=list)
    include_stop_str_in_output: bool = False
    ignore_eos: bool = False
    min_tokens: int = 0
    skip_special_tokens: bool = True
    spaces_between_special_tokens: bool = True
    truncate_prompt_tokens: Optional[Annotated[int, Field(ge=1)]] = None
    allowed_token_ids: Optional[List[int]] = None
    prompt_logprobs: Optional[int] = None

支持以下额外参数

    add_special_tokens: bool = Field(
        default=True,
        description=(
            "If true (the default), special tokens (e.g. BOS) will be added to "
            "the prompt."),
    )
    response_format: Optional[ResponseFormat] = Field(
        default=None,
        description=
        ("Similar to chat completion, this parameter specifies the format of "
         "output. Only {'type': 'json_object'}, {'type': 'json_schema'} or "
         "{'type': 'text' } is supported."),
    )
    guided_json: Optional[Union[str, dict, BaseModel]] = Field(
        default=None,
        description="If specified, the output will follow the JSON schema.",
    )
    guided_regex: Optional[str] = Field(
        default=None,
        description=(
            "If specified, the output will follow the regex pattern."),
    )
    guided_choice: Optional[List[str]] = Field(
        default=None,
        description=(
            "If specified, the output will be exactly one of the choices."),
    )
    guided_grammar: Optional[str] = Field(
        default=None,
        description=(
            "If specified, the output will follow the context free grammar."),
    )
    guided_decoding_backend: Optional[str] = Field(
        default=None,
        description=(
            "If specified, will override the default guided decoding backend "
            "of the server for this specific request. If set, must be one of "
            "'outlines' / 'lm-format-enforcer'"))
    guided_whitespace_pattern: Optional[str] = Field(
        default=None,
        description=(
            "If specified, will override the default whitespace pattern "
            "for guided json decoding."))
    priority: int = Field(
        default=0,
        description=(
            "The priority of the request (lower means earlier handling; "
            "default: 0). Any priority other than 0 will raise an error "
            "if the served model does not use priority scheduling."))
    logits_processors: Optional[LogitsProcessors] = Field(
        default=None,
        description=(
            "A list of either qualified names of logits processors, or "
            "constructor objects, to apply when sampling. A constructor is "
            "a JSON object with a required 'qualname' field specifying the "
            "qualified name of the processor class/factory, and optional "
            "'args' and 'kwargs' fields containing positional and keyword "
            "arguments. For example: {'qualname': "
            "'my_module.MyLogitsProcessor', 'args': [1, 2], 'kwargs': "
            "{'param': 'value'}}."))

Chat API#

我们的 Chat API 与 OpenAI 的 Chat Completions API 兼容;您可以使用 官方 OpenAI Python 客户端 与之交互。

我们同时支持 VisionAudio 相关参数;请参阅我们的 多模态输入 指南以获取更多信息。

  • 注意:不支持 image_url.detail 参数。

代码示例:examples/online_serving/openai_chat_completion_client.py

额外参数#

支持以下 采样参数

    best_of: Optional[int] = None
    use_beam_search: bool = False
    top_k: Optional[int] = None
    min_p: Optional[float] = None
    repetition_penalty: Optional[float] = None
    length_penalty: float = 1.0
    stop_token_ids: Optional[List[int]] = Field(default_factory=list)
    include_stop_str_in_output: bool = False
    ignore_eos: bool = False
    min_tokens: int = 0
    skip_special_tokens: bool = True
    spaces_between_special_tokens: bool = True
    truncate_prompt_tokens: Optional[Annotated[int, Field(ge=1)]] = None
    prompt_logprobs: Optional[int] = None

支持以下额外参数

    echo: bool = Field(
        default=False,
        description=(
            "If true, the new message will be prepended with the last message "
            "if they belong to the same role."),
    )
    add_generation_prompt: bool = Field(
        default=True,
        description=
        ("If true, the generation prompt will be added to the chat template. "
         "This is a parameter used by chat template in tokenizer config of the "
         "model."),
    )
    continue_final_message: bool = Field(
        default=False,
        description=
        ("If this is set, the chat will be formatted so that the final "
         "message in the chat is open-ended, without any EOS tokens. The "
         "model will continue this message rather than starting a new one. "
         "This allows you to \"prefill\" part of the model's response for it. "
         "Cannot be used at the same time as `add_generation_prompt`."),
    )
    add_special_tokens: bool = Field(
        default=False,
        description=(
            "If true, special tokens (e.g. BOS) will be added to the prompt "
            "on top of what is added by the chat template. "
            "For most models, the chat template takes care of adding the "
            "special tokens so this should be set to false (as is the "
            "default)."),
    )
    documents: Optional[List[Dict[str, str]]] = Field(
        default=None,
        description=
        ("A list of dicts representing documents that will be accessible to "
         "the model if it is performing RAG (retrieval-augmented generation)."
         " If the template does not support RAG, this argument will have no "
         "effect. We recommend that each document should be a dict containing "
         "\"title\" and \"text\" keys."),
    )
    chat_template: Optional[str] = Field(
        default=None,
        description=(
            "A Jinja template to use for this conversion. "
            "As of transformers v4.44, default chat template is no longer "
            "allowed, so you must provide a chat template if the tokenizer "
            "does not define one."),
    )
    chat_template_kwargs: Optional[Dict[str, Any]] = Field(
        default=None,
        description=("Additional kwargs to pass to the template renderer. "
                     "Will be accessible by the chat template."),
    )
    mm_processor_kwargs: Optional[Dict[str, Any]] = Field(
        default=None,
        description=("Additional kwargs to pass to the HF processor."),
    )
    guided_json: Optional[Union[str, dict, BaseModel]] = Field(
        default=None,
        description=("If specified, the output will follow the JSON schema."),
    )
    guided_regex: Optional[str] = Field(
        default=None,
        description=(
            "If specified, the output will follow the regex pattern."),
    )
    guided_choice: Optional[List[str]] = Field(
        default=None,
        description=(
            "If specified, the output will be exactly one of the choices."),
    )
    guided_grammar: Optional[str] = Field(
        default=None,
        description=(
            "If specified, the output will follow the context free grammar."),
    )
    guided_decoding_backend: Optional[str] = Field(
        default=None,
        description=(
            "If specified, will override the default guided decoding backend "
            "of the server for this specific request. If set, must be either "
            "'outlines' / 'lm-format-enforcer'"))
    guided_whitespace_pattern: Optional[str] = Field(
        default=None,
        description=(
            "If specified, will override the default whitespace pattern "
            "for guided json decoding."))
    priority: int = Field(
        default=0,
        description=(
            "The priority of the request (lower means earlier handling; "
            "default: 0). Any priority other than 0 will raise an error "
            "if the served model does not use priority scheduling."))
    request_id: str = Field(
        default_factory=lambda: f"{random_uuid()}",
        description=(
            "The request_id related to this request. If the caller does "
            "not set it, a random_uuid will be generated. This id is used "
            "through out the inference process and return in response."))
    logits_processors: Optional[LogitsProcessors] = Field(
        default=None,
        description=(
            "A list of either qualified names of logits processors, or "
            "constructor objects, to apply when sampling. A constructor is "
            "a JSON object with a required 'qualname' field specifying the "
            "qualified name of the processor class/factory, and optional "
            "'args' and 'kwargs' fields containing positional and keyword "
            "arguments. For example: {'qualname': "
            "'my_module.MyLogitsProcessor', 'args': [1, 2], 'kwargs': "
            "{'param': 'value'}}."))

Embeddings API#

我们的 Embeddings API 与 OpenAI 的 Embeddings API 兼容;您可以使用 官方 OpenAI Python 客户端 与之交互。

如果模型具有 聊天模板,您可以将 inputs 替换为 messages 列表(与 Chat API 相同的架构),这些列表将被视为模型的单个提示。

提示

这使得可以将多模态输入传递给嵌入模型,有关详细信息,请参阅 此页面

代码示例:examples/online_serving/openai_embedding_client.py

额外参数#

支持以下 池化参数

    additional_data: Optional[Any] = None

默认情况下支持以下额外参数

    add_special_tokens: bool = Field(
        default=True,
        description=(
            "If true (the default), special tokens (e.g. BOS) will be added to "
            "the prompt."),
    )
    priority: int = Field(
        default=0,
        description=(
            "The priority of the request (lower means earlier handling; "
            "default: 0). Any priority other than 0 will raise an error "
            "if the served model does not use priority scheduling."))

对于类似聊天的输入(即,如果传递了 messages),则支持以下额外参数

    add_special_tokens: bool = Field(
        default=False,
        description=(
            "If true, special tokens (e.g. BOS) will be added to the prompt "
            "on top of what is added by the chat template. "
            "For most models, the chat template takes care of adding the "
            "special tokens so this should be set to false (as is the "
            "default)."),
    )
    chat_template: Optional[str] = Field(
        default=None,
        description=(
            "A Jinja template to use for this conversion. "
            "As of transformers v4.44, default chat template is no longer "
            "allowed, so you must provide a chat template if the tokenizer "
            "does not define one."),
    )
    chat_template_kwargs: Optional[Dict[str, Any]] = Field(
        default=None,
        description=("Additional kwargs to pass to the template renderer. "
                     "Will be accessible by the chat template."),
    )
    mm_processor_kwargs: Optional[Dict[str, Any]] = Field(
        default=None,
        description=("Additional kwargs to pass to the HF processor."),
    )
    priority: int = Field(
        default=0,
        description=(
            "The priority of the request (lower means earlier handling; "
            "default: 0). Any priority other than 0 will raise an error "
            "if the served model does not use priority scheduling."))

Transcriptions API#

我们的 Transcriptions API 与 OpenAI 的 Transcriptions API 兼容;您可以使用 官方 OpenAI Python 客户端 与之交互。

代码示例:examples/online_serving/openai_transcription_client.py

Tokenizer API#

我们的 Tokenizer API 是 HuggingFace 风格的分词器 的简单包装器。它由两个端点组成

  • /tokenize 对应于调用 tokenizer.encode()

  • /detokenize 对应于调用 tokenizer.decode()

Pooling API#

我们的 Pooling API 使用 池化模型 编码输入提示,并返回相应的隐藏状态。

输入格式与 Embeddings API 相同,但输出数据可以包含任意嵌套列表,而不仅仅是浮点数的一维列表。

代码示例:examples/online_serving/openai_pooling_client.py

Score API#

我们的 Score API 可以应用交叉编码器模型或嵌入模型来预测句子对的分数。当使用嵌入模型时,分数对应于每个嵌入对之间的余弦相似度。通常,句子对的分数是指两个句子之间的相似度,范围为 0 到 1。

您可以在 sbert.net 上找到交叉编码器模型的文档。

代码示例:examples/online_serving/openai_cross_encoder_score.py

单句推理#

您可以将字符串传递给 text_1text_2,形成单个句子对。

请求

curl -X 'POST' \
  'http://127.0.0.1:8000/score' \
  -H 'accept: application/json' \
  -H 'Content-Type: application/json' \
  -d '{
  "model": "BAAI/bge-reranker-v2-m3",
  "encoding_format": "float",
  "text_1": "What is the capital of France?",
  "text_2": "The capital of France is Paris."
}'

响应

{
  "id": "score-request-id",
  "object": "list",
  "created": 693447,
  "model": "BAAI/bge-reranker-v2-m3",
  "data": [
    {
      "index": 0,
      "object": "score",
      "score": 1
    }
  ],
  "usage": {}
}

批量推理#

您可以将字符串传递给 text_1,将列表传递给 text_2,形成多个句子对,其中每对由 text_1text_2 中的字符串构建。对的总数为 len(text_2)

请求

curl -X 'POST' \
  'http://127.0.0.1:8000/score' \
  -H 'accept: application/json' \
  -H 'Content-Type: application/json' \
  -d '{
  "model": "BAAI/bge-reranker-v2-m3",
  "text_1": "What is the capital of France?",
  "text_2": [
    "The capital of Brazil is Brasilia.",
    "The capital of France is Paris."
  ]
}'

响应

{
  "id": "score-request-id",
  "object": "list",
  "created": 693570,
  "model": "BAAI/bge-reranker-v2-m3",
  "data": [
    {
      "index": 0,
      "object": "score",
      "score": 0.001094818115234375
    },
    {
      "index": 1,
      "object": "score",
      "score": 1
    }
  ],
  "usage": {}
}

您可以将列表传递给 text_1text_2,形成多个句子对,其中每对由 text_1 中的字符串和 text_2 中的相应字符串构建(类似于 zip())。对的总数为 len(text_2)

请求

curl -X 'POST' \
  'http://127.0.0.1:8000/score' \
  -H 'accept: application/json' \
  -H 'Content-Type: application/json' \
  -d '{
  "model": "BAAI/bge-reranker-v2-m3",
  "encoding_format": "float",
  "text_1": [
    "What is the capital of Brazil?",
    "What is the capital of France?"
  ],
  "text_2": [
    "The capital of Brazil is Brasilia.",
    "The capital of France is Paris."
  ]
}'

响应

{
  "id": "score-request-id",
  "object": "list",
  "created": 693447,
  "model": "BAAI/bge-reranker-v2-m3",
  "data": [
    {
      "index": 0,
      "object": "score",
      "score": 1
    },
    {
      "index": 1,
      "object": "score",
      "score": 1
    }
  ],
  "usage": {}
}

额外参数#

支持以下 池化参数

    additional_data: Optional[Any] = None

支持以下额外参数

    priority: int = Field(
        default=0,
        description=(
            "The priority of the request (lower means earlier handling; "
            "default: 0). Any priority other than 0 will raise an error "
            "if the served model does not use priority scheduling."))

Re-rank API#

我们的 Re-rank API 可以应用嵌入模型或交叉编码器模型来预测单个查询与文档列表之间相关性分数。通常,句子对的分数是指两个句子之间的相似度,范围为 0 到 1。

您可以在 sbert.net 上找到交叉编码器模型的文档。

rerank 端点支持流行的重排序模型,例如 BAAI/bge-reranker-base 和其他支持 score 任务的模型。此外,/rerank/v1/rerank/v2/rerank 端点与 Jina AI 的重排序 API 接口Cohere 的重排序 API 接口 兼容,以确保与流行的开源工具的兼容性。

代码示例:examples/online_serving/jinaai_rerank_client.py

示例请求#

请注意,top_n 请求参数是可选的,默认值为 documents 字段的长度。结果文档将按相关性排序,并且可以使用 index 属性来确定原始顺序。

请求

curl -X 'POST' \
  'http://127.0.0.1:8000/v1/rerank' \
  -H 'accept: application/json' \
  -H 'Content-Type: application/json' \
  -d '{
  "model": "BAAI/bge-reranker-base",
  "query": "What is the capital of France?",
  "documents": [
    "The capital of Brazil is Brasilia.",
    "The capital of France is Paris.",
    "Horses and cows are both animals"
  ]
}'

响应

{
  "id": "rerank-fae51b2b664d4ed38f5969b612edff77",
  "model": "BAAI/bge-reranker-base",
  "usage": {
    "total_tokens": 56
  },
  "results": [
    {
      "index": 1,
      "document": {
        "text": "The capital of France is Paris."
      },
      "relevance_score": 0.99853515625
    },
    {
      "index": 0,
      "document": {
        "text": "The capital of Brazil is Brasilia."
      },
      "relevance_score": 0.0005860328674316406
    }
  ]
}

额外参数#

支持以下 池化参数

    additional_data: Optional[Any] = None

支持以下额外参数

    priority: int = Field(
        default=0,
        description=(
            "The priority of the request (lower means earlier handling; "
            "default: 0). Any priority other than 0 will raise an error "
            "if the served model does not use priority scheduling."))