mcpField
S
sglang

sglang

github.com/kalarislabs其他7343 次安装4 天前更新
代码仓库

关于 sglang

这项技能指南介绍 SGLang,这是一款用于 LLM 和视觉语言模型的推理服务框架。重点涵盖结构化生成,以及面向重复提示词和上下文的 RadixAttention 缓存。

主要功能

  1. 01自动缓存共享前缀
  2. 02JSON、正则表达式和语法约束
  3. 03函数调用工作流
  4. 04多轮对话支持
  5. 05连续批处理
  6. 06兼容 OpenAI 的 API

适用场景

  1. 01生成符合 Schema 约束的 JSON
  2. 02为重复提示词的 Agent 提供服务
  3. 03处理多轮对话
  4. 04批处理并行推理请求

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/kalarislabs/research-agent-skills --skill sglang

安装后在 Claude Code 中输入/sglang确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

references/
deployment.md
radix-attention.md
structured-generation.md

详细介绍

SGLang

面向大模型和 VLM 的高性能服务框架,采用 RadixAttention 实现前缀自动缓存。

何时使用 SGLang

在以下情况下使用 SGLang:

  • 需要结构化输出(JSON、正则表达式、语法)
  • 构建带有重复前缀(系统提示词、工具)的 Agent
  • 构建使用函数调用的 Agent 工作流
  • 处理共享上下文的多轮对话
  • 需要更快的 JSON 解码速度(比标准方式快 3×)

在以下情况下改用 vLLM:

  • 只需简单的文本生成,不需要结构化输出
  • 不需要前缀缓存
  • 想要成熟且经过广泛测试的生产系统

在以下情况下改用 TensorRT-LLM:

  • 追求单请求的最低延迟(不需要批处理)
  • 仅部署在 NVIDIA 平台
  • 需要在 H100 上使用 FP8/INT4 量化

快速入门

安装
# pip install (recommended)
pip install "sglang[all]"

# With FlashInfer (faster, CUDA 11.8/12.1)
pip install sglang[all] flashinfer -i https://flashinfer.ai/whl/cu121/torch2.4/

# From source
git clone https://github.com/sgl-project/sglang.git
cd sglang
pip install -e "python[all]"
启动服务
# Basic server (Llama 3-8B)
python -m sglang.launch_server \
    --model-path meta-llama/Meta-Llama-3-8B-Instruct \
    --port 30000

# With RadixAttention (automatic prefix caching)
python -m sglang.launch_server \
    --model-path meta-llama/Meta-Llama-3-8B-Instruct \
    --port 30000 \
    --enable-radix-cache  # Default: enabled

# Multi-GPU (tensor parallelism)
python -m sglang.launch_server \
    --model-path meta-llama/Meta-Llama-3-70B-Instruct \
    --tp 4 \
    --port 30000
基础推理
import sglang as sgl

# Set backend
sgl.set_default_backend(sgl.OpenAI("http://localhost:30000/v1"))

# Simple generation
@sgl.function
def simple_gen(s, question):
    s += "Q: " + question + "\n"
    s += "A:" + sgl.gen("answer", max_tokens=100)

# Run
state = simple_gen.run(question="What is the capital of France?")
print(state["answer"])
# Output: "The capital of France is Paris."
结构化 JSON 输出
import sglang as sgl

@sgl.function
def extract_person(s, text):
    s += f"Extract person information from: {text}\n"
    s += "Output JSON:\n"

    # Constrained JSON generation
    s += sgl.gen(
        "json_output",
        max_tokens=200,
        regex=r'\{"name": "[^"]+", "age": \d+, "occupation": "[^"]+"\}'
    )

# Run
state = extract_person.run(
    text="John Smith is a 35-year-old software engineer."
)
print(state["json_output"])
# Output: {"name": "John Smith", "age": 35, "occupation": "software engineer"}

RadixAttention(核心创新)

功能:自动缓存并复用不同请求中的公共前缀。

性能:

  • 对共享系统提示词的 Agent 工作负载,速度提升 5×
  • 对重复示例的少样本提示,速度提升 10×
  • 零配置——自动生效

工作原理:

  1. 根据所有已处理的 Token 构建基数树
  2. 自动检测共享前缀
  3. 为匹配的前缀复用 KV 缓存
  4. 只计算新 Token

示例(带系统提示词的 Agent):

Request 1: [SYSTEM_PROMPT] + "What's the weather?"
→ Computes full prompt (1000 tokens)

