sglang
它能做什么
这项技能介绍 SGLang,这是一个语言模型服务框架,擅长结构化输出和重复提示词。适合构建需要可靠 JSON 回答的智能体或应用的开发者。
适用场景
- ✓当你需要模型始终返回有效的 JSON,或遵循某个正则表达式格式时。
- ✓当你的智能体每次调用都重复相同的系统提示词和工具列表时。
- ✓当你运行的多轮对话大部分上下文都相同时。
技能链接
https://github.com/Orchestra-Research/AI-Research-SKILLs/blob/main/12-inference-serving/sglang/SKILL.md复制后粘贴给你的 AI(Claude、ChatGPT 或 Cursor),让它按照说明操作。
使用方法
最简单的方法:复制下面的消息,粘贴给你的 AI。它会读取这个技能并按说明操作。
可直接粘贴的消息
适用于 Claude Code、Codex 或 Cursor:在项目文件夹中运行,即可安装该技能。
下载 SKILL.md,放进智能体的技能文件夹。
可以这样问 AI
“请帮我部署一个始终返回有效 JSON 的模型给我的智能体,并让重复请求更快。”
每周 5 个新技能,1 分钟读完。
工作原理
你用模型路径和端口启动 SGLang 服务器。它用 RadixAttention 缓存共享的提示词前缀,还可以约束输出,使其符合 JSON 或正则表达式格式。
技术内容(原始 SKILL.md)
作者在 GitHub 上的英文原文。
SGLang
High-performance serving framework for LLMs and VLMs with RadixAttention for automatic prefix caching.
When to use SGLang
Use SGLang when:
- Need structured outputs (JSON, regex, grammar)
- Building agents with repeated prefixes (system prompts, tools)
- Agentic workflows with function calling
- Multi-turn conversations with shared context
- Need faster JSON decoding (3× vs standard)
Use vLLM instead when:
- Simple text generation without structure
- Don't need prefix caching
- Want mature, widely-tested production system
Use TensorRT-LLM instead when:
- Maximum single-request latency (no batching needed)
- NVIDIA-only deployment
- Need FP8/INT4 quantization on H100
Quick start
Installation
# 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]"
Launch server
# 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
Basic inference
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."
Structured JSON output
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 (Key Innovation)
What it does: Automatically caches and reuses common prefixes across requests.
Performance:
- 5× faster for agentic workloads with shared system prompts
- 10× faster for few-shot prompting with repeated examples
- Zero configuration - works automatically
How it works:
- Builds radix tree of all processed tokens
- Automatically detects shared prefixes
- Reuses KV cache for matching prefixes
- Only computes new tokens
Example (Agent with system prompt):
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!
Structured generation patterns
JSON with schema
@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
Regex-constrained generation
@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 john.doe@example.com for details")
print(state["email"])
# Output: "john.doe@exa
常见问题
什么是 RadixAttention?
技能将它描述为自动前缀缓存,即复用共享开头文本已完成的计算。
JSON 解码能快多少?
技能说它可以比标准解码快约 3 倍。
什么时候 vLLM 是更好的选择?
技能建议在只做简单文本生成、不需要结构化输出或前缀缓存时使用 vLLM。
详情
作者的原始描述
Fast structured generation and serving for LLMs with RadixAttention prefix caching. Use for JSON/regex outputs, constrained decoding, agentic workflows with tool calls, or when you need 5× faster inference than vLLM with prefix sharing. Powers 300,000+ GPUs at xAI, AMD, NVIDIA, and LinkedIn.
热度
- GitHub 星标
- 14k
- 排名
- #11215
- 许可证
- MIT
- 更新时间
- 2026/10/10
评论
- …
同一仓库的更多技能
autoresearch
14k引导你的智能体完成一个完整的 AI 研究项目,从文献综述到实验和写作,并通过反复的测试与审查循环推进。
prompt-guard
14k让你的智能体在文本进入你的 AI 应用之前,使用 Meta 的小型分类器检查其中是否含有提示注入和越狱尝试。
pytorch-fsdp2
14k向你的智能体展示如何在训练脚本中加入 PyTorch FSDP2,使大型模型能被拆分到多张 GPU 上并正确保存。
ml-training-recipes
14k为你的智能体提供经过验证的神经网络训练方案,涵盖模型选择、优化器、学习率以及处理损失骤升的方法。