Skip to content
LlamaIndex 文档版本 跟随上游 源快照 1c33b66e 更新于 2026-10-18

使用 vLLM 有两种模式:本地和远程。我们先从前者开始,它要求本地有可用的 CUDA 环境。

安装 vLLM

pip install vllm
或者如果你想编译,可以从源码编译安装

Orca-7b 补全示例

%pip install llama-index-llms-vllm
import os

os.environ["HF_HOME"] = "model/"
from llama_index.llms.vllm import Vllm, VllmServer
llm = Vllm(
    model="microsoft/Orca-2-7b",
    tensor_parallel_size=4,
    max_new_tokens=100,
    vllm_kwargs={"swap_space": 1, "gpu_memory_utilization": 0.5},
)
llm.complete("[INST]You are a helpful assistant[/INST] What is a black hole ?")

LLama-2-7b 补全示例

llm = Vllm(
    model="codellama/CodeLlama-7b-hf",
    dtype="float16",
    tensor_parallel_size=4,
    temperature=0,
    max_new_tokens=100,
    vllm_kwargs={
        "swap_space": 1,
        "gpu_memory_utilization": 0.5,
        "max_model_len": 4096,
    },
)
llm.complete("import socket\n\ndef ping_exponential_backoff(host: str):")

Mistral chat 7b 补全示例

llm = Vllm(
    model="mistralai/Mistral-7B-Instruct-v0.1",
    dtype="float16",
    tensor_parallel_size=4,
    temperature=0,
    max_new_tokens=100,
    vllm_kwargs={
        "swap_space": 1,
        "gpu_memory_utilization": 0.5,
        "max_model_len": 4096,
    },
)
Vllm mock initialized
llm.complete(" What is a black hole ?")

通过 HTTP 调用 vLLM

在此模式下,无需安装 vllm 模型,也无需本地具备 CUDA。要设置 vLLM API,你可以遵循此处的指南。注意:llama-index-llms-vllm 模块是 vllm.entrypoints.api_server 的客户端,而后者仅是一个演示。
如果 vLLM 服务器以 vllm.entrypoints.openai.api_server 作为 OpenAI 兼容服务器启动,或通过 Docker 启动,你需要使用 llama-index-llms-openai-like 模块中的 OpenAILike 类

补全响应

from llama_index.core.llms import ChatMessage
llm = VllmServer(
    api_url="http://localhost:8000/generate", max_new_tokens=100, temperature=0
)
llm.complete("what is a black hole ?")
message = [ChatMessage(content="hello", role="user")]
llm.chat(message)

流式响应

list(llm.stream_complete("what is a black hole"))[-1]
message = [ChatMessage(content="what is a black hole", role="user")]
[x for x in llm.stream_chat(message)][-1]

异步响应

import asyncio

await llm.acomplete("What is a black hole")
await llm.achat(message)
[x async for x in await llm.astream_complete("what is a black hole")][-1]
[x async for x in await llm.astream_chat(message)][-1]

BytesRouter 是社区翻译站点,所有译文仅供参考,一切以官方英文原文为准。