Request 2: [SAME_SYSTEM_PROMPT] + "Book a flight"
→ Reuses system prompt KV cache (998 tokens)
→ Only computes 2 new tokens
→ 5× faster!

结构化生成模式

使用 Schema 生成 JSON
@sgl.function
def structured_extraction(s, article):
    s += f"Article: {article}\n\n"
    s += "Extract key information as JSON:\n"

    # JSON schema constraint
    schema = {
        "type": "object",
        "properties": {
            "title": {"type": "string"},
            "author": {"type": "string"},
            "summary": {"type": "string"},
            "sentiment": {"type": "string", "enum": ["positive", "negative", "neutral"]}
        },
        "required": ["title", "author", "summary", "sentiment"]
    }

    s += sgl.gen("info", max_tokens=300, json_schema=schema)

state = structured_extraction.run(article="...")
print(state["info"])
# Output: Valid JSON matching schema
使用正则表达式约束生成
@sgl.function
def extract_email(s, text):
    s += f"Extract email from: {text}\n"
    s += "Email: "

    # Email regex pattern
    s += sgl.gen(
        "email",
        max_tokens=50,
        regex=r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}'
    )

state = extract_email.run(text="Contact [email protected] for details")
print(state["email"])
# Output: "[email protected]"
基于语法的生成
@sgl.function
def generate_code(s, description):
    s += f"Generate Python code for: {description}\n"
    s += "```python\n"

    # EBNF grammar for Python
    python_grammar = """
    ?start: function_def
    function_def: "def" NAME "(" [parameters] "):" suite
    parameters: parameter ("," parameter)*
    parameter: NAME
    suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT
    """

    s += sgl.gen("code", max_tokens=200, grammar=python_grammar)
    s += "\n```"

使用函数调用的 Agent 工作流

import sglang as sgl

# Define tools
tools = [
    {
        "name": "get_weather",
        "description": "Get weather for a location",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {"type": "string"}
            }
        }
    },
    {
        "name": "book_flight",
        "description": "Book a flight",
        "parameters": {
            "type": "object",
            "properties": {
                "from": {"type": "string"},
                "to": {"type": "string"},
                "date": {"type": "string"}
            }
        }
    }
]

@sgl.function
def agent_workflow(s, user_query, tools):
    # System prompt (cached with RadixAttention)
    s += "You are a helpful assistant with access to tools.\n"
    s += f"Available tools: {tools}\n\n"

    # User query
    s += f"User: {user_query}\n"
    s += "Assistant: "

    # Generate with function calling
    s += sgl.gen(
        "response",
        max_tokens=200,
        tools=tools,  # SGLang handles tool call format
        stop=["User:", "\n\n"]
    )

# Multiple queries reuse system prompt
state1 = agent_workflow.run(
    user_query="What's the weather in NYC?",
    tools=tools
)
# First call: Computes full system prompt

state2 = agent_workflow.run(
    user_query="Book a flight to LA",
    tools=tools
)
# Second call: Reuses system prompt (5× faster)

性能基准测试

RadixAttention 加速效果

少样本提示(提示中包含 10 个示例):

  • vLLM:2.5 秒/请求
  • SGLang:0.25 秒/请求(快 10×)
  • 吞吐量:提高 4×

Agent 工作流(1000 Token 的系统提示词):

  • vLLM:1.8 秒/请求
  • SGLang:0.35 秒/请求(快 5×)

JSON 解码:

  • 标准方式:45 Token/秒
  • SGLang:135 Token/秒(快 3×)
吞吐量(Llama 3-8B,A100)
工作负载vLLMSGLang加速比
简单生成2500 Token/秒2800 Token/秒1.12×
少样本(10 个示例)500 Token/秒5000 Token/秒10×
Agent(工具调用)800 Token/秒4000 Token/秒5×
JSON 输出600 Token/秒2400 Token/秒4×

多轮对话

@sgl.function
def multi_turn_chat(s, history, new_message):
    # System prompt (always cached)
    s += "You are a helpful AI assistant.\n\n"

    # Conversation history (cached as it grows)
    for msg in history:
        s += f"{msg['role']}: {msg['content']}\n"

    # New user message (only new part)
    s += f"User: {new_message}\n"
    s += "Assistant: "
    s += sgl.gen("response", max_tokens=200)

# Turn 1
history = []
state = multi_turn_chat.run(history=history, new_message="Hi there!")
history.append({"role": "User", "content": "Hi there!"})
history.append({"role": "Assistant", "content": state["response"]})

