text stringlengths 14 100k | source stringclasses 1
value | repo stringclasses 810
values | language stringclasses 13
values |
|---|---|---|---|
<|fim_prefix|># SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import os
from urllib.request import urlopen
from vllm import LLM, SamplingParams
os.environ["VLLM_ALLOW_LONG_MAX_MODEL_LEN"] = "1"
def load_prompt() -> str:
# Test cases with various lengths... | fim | vllm-project/vllm | python |
<|fim_prefix|># SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import httpx
from transformers import AutoTokenizer
GEN_ENDPOINT = "http://localhost:8000/inference/v1/generate"
DUMMY_API_KEY = "empty"
MODEL_NAME = "Qwen/Qwen3-0.6B"
transport = httpx.HTTPTranspo... | fim | vllm-project/vllm | python |
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from vllm import LLM, SamplingParams
from vllm.v1.metrics.reader import Counter, Gauge, Histogram, Vector
# Sample prompts.
prompts = [
"Hello, my name is",
"The president of the United States is",
"... | fim | vllm-project/vllm | python |
<|fim_suffix|> span.set_attribute("prompt", prompt)
headers = {}
TraceContextTextMapPropagator().inject(headers)
payload = {
"model": "facebook/opt-125m",
"prompt": prompt,
"max_tokens": 10,
"n": 3,
"use_beam_search": "true",
"temperature": 0.0,
# "s... | fim | vllm-project/vllm | python |
<|fim_suffix|>rompt in prompts:
response = requests.post(
tokenize_url,
json={"model": model, "prompt": prompt},
)
token_ids.append(response.json()["tokens"])
payload = {
"model": model,
"input": token_ids,
}
response = requests.post(classify_... | fim | vllm-project/vllm | python |
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# ruff: noqa: E501
"""Example Python client for multimodal classification API using vLLM API server
NOTE:
start a supported multimodal classification model server with `vllm serve`, e.g.
vllm serve muziyon... | fim | vllm-project/vllm | python |
<|fim_prefix|># SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from argparse import Namespace
from vllm import LLM, EngineArgs
from vllm.utils.argparse_utils import FlexibleArgumentParser
def parse_args():
parser = FlexibleArgumentParser()
parser = E... | fim | vllm-project/vllm | python |
<|fim_suffix|> print("-" * 60)
for prompt, output in zip(prompts, outputs):
embeds = output.outputs.embedding
embeds_trimmed = (
(str(embeds[:16])[:-1] + ", ...]") if len(embeds) > 16 else embeds
)
print(f"Prompt: {prompt!r} \nEmbeddings: {embeds_trimmed} (size={len(embed... | fim | vllm-project/vllm | python |
<|fim_prefix|># SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Example Python client for embedding API using vLLM API server
NOTE:
start a supported embeddings model server with `vllm serve`, e.g.
vllm serve intfloat/e5-small
"""
import argparse
imp... | fim | vllm-project/vllm | python |
<|fim_suffix|>f"http://{args.host}:{args.port}"
models_url = base_url + "/v1/models"
embeddings_url = base_url + "/v1/embeddings"
response = requests.get(models_url)
model = response.json()["data"][0]["id"]
embedding_size = 0
input_texts = [
"The best thing about vLLM is that it suppo... | fim | vllm-project/vllm | python |
<|fim_suffix|> api_key=openai_api_key,
base_url=openai_api_base,
)
models = client.models.list()
model = models.data[0].id
responses = client.embeddings.create(
# ruff: noqa: E501
input=[
"Hello my name is",
"The best thing about vLLM is that it support... | fim | vllm-project/vllm | python |
<|fim_prefix|># SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""
Example script demonstrating long text embedding with chunked processing in vLLM.
This example shows how to use vLLM's chunked processing feature to handle text
inputs that exceed the model's m... | fim | vllm-project/vllm | python |
<|fim_prefix|># SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the v<|fim_suffix|>/v1"
def main():
client = OpenAI(
# defaults to os.environ.get("OPENAI_API_KEY")
api_key=openai_api_key,
base_url=openai_api_base,
)
models = client.models.li... | fim | vllm-project/vllm | python |
<|fim_prefix|># SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# ruff: noqa: E501
"""
This example shows how to use vLLM for running offline inference with
the correct prompt format on vision language models for multimodal embedding.
For most models, the prompt... | fim | vllm-project/vllm | python |
<|fim_prefix|># SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# ruff: noqa: E501
"""Example Python client for multimodal embedding API using vLLM API server.
Refer to each `run_*` function for the command to run the server for that model.
"""
import argparse
... | fim | vllm-project/vllm | python |
<|fim_suffix|>
if __name__ == "__main__":
main()
<|fim_prefix|># SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import os
import pybase64 as base64
import torch
from vllm import LLM
# This example shows how to perform an offline inference that generates... | fim | vllm-project/vllm | python |
<|fim_suffix|>ndices: list[int] | None = None,
):
"""Build an input example by loading images in *file_paths*.
Args:
file_paths: list of file paths .
mean: list containing mean values for each band in the
images in *file_paths*.
std: list containing std values for each ban... | fim | vllm-project/vllm | python |
<|fim_suffix|>getcwd(), "online_prediction.tiff")
with open(out_path, "wb") as f:
f.write(decoded_image)
if __name__ == "__main__":
main()
<|fim_prefix|># SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import os
import pybase64 as base64
imp... | fim | vllm-project/vllm | python |
<|fim_suffix|>me is",
"The president of the United States is",
"The capital of France is",
"The future of AI is",
]
# Create an LLM.
# You should pass runner="pooling" for reward models
llm = LLM(**vars(args))
# Generate rewards. The output is a list of PoolingRequestOutput... | fim | vllm-project/vllm | python |
<|fim_prefix|># SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""
Example online usage of sequence reward models.
Run `vllm serve <model> --runner pooling`
to start up the server in vLLM. e.g.
vllm serve Skywork/Skywork-Reward-V2-Qwen3-0.6B
The key distincti... | fim | vllm-project/vllm | python |
<|fim_prefix|># SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""
Example offline usage of token reward models.
The key distinction between sequence classification and token classification
lies in their output granularity: sequence classification produces a s... | fim | vllm-project/vllm | python |
<|fim_suffix|> pprint.pprint(pooling_response.json())
print("-" * 50)
if __name__ == "__main__":
args = parse_args()
main(args)
<|fim_prefix|># SPDX-License-Identifier: Apache-2.0
# SPDX<|fim_middle|>-FileCopyrightText: Copyright contributors to the vLLM project
"""
Example online usage of token reward m... | fim | vllm-project/vllm | python |
<|fim_prefix|># SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyr<|fim_suffix|> rerank_v1_result = cohere_rerank(cohere_v1, model, query, documents)
print("-" * 50)
print("rerank_v1_result:\n", rerank_v1_result)
print("-" * 50)
# or the v2
cohere_v2 = cohere.ClientV2("sk-fake-key", base_url="ht... | fim | vllm-project/vllm | python |
<|fim_prefix|># SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""
Example of using ColBERT late interaction models for reranking and scoring.
ColBERT (Contextualized Late Interaction over BERT) uses per-token embeddings
and MaxSim scoring for document rerankin... | fim | vllm-project/vllm | python |
<|fim_prefix|># SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""
Example of using ColModernVBERT late interaction model for reranking.
ColModernVBERT is a multi-modal ColBERT-style model combining a SigLIP
vision encoder with a ModernBERT text encoder. It pro... | fim | vllm-project/vllm | python |
<|fim_suffix|>nts,
}
response = requests.post(f"{BASE_URL}/score", headers=headers, json=data)
if response.status_code == 200:
result = response.json()
print(f"\n Query: {query}\n")
for item in result["data"]:
idx = item["index"]
score = item["score"]
... | fim | vllm-project/vllm | python |
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# ruff: noqa: E501
"""
Example of using ColQwen3 late interaction model for reranking and scoring.
ColQwen3 is a multi-modal ColBERT-style model based on Qwen3-VL.
It produces per-token embeddings and uses MaxSim... | fim | vllm-project/vllm | python |
<|fim_suffix|>"Converting *ForCausalLM models to "
"*ForSequenceClassification models."
)
parser.add_argument(
"--model_name",
type=str,
default="BAAI/bge-reranker-v2-gemma",
help="HuggingFace model name or local path",
)
parser.add_argument(
"--classifier... | fim | vllm-project/vllm | python |
<|fim_prefix|># SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# ruff: noqa: E501
"""
What is the difference between the official original version and one
that has been converted into a sequence classification model?
Qwen3-Reranker is a language model that doi... | fim | vllm-project/vllm | python |
<|fim_suffix|>se.json(), indent=2))
else:
# Handle request failure
print(f"Request failed with status code: {response.status_code}")
print(response.text)
if __name__ == "__main__":
main()
<|fim_prefix|># SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributo... | fim | vllm-project/vllm | python |
<|fim_prefix|># SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""
Example of using the OpenAI entrypoint's rerank API which is compatible with
Jina and Coher<|fim_suffix|> "query": "What is the capital of France?",
"documents": [
"The capital of Bra... | fim | vllm-project/vllm | python |
<|fim_suffix|>zil is Brasilia.",
"The capital of France is Paris.",
]
prompt = {"model": model_name, "queries": queries, "documents": documents}
score_response = post_http_request(prompt=prompt, api_url=api_url)
print("\nPrompt when queries and documents are both lists:")
pprint.pprint(promp... | fim | vllm-project/vllm | python |
<|fim_prefix|># SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# ruff: noqa: E501
from argparse import Namespace
from pathlib import Path
from typing import Any
from vllm import LLM, EngineArgs
from vllm.utils.argparse_utils import FlexibleArgumentParser
def ... | fim | vllm-project/vllm | python |
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# ruff: noqa: E501
"""
Example of using the rerank API with template.
This script demonstrates how to interact with a vLLM server running
a reranking model via the REST API.
Before running this script, start the ... | fim | vllm-project/vllm | python |
<|fim_prefix|># SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# ruff: noqa: E501
"""
Example Python client for multimodal rerank API which is compatible with
Jina and Cohere https://jina.ai/reranker
Run `vllm serve <model> --runner pooling` to start up the se... | fim | vllm-project/vllm | python |
<|fim_prefix|># SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""
This example shows how to use vLLM for running offline inference with
vision language reranker models for multimodal scoring tasks.
Vision language rerankers score the relevance between a text q... | fim | vllm-project/vllm | python |
<|fim_suffix|>pprint(response.json())
print("Query: string & Document: list")
prompt = {
"model": model,
"queries": query,
"documents": [
document,
{"content": [documents[0]]},
{"content": [documents[1]]},
{"content": [documents[0], docume... | fim | vllm-project/vllm | python |
<|fim_suffix|>ager=True,
hf_overrides={"architectures": ["Qwen3ASRForcedAlignerForTokenClassification"]},
)
return parser.parse_args()
def build_prompt(words: list[str]) -> str:
"""Build the forced alignment prompt from a word list.
Format: <|audio_start|><|audio_pad|><|audio_end|>
... | fim | vllm-project/vllm | python |
<|fim_suffix|>ed from https://huggingface.co/boltuix/NeuroBERT-NER
from argparse import Namespace
from vllm import LLM, EngineArgs
from vllm.utils.argparse_utils import FlexibleArgumentParser
def parse_args():
parser = FlexibleArgumentParser()
parser = EngineArgs.add_cli_args(parser)
# Set example speci... | fim | vllm-project/vllm | python |
<|fim_suffix|>pe=str, default="localhost")
parser.add_argument("--port", type=int, default=8000)
parser.add_argument("--model", type=str, default="boltuix/NeuroBERT-NER")
return parser.parse_args()
def main(args):
from transformers import AutoConfig, AutoTokenizer
api_url = f"http://{args.host}:... | fim | vllm-project/vllm | python |
<|fim_prefix|># SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# ruff: noqa: E501
"""
Example online usage of Pooling API for ColQwen3 multi-vector retrieval.
ColQwen3 is a multi-modal late interaction model based on Qwen3-VL that
produces per-token embeddings... | fim | vllm-project/vllm | python |
<|fim_prefix|># SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import torch
from vllm import LLM
from vllm.config import PoolerConfig
from vllm.inputs import TextPrompt
from vllm.multimodal.utils import fetch_image
def main():
# Initialize model
mode... | fim | vllm-project/vllm | python |
<|fim_prefix|># SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# ruff: noqa: E501
import torch.nn.functional as F
from vllm import LLM
query = "What are the health benefits of green tea?"
documents = [
"Green tea contains antioxidants called catechins tha... | fim | vllm-project/vllm | python |
<|fim_prefix|># SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from argparse import Namespace
from vllm import LLM, EngineArgs
from vllm.config import PoolerConfig
from vllm.utils.argparse_utils import FlexibleArgumentParser
def parse_args():
parser = Fl... | fim | vllm-project/vllm | python |
<|fim_suffix|>ng and documents is a list:")
pprint.pprint(prompt)
print("\nScore Response:")
pprint.pprint(score_response.json())
if __name__ == "__main__":
args = parse_args()
main(args)
<|fim_prefix|># SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vL... | fim | vllm-project/vllm | python |
<|fim_suffix|>one or more files separately.
#
# ds.write_parquet("s3://<your-output-bucket>")
<|fim_prefix|># SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""
This example shows how to use Ray Data for data parallel batch inference.
Ray Data is a data process... | fim | vllm-project/vllm | python |
<|fim_prefix|>#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import argparse
import json
import sys
import requests
def scale(host, port, new_dp_size):
url = f"http://{host}:{port}/scale_elastic_ep"
payload = {"new_data_paral... | fim | vllm-project/vllm | python |
<|fim_prefix|># SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""
Deploy DeepSeek R1 or V3 with Ray Serve LLM.
Ray Serve LLM is a scalable and production-grade model serving library built
on the Ray distributed computing framework and first-class support fo<|f... | fim | vllm-project/vllm | python |
<|fim_suffix|>unks = list(tool_calls_stream)
reasoning, arguments, function_names = extract_reasoning_and_calls(chunks)
print(f"reasoning: {reasoning}")
print(f"function name: {function_names[0]}")
print(f"function arguments: {arguments[0]}")
print("----------Full Generate With Named Function Cal... | fim | vllm-project/vllm | python |
<|fim_prefix|># SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""
An example shows how to generate chat completions from reasoning models
like DeepSeekR1.
To run this example, you need to start the vLLM server
with the reasoning parser:
```bash
vllm serve dee... | fim | vllm-project/vllm | python |
<|fim_suffix|> printed_content = False
for chunk in stream:
# Safely extract reasoning and content from delta,
# defaulting to None if attributes don't exist or are empty strings
reasoning = getattr(chunk.choices[0].delta, "reasoning", None) or None
content = getattr(chunk.choices... | fim | vllm-project/vllm | python |
<|fim_suffix|>input_messages,
)
print(response_2.output_text)
# I am Qwen, a large language model developed by Alibaba Cloud.
# I am designed to assist with a wide range of tasks, including
# answering questions, creating content, coding, and engaging in
# conversations. I can help with various ... | fim | vllm-project/vllm | python |
<|fim_suffix|>ut, pause_token_index
async def pause_after_n_tokens(self):
"""Wait for any request to set the pause flag, then pause."""
while not self._request_pause_flag:
await asyncio.sleep(0)
await super().pause_generation(mode="keep")
await asyncio.sleep(5)
s... | fim | vllm-project/vllm | python |
<|fim_suffix|>t, generated_text in zip(prompts, outputs_updated):
print(f"Prompt: {prompt!r}\nGenerated text: {generated_text!r}")
print("-" * 50)
# Note: The training model and IPC handles remain in memory.
# In a real RLHF training loop, you would update the training model
# and create ne... | fim | vllm-project/vllm | python |
<|fim_prefix|># SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""
Demonstrates reinforcement learning from human feedback (RLHF) using vLLM
via HTTP API, with native weight syncing APIs.
Unlike rlhf.py which creates a vLLM instance programmatically, this scrip... | fim | vllm-project/vllm | python |
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""
Demonstrates reinforcement learning from human feedback (RLHF) using vLLM and Ray,
with IPC-based weight syncing APIs
The script colocates the training and inference workloads onto the same GPU using Ray.
Th... | fim | vllm-project/vllm | python |
<|fim_suffix|> # gate, up = linear(x, gate_up_proj[i]).chunk(2, dim=-1)
# → rows [:I] of gate_up_proj[i] are gate, rows [I:] are up.
params = self.model.state_dict()
for name in list(params.keys()):
param = params.pop(name)
if isinstance(param, DTen... | fim | vllm-project/vllm | python |
<|fim_prefix|># SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""
Demonstrates reinforcement learning using vLLM and Ray,
with native weight syncing APIs at engine instance.
The script separates training and inference workloads onto distinct GPUs
so that Ray c... | fim | vllm-project/vllm | python |
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""
RLHF with FSDP2 training (4 GPUs) and vLLM expert-parallel inference (4 GPUs).
8-GPU layout:
Training — 4 GPUs, PyTorch FSDP2 (fully_shard)
Inference — 4 GPUs, vLLM AsyncLLMEngine with expert parallelism... | fim | vllm-project/vllm | python |
<|fim_suffix|>l(llm)
ray.init()
try:
train_model = TrainModel.remote(MODEL_NAME)
pg_inference = placement_group([{"GPU": 1, "CPU": 0}])
ray.get(pg_inference.ready())
scheduling_inference = PlacementGroupSchedulingStrategy(
placement_group=pg_inference,
placement_group_capture_child_t... | fim | vllm-project/vllm | python |
<|fim_prefix|># SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""
End-to-end example for routed experts capture with hybrid models.
Validates that:
1. routed_experts is returned in CompletionOutput for MoE models.
2. Expert IDs are within valid range.
3. Resul... | fim | vllm-project/vllm | python |
<|fim_suffix|>load_format": "auto"}},)
)
# Now reload real weights inplace
llm.collective_rpc("reload_weights")
# Check outputs make sense
outputs = llm.generate(prompts, sampling_params)
print("\nOutputs make sense after loading real weights:")
print_prompts_and_outputs(outputs)
if __nam... | fim | vllm-project/vllm | python |
<|fim_suffix|>model": model,
"response_format": "json",
}
response = requests.post(url, files=files, data=data, stream=True)
response.raise_for_status()
tokens: list[str] = []
for chunk in response.iter_lines(
chunk_size=8192, decode_unicode=False, delimi... | fim | vllm-project/vllm | python |
<|fim_suffix|>files, data=data, stream=True
)
for chunk in response.iter_lines(
chunk_size=8192, decode_unicode=False, delimiter=b"\n"
):
if chunk:
data = chunk[len("data: ") :]
data = json.loads(data.decode("utf-8"))
data =... | fim | vllm-project/vllm | python |
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import asyncio
import json
import httpx
from openai import OpenAI
from vllm.assets.audio import AudioAsset
def sync_openai(audio_path: str, client: OpenAI, model: str):
with open(audio_path, "rb") as f:
... | fim | vllm-project/vllm | python |
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""
This script demonstrates how to use the vLLM Realtime WebSocket API to perform
audio transcription by uploading an audio file.
Before running this script, you must start the vLLM server with a realtime-capabl... | fim | vllm-project/vllm | python |
<|fim_suffix|>"--model",
type=str,
default="mistralai/Voxtral-Mini-4B-Realtime-2602",
help="Model that is served and should be pinged.",
)
parser.add_argument(
"--host", type=str, default="localhost", help="vLLM server host"
)
parser.add_argument("--port", type=int, defau... | fim | vllm-project/vllm | python |
<|fim_prefix|># SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# ruff: noqa
import json
import random
import string
from vllm import LLM
from vllm.sampling_params import SamplingParams
# This script is an offline demo for function calling
#
# If you want to r... | fim | vllm-project/vllm | python |
<|fim_suffix|># Handle arguments from streamed tool calls
arguments = handle_tool_calls_arguments(chunks)
if len(arguments):
print(f"streamed tool call arguments: {arguments[-1]}\n")
print("-" * 70)
# Add tool call results to the conversation
messages.append(
{
"role":... | fim | vllm-project/vllm | python |
<|fim_prefix|># SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""
To run this example, you can start the vLLM server
without any specific flags:
```bash
vllm serve unsloth/Llama-3.2-1B-Instruct \
--structured-outputs-config.backend outlines
```
This examp... | fim | vllm-project/vllm | python |
<|fim_prefix|># SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# ruff: noqa: E501
"""
Set up this example by starting a vLLM OpenAI-compatible server with tool call
options enabled for xLAM-2 models:
vllm serve --model Salesforce/Llama-xLAM-2-8b-fc-r --enable-a... | fim | vllm-project/vllm | python |
<|fim_suffix|>sage"),
]
# Execute all test cases
for query, test_name in test_cases:
run_test_case(query, test_name)
time.sleep(1) # Small delay between tests
print("\nAll tests completed.")
if __name__ == "__main__":
main()
<|fim_prefix|># SPDX-License-Identifier: Apache-2.0
# ... | fim | vllm-project/vllm | python |
<|fim_suffix|>n",
], # Allow search and open, block find
"read_only": False,
},
}
],
)
print(f"Status: {response.status}")
print(f"Output: {response.output_text}")
print()
def main():
"""Run all examples."""
print("\... | fim | vllm-project/vllm | python |
<|fim_suffix|>tput": str(result),
}
)
response_2 = client.responses.create(
model=model,
input=input_messages,
tools=tools,
)
print(response_2.output_text)
if __name__ == "__main__":
main()
<|fim_prefix|># SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText... | fim | vllm-project/vllm | python |
<|fim_suffix|> while let Some(event) = stream.next().await.transpose()? {
match event {
ChatEvent::Start { .. } => {
saw_start = true;
}
ChatEvent::BlockStart { kind, .. } => {
if saw_stream_output {
... | fim | vllm-project/vllm | rust |
<|fim_suffix|>ltimodalModelInfo::from_paths(
model_id.clone(),
(!model_type.is_empty()).then_some(model_type.to_string()),
files.config_path.as_deref(),
files.preprocessor_config_path.as_deref(),
tokenizer.clone(),
)?
};... | fim | vllm-project/vllm | rust |
<|fim_suffix|>
}
<|fim_prefix|>use std::collections::HashMap;
use std::sync::Arc;
use serde_json::Value;
use vllm_text::{DynTextBackend, TextBackend};
use crate::error::Result;
use crate::multimodal::MultimodalModelInfo;
use crate::output::DynChatOutputProcessor;
use crate::renderer::DynChatRenderer;
use crate::reque... | fim | vllm-project/vllm | rust |
<|fim_suffix|>nt: {message}")]
ToolCallStreamInvariant { message: String },
#[error(transparent)]
Text(#[from] vllm_text::Error),
#[error(transparent)]
Tokenizer(#[from] vllm_tokenizer::TokenizerError),
}
pub type Result<T> = std::result::Result<T, Error>;
/// Format the available-parser suffix us... | fim | vllm-project/vllm | rust |
<|fim_suffix|>tring> {
Some(
self.iter()
.filter_map(|block| match block {
AssistantContentBlock::Reasoning { text } => Some(text.as_str()),
_ => None,
})
.collect(),
)
.filter(|s: &String| !s.is_... | fim | vllm-project/vllm | rust |
<|fim_prefix|>//! Minimal chat facade above [`vllm_text`].
//!
//! This crate keeps the northbound boundary intentionally small:
//! `messages -> rendered prompt -> tokenized prompt -> engine request ->
//! streamed structured assistant events`. The request side remains text-first,
//! while the response side can emit ... | fim | vllm-project/vllm | rust |
use std::collections::HashMap;
use half::{bf16, f16};
use llm_multimodal::{ModelSpecificValue, PreprocessedImages};
use vllm_engine_core_client::protocol::ModelDtype;
use vllm_engine_core_client::protocol::multimodal::MmKwargValue as ProtocolKwargValue;
use vllm_engine_core_client::protocol::tensor::{ShapeExt as _, Wi... | fim | vllm-project/vllm | rust |
<|fim_suffix|>s = vec![llama4_multi_tile_replacement()];
let ranges = info.expand_prompt_tokens(&mut prompt_token_ids, replacements).unwrap();
assert_eq!(
prompt_token_ids,
vec![
1,
LLAMA4_IMAGE_START_ID,
LLAMA4_PATCH_ID,
... | fim | vllm-project/vllm | rust |
//! Default output processing pipeline.
mod reasoning;
mod tool;
use std::sync::Once;
use futures::{Stream, StreamExt as _};
use tracing::info;
use trait_set::trait_set;
use vllm_text::tokenizer::DynTokenizer;
use self::reasoning::reasoning_event_stream;
use self::tool::tool_event_stream;
use super::structured::str... | fim | vllm-project/vllm | rust |
<|fim_suffix|>TokenUsage {
prompt_token_count: 3,
output_token_count: 0,
cached_token_count: 0,
},
finish_reason: FinishReason::stop_eos(),
kv_transfer_params: None,
},
... | fim | vllm-project/vllm | rust |
<|fim_prefix|>//! Adapts plain assistant text deltas into tool-call-aware assistant updates.
//!
//! This stage runs after reasoning separation and before final block assembly.
//! It only inspects normal assistant text, leaves reasoning deltas untouched,
//! and translates incremental tool parsing output into internal... | fim | vllm-project/vllm | rust |
<|fim_suffix|>)
.await;
}
if let Some(finished) = finished {
y.yield_ok(AssistantEvent::Done {
usage: finished.usage,
finish_reason: finished.finish_reason,
kv_transfer_params... | fim | vllm-project/vllm | rust |
<|fim_suffix|>nnel)
.with_recipient(format!("functions.{name}"))
.with_content_type("json")
}
fn decoded_start() -> DecodedTextEvent {
DecodedTextEvent::Start {
prompt_token_ids: Arc::<[u32]>::from([]),
prompt_logprobs: None,
}
}
fn finished() -> Finished {
Finished {
... | fim | vllm-project/vllm | rust |
<|fim_prefix|>use std::pin::Pin;
use std::sync::Arc;
use futures::Stream;
use subenum::subenum;
use trait_set::trait_set;
use uuid::Uuid;
use vllm_llm::TokenUsage;
use vllm_text::output::{DecodedLogprobs, DecodedPromptLogprobs, DecodedTextEvent};
use crate::FinishReason;
use crate::error::Result;
use crate::event::{A... | fim | vllm-project/vllm | rust |
<|fim_prefix|>//! Adapts parsed assistant updates into structured chat events.
//!
//! This module remains the final assembly stage in `vllm-chat`. Token-to-text
//! decoding still lives in `decoded.rs`, while reasoning separation and tool
//! parsing are handled earlier by their own adapters. This stage consumes those... | fim | vllm-project/vllm | rust |
<|fim_prefix|>pub mod reasoning;
pub mod tool;
use std::collections::HashMap;
use std::convert::Infallible;
use std::fmt;
use std::str::FromStr;
use serde_with::{DeserializeFromStr, SerializeDisplay};
/// Specify which reasoning or tool-call parser implementation to use.
#[derive(Debug, Clone, PartialEq, Eq, Default... | fim | vllm-project/vllm | rust |
<|fim_suffix|>names::STEP3)
.register_pattern("seed-oss", names::SEED_OSS)
.register_pattern("seedoss", names::SEED_OSS)
.register_pattern("minimax", names::MINIMAX_M2)
.register_pattern("mm-m2", names::MINIMAX_M2)
.register_pattern("cohere", names::COHERE_CMD... | fim | vllm-project/vllm | rust |
use std::sync::Arc;
use vllm_tokenizer::Tokenizer;
use super::{ReasoningParserFactory, names};
struct FakeTokenizer;
impl Tokenizer for FakeTokenizer {
fn encode(&self, text: &str, _add_special_tokens: bool) -> vllm_tokenizer::Result<Vec<u32>> {
Ok(text.chars().map(u32::from).collect())
}
fn de... | fim | vllm-project/vllm | rust |
<|fim_suffix|>EEK_V3)
.register_pattern("deepseek-v4", names::DEEPSEEK_V4)
.register_pattern("deepseek_v4", names::DEEPSEEK_V4)
.register_pattern("deepseek-v3.2", names::DEEPSEEK_V32)
.register_pattern("deepseek-v3.1", names::DEEPSEEK_V31)
.register_pattern("d... | fim | vllm-project/vllm | rust |
<|fim_prefix|>use vllm_tool_parser::Result;
use super::{ToolParser, ToolParserFactory, ToolParserOutput, names};
use crate::Error;
use crate::request::ChatTool;
struct FakeToolParser;
impl ToolParser for FakeToolParser {
fn create(_tools: &[ChatTool]) -> Result<Box<dyn ToolParser>>
where
Self: Sized ... | fim | vllm-project/vllm | rust |
<|fim_prefix|>//! DeepSeek V3.2 prompt renderer.
use std::collections::{HashMap, HashSet};
use std::fmt::Write as _;
use serde::Serialize;
use serde_json::Value;
use serde_json_fmt::JsonFormat;
use crate::error::{Error, Result};
use crate::request::{ChatContent, ChatMessage, ChatRequest, ChatRole, ChatTool};
use cra... | fim | vllm-project/vllm | rust |
<|fim_prefix|>mod encoding;
use vllm_text::Prompt;
use su<|fim_suffix|>derive(Debug, Clone, Copy, Default)]
pub struct DeepSeekV32ChatRenderer;
impl DeepSeekV32ChatRenderer {
/// Create the dedicated DeepSeek V3.2 renderer.
pub fn new() -> Self {
Self
}
}
impl ChatRenderer for DeepSeekV32ChatRen... | fim | vllm-project/vllm | rust |
<|fim_prefix|>use std::fs;
use std::path::PathBuf;
use expect_test::{ExpectFile, expect, expect_file};
use serde::Deserialize;
use serde_json::{Value, json};
use thiserror_ext::AsReport;
use super::DeepSeekV32ChatRenderer;
use crate::error::Error;
use crate::event::{AssistantContentBlock, AssistantToolCall};
use crat... | fim | vllm-project/vllm | rust |
<|fim_suffix|>t > 0 {
out.push_str("\n\n");
}
let ChatMessage::ToolResponse { content, .. } = &messages[*message_index] else {
unreachable!("tool response block should only contain tool messages");
};
write_tool_result(out, content)?;
}
Ok(())
}
/// Retu... | fim | vllm-project/vllm | rust |
<|fim_suffix|> Ok(RenderedPrompt {
prompt: Prompt::Text(encoding::render_request(request)?),
})
}
}
#[cfg(test)]
mod tests;
<|fim_prefix|>mod encoding;
use vllm_text::Prompt;
use super::{ChatRenderer, RenderedPrompt};
use crate::Result;
use <|fim_middle|>crate::request::ChatRequest;
///... | fim | vllm-project/vllm | rust |
<|fim_suffix|> .insert("thinking".to_string(), Value::Bool(true));
request.chat_options.template_kwargs.insert(
"reasoning_effort".to_string(),
Value::String("max".to_string()),
);
let rendered = render_request(&request);
expect!["<|begin▁of▁sentence|><|User|>solve it<|Assistant|>... | fim | vllm-project/vllm | rust |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.