sglang
O que ela faz
Esta skill explica o SGLang, um framework de servir modelos de linguagem que se destaca em saída estruturada e prompts repetidos. É para desenvolvedores que criam agentes ou apps que precisam de respostas JSON confiáveis.
Quando usar
- ✓Quando você precisa que o modelo sempre devolva JSON válido ou siga um padrão regex.
- ✓Quando seu agente repete o mesmo prompt de sistema e a mesma lista de ferramentas em cada chamada.
- ✓Quando você roda conversas com várias trocas que compartilham a maior parte do contexto.
Link da skill
https://github.com/Orchestra-Research/AI-Research-SKILLs/blob/main/12-inference-serving/sglang/SKILL.mdCopie e cole na sua IA (Claude, ChatGPT ou Cursor) pedindo para seguir as instruções.
Como usar
O jeito mais fácil: copie a mensagem e cole na sua IA. Ela lê a skill e segue as instruções.
Mensagem pronta para colar
Para Claude Code, Codex ou Cursor: rode na pasta do projeto e a skill fica instalada.
Baixe o SKILL.md e coloque na pasta de skills do seu agente.
Exemplo do que pedir para a IA
“Sirva um modelo que sempre devolva JSON válido para o meu agente, e deixe as requisições repetidas mais rápidas.”
5 skills novas por semana. 1 minuto de leitura.
Como funciona
Você inicia um servidor SGLang com o caminho do modelo e uma porta. Ele guarda em cache os prefixos de prompt compartilhados com o RadixAttention e pode limitar a saída para que siga um formato JSON ou regex.
Conteúdo técnico (SKILL.md original)
Texto original do autor, em inglês, direto do 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
Perguntas frequentes
O que é o RadixAttention?
A skill descreve como um cache automático de prefixos, que reaproveita o trabalho feito sobre um texto inicial compartilhado.
Quão mais rápida é a decodificação de JSON?
A skill diz que pode ser cerca de 3 vezes mais rápida que a decodificação padrão.
Quando o vLLM é a melhor escolha?
A skill sugere o vLLM para geração de texto simples, sem estrutura nem cache de prefixo.
Detalhes
Descrição original do autor
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.
Popularidade
- Estrelas no GitHub
- 14 mil
- Posição no ranking
- #11215
- Licença
- MIT
- Atualizada em
- 10/10/2026
Comentários
- …
Mais skills deste repositório
autoresearch
14 milOrienta seu agente em um projeto completo de pesquisa em IA, da revisão da literatura aos experimentos e à escrita, com um ciclo repetido de testes e revisão.
prompt-guard
14 milPermite que seu agente verifique textos em busca de injeção de prompt e tentativas de jailbreak antes de chegarem ao seu app de IA, usando o classificador pequeno da Meta.
pytorch-fsdp2
14 milMostra ao seu agente como adicionar o FSDP2 do PyTorch a um script de treino, para que modelos grandes sejam divididos entre GPUs e salvos corretamente.
ml-training-recipes
14 milDá ao seu agente receitas de treino testadas para redes neurais, cobrindo a escolha do modelo, otimizadores, taxas de aprendizado e a correção de picos de perda.
Skills parecidas
pytorch-patterns
280 milAjuda seu agente a usar PyTorch para criar modelos de aprendizado de máquina. Aplica boas práticas para treinar de forma eficiente e consistente.
evm-token-decimals
280 milAjuda seu agente a evitar erros com números decimais em diferentes redes blockchain. Garante que os valores de tokens sejam precisos em transações e cálculos.
ito-inference
280 milFaz seu agente verificar a disponibilidade de modelos de IA para uso. Ele conecta o pedido de computação com o serviço de modelo pronto.