# Turn 2 (reuses Turn 1 KV cache)
state = multi_turn_chat.run(history=history, new_message="What's 2+2?")
# Only computes new message (much faster!)

# Turn 3 (reuses Turn 1 + Turn 2 KV cache)
state = multi_turn_chat.run(history=history, new_message="Tell me a joke")
# Progressively faster as history grows

高级功能

推测解码
# Launch with draft model (2-3× faster)
python -m sglang.launch_server \
    --model-path meta-llama/Meta-Llama-3-70B-Instruct \
    --speculative-model meta-llama/Meta-Llama-3-8B-Instruct \
    --speculative-num-steps 5
多模态(视觉模型)
@sgl.function
def describe_image(s, image_path):
    s += sgl.image(image_path)
    s += "Describe this image in detail: "
    s += sgl.gen("description", max_tokens=200)

state = describe_image.run(image_path="photo.jpg")
print(state["description"])
批处理和并行请求
# Automatic batching (continuous batching)
states = sgl.run_batch(
    [
        simple_gen.bind(question="What is AI?"),
        simple_gen.bind(question="What is ML?"),
        simple_gen.bind(question="What is DL?"),
    ]
)

# All 3 processed in single batch (efficient)

兼容 OpenAI 的 API

# Start server with OpenAI API
python -m sglang.launch_server \
    --model-path meta-llama/Meta-Llama-3-8B-Instruct \
    --port 30000

# Use with OpenAI client
curl http://localhost:30000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "default",
    "messages": [
      {"role": "system", "content": "You are helpful"},
      {"role": "user", "content": "Hello"}
    ],
    "temperature": 0.7,
    "max_tokens": 100
  }'

# Works with OpenAI Python SDK
from openai import OpenAI
client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY")

response = client.chat.completions.create(
    model="default",
    messages=[{"role": "user", "content": "Hello"}]
)

支持的模型

文本模型:

  • Llama 2、Llama 3、Llama 3.1、Llama 3.2
  • Mistral、Mixtral
  • Qwen、Qwen2、QwQ
  • DeepSeek-V2、DeepSeek-V3
  • Gemma、Phi-3

视觉模型:

  • LLaVA、LLaVA-OneVision
  • Phi-3-Vision
  • Qwen2-VL

来自 HuggingFace 的 100+ 个模型

硬件支持

NVIDIA:A100、H100、L4、T4(CUDA 11.8+) AMD:MI300、MI250(ROCm 6.0+) Intel:配备 GPU 的 Xeon(即将推出) Apple:通过 MPS 支持 M1/M2/M3(实验性)

参考资料

资源

Agent 操作流程

  1. 检查环境。 确认硬件、框架和服务版本、模型格式以及预期负载。
  2. 明确输入。 根据数据或用户确认格式、标识符和参数。任何会改变结果的值都应询问,不要猜测。
  3. 先运行小规模版本。 在扩展规模前,先服务或记录单个请求,或端到端运行一次。
  4. 使用上述说明和参考资料执行完整任务。
  5. 验证结果。 对照参考值测量延迟、吞吐量和输出正确性;检查资源使用情况和成本。
  6. 报告。 说明运行了什么(版本、命令、参数)、检查了什么,以及还有哪些不确定之处。
如果发生这种情况请这样做
服务无法启动或发生 OOM检查模型大小与内存是否匹配,并检查量化和并行设置。
这些说明中的函数、标志或端点在已安装版本中不存在查阅已安装版本自己的文档(help()、--help、官方文档),进行调整并告知用户。切勿虚构 API。
必需的输入、标识符或参数含糊不清询问用户,或在运行前明确说明假设。

诚信原则

  • 切勿捏造结果、参数、标识符、引用或统计数据。如果无法运行或验证某项内容,请明确说明。
  • 不要公开暴露服务或凭证;配置前确认云服务成本。
  • 请将此处与版本相关的详情视为可能已过时:根据已安装版本的官方文档进行确认。
  • 对于会产生费用、占用共享 GPU 或云配额、涉及个人或患者数据,或无法撤销的操作,请先征求同意。

相关技能

  • tensorrt-llm:使用 NVIDIA TensorRT 优化 LLM 推理,以实现最高吞吐量和最低延迟。
  • outlines:使用 Outlines(dottxt.ai)生成保证有效的结构化输出,通过有限状态机约束 token 采样,……
  • llama-cpp:无需 NVIDIA 硬件,即可在 CPU、Apple Silicon 和消费级 GPU 上运行 LLM 推理。

评论

支持 Markdown