{"id":"sglang","name":"sglang","summary":"RadixAttentionプレフィックスキャッシュを備えたLLM向けの高速構造化生成とサービス。JSON/正規表現の出力、制約付きデコード、ツールコールによるエージェント型ワークフロー、またはプレフィックス共有でvLLMより5×速い推論が必要な場合などに使います。","body":"# SGLang\n\nHigh-performance serving framework for LLMs and VLMs with RadixAttention for automatic prefix caching.\n\n## When to use SGLang\n\n**Use SGLang when:**\n- Need structured outputs (JSON, regex, grammar)\n- Building agents with repeated prefixes (system prompts, tools)\n- Agentic workflows with function calling\n- Multi-turn conversations with shared context\n- Need faster JSON decoding (3× vs standard)\n\n**Use vLLM instead when:**\n- Simple text generation without structure\n- Don't need prefix caching\n- Want mature, widely-tested production system\n\n**Use TensorRT-LLM instead when:**\n- Maximum single-request latency (no batching needed)\n- NVIDIA-only deployment\n- Need FP8/INT4 quantization on H100\n\n## Quick start\n\n### Installation\n\n```bash\n# pip install (recommended)\npip install \"sglang[all]\"\n\n# With FlashInfer (faster, CUDA 11.8/12.1)\npip install sglang[all] flashinfer -i https://flashinfer.ai/whl/cu121/torch2.4/\n\n# From source\ngit clone https://github.com/sgl-project/sglang.git\ncd sglang\npip install -e \"python[all]\"\n```\n\n### Launch server\n\n```bash\n# Basic server (Llama 3-8B)\npython -m sglang.launch_server \\\n    --model-path meta-llama/Meta-Llama-3-8B-Instruct \\\n    --port 30000\n\n# With RadixAttention (automatic prefix caching)\npython -m sglang.launch_server \\\n    --model-path meta-llama/Meta-Llama-3-8B-Instruct \\\n    --port 30000 \\\n    --enable-radix-cache  # Default: enabled\n\n# Multi-GPU (tensor parallelism)\npython -m sglang.launch_server \\\n    --model-path meta-llama/Meta-Llama-3-70B-Instruct \\\n    --tp 4 \\\n    --port 30000\n```\n\n### Basic inference\n\n```python\nimport sglang as sgl\n\n# Set backend\nsgl.set_default_backend(sgl.OpenAI(\"http://localhost:30000/v1\"))\n\n# Simple generation\n@sgl.function\ndef simple_gen(s, question):\n    s += \"Q: \" + question + \"\\n\"\n    s += \"A:\" + sgl.gen(\"answer\", max_tokens=100)\n\n# Run\nstate = simple_gen.run(question=\"What is the capital of France?\")\nprint(state[\"answer\"])\n# Output: \"The capital of France is Paris.\"\n```\n\n### Structured JSON output\n\n```python\nimport sglang as sgl\n\n@sgl.function\ndef extract_person(s, text):\n    s += f\"Extract person information from: {text}\\n\"\n    s += \"Output JSON:\\n\"\n\n    # Constrained JSON generation\n    s += sgl.gen(\n        \"json_output\",\n        max_tokens=200,\n        regex=r'\\{\"name\": \"[^\"]+\", \"age\": \\d+, \"occupation\": \"[^\"]+\"\\}'\n    )\n\n# Run\nstate = extract_person.run(\n    text=\"John Smith is a 35-year-old software engineer.\"\n)\nprint(state[\"json_output\"])\n# Output: {\"name\": \"John Smith\", \"age\": 35, \"occupation\": \"software engineer\"}\n```\n\n## RadixAttention (Key Innovation)\n\n**What it does**: Automatically caches and reuses common prefixes across requests.\n\n**Performance**:\n- **5× faster** for agentic workloads with shared system prompts\n- **10× faster** for few-shot prompting with repeated examples\n- **Zero configuration** - works automatically\n\n**How it works**:\n1. Builds radix tree of all processed tokens\n2. Automatically detects shared prefixes\n3. Reuses KV cache for matching prefixes\n4. Only computes new tokens\n\n**Example** (Agent with system prompt):\n\n```\nRequest 1: [SYSTEM_PROMPT] + \"What's the weather?\"\n→ Computes full prompt (1000 tokens)\n\nRequest 2: [SAME_SYSTEM_PROMPT] + \"Book a flight\"\n→ Reuses system prompt KV cache (998 tokens)\n→ Only computes 2 new tokens\n→ 5× faster!\n```\n\n## Structured generation patterns\n\n### JSON with schema\n\n```python\n@sgl.function\ndef structured_extraction(s, article):\n    s += f\"Article: {article}\\n\\n\"\n    s += \"Extract key information as JSON:\\n\"\n\n    # JSON schema constraint\n    schema = {\n        \"type\": \"object\",\n        \"properties\": {\n            \"title\": {\"type\": \"string\"},\n            \"author\": {\"type\": \"string\"},\n            \"summary\": {\"type\": \"string\"},\n            \"sentiment\": {\"type\": \"string\", \"enum\": [\"positive\", \"negative\", \"neutral\"]}\n        },\n        \"required\": [\"title\", \"author\", \"summary\", \"sentiment\"]\n    }\n\n    s += sgl.gen(\"info\", max_tokens=300, json_schema=schema)\n\nstate = structured_extraction.run(article=\"...\")\nprint(state[\"info\"])\n# Output: Valid JSON matching schema\n```\n\n### Regex-constrained generation\n\n```python\n@sgl.function\ndef extract_email(s, text):\n    s += f\"Extract email from: {text}\\n\"\n    s += \"Email: \"\n\n    # Email regex pattern\n    s += sgl.gen(\n        \"email\",\n        max_tokens=50,\n        regex=r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}'\n    )\n\nstate = extract_email.run(text=\"Contact john.doe@example.com for details\")\nprint(state[\"email\"])\n# Output: \"john.doe@example.com\"\n```\n\n### Grammar-based generation\n\n```python\n@sgl.function\ndef generate_code(s, description):\n    s += f\"Generate Python code for: {description}\\n\"\n    s += \"```python\\n\"\n\n    # EBNF grammar for Python\n    python_grammar = \"\"\"\n    ?start: function_def\n    function_def: \"def\" NAME \"(\" [parameters] \"):\" suite\n    parameters: parameter (\",\" parameter)*\n    parameter: NAME\n    suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT\n    \"\"\"\n\n    s += sgl.gen(\"code\", max_tokens=200, grammar=python_grammar)\n    s += \"\\n```\"\n```\n\n## Agent workflows with function calling\n\n```python\nimport sglang as sgl\n\n# Define tools\ntools = [\n    {\n        \"name\": \"get_weather\",\n        \"description\": \"Get weather for a location\",\n        \"parameters\": {\n            \"type\": \"object\",\n            \"properties\": {\n                \"location\": {\"type\": \"string\"}\n            }\n        }\n    },\n    {\n        \"name\": \"book_flight\",\n        \"description\": \"Book a flight\",\n        \"parameters\": {\n            \"type\": \"object\",\n            \"properties\": {\n                \"from\": {\"type\": \"string\"},\n                \"to\": {\"type\": \"string\"},\n                \"date\": {\"type\": \"string\"}\n            }\n        }\n    }\n]\n\n@sgl.function\ndef agent_workflow(s, user_query, tools):\n    # System prompt (cached with RadixAttention)\n    s += \"You are a helpful assistant with access to tools.\\n\"\n    s += f\"Available tools: {tools}\\n\\n\"\n\n    # User query\n    s += f\"User: {user_query}\\n\"\n    s += \"Assistant: \"\n\n    # Generate with function calling\n    s += sgl.gen(\n        \"response\",\n        max_tokens=200,\n        tools=tools,  # SGLang handles tool call format\n        stop=[\"User:\", \"\\n\\n\"]\n    )\n\n# Multiple queries reuse system prompt\nstate1 = agent_workflow.run(\n    user_query=\"What's the weather in NYC?\",\n    tools=tools\n)\n# First call: Computes full system prompt\n\nstate2 = agent_workflow.run(\n    user_query=\"Book a flight to LA\",\n    tools=tools\n)\n# Second call: Reuses system prompt (5× faster)\n```\n\n## Performance benchmarks\n\n### RadixAttention speedup\n\n**Few-shot prompting** (10 examples in prompt):\n- vLLM: 2.5 sec/request\n- SGLang: **0.25 sec/request** (10× faster)\n- Throughput: 4× higher\n\n**Agent workflows** (1000-token system prompt):\n- vLLM: 1.8 sec/request\n- SGLang: **0.35 sec/request** (5× faster)\n\n**JSON decoding**:\n- Standard: 45 tok/s\n- SGLang: **135 tok/s** (3× faster)\n\n### Throughput (Llama 3-8B, A100)\n\n| Workload | vLLM | SGLang | Speedup |\n|----------|------|--------|---------|\n| Simple generation | 2500 tok/s | 2800 tok/s | 1.12× |\n| Few-shot (10 examples) | 500 tok/s | 5000 tok/s | 10× |\n| Agent (tool calls) | 800 tok/s | 4000 tok/s | 5× |\n| JSON output | 600 tok/s | 2400 tok/s | 4× |\n\n## Multi-turn conversations\n\n```python\n@sgl.function\ndef multi_turn_chat(s, history, new_message):\n    # System prompt (always cached)\n    s += \"You are a helpful AI assistant.\\n\\n\"\n\n    # Conversation history (cached as it grows)\n    for msg in history:\n        s += f\"{msg['role']}: {msg['content']}\\n\"\n\n    # New user message (only new part)\n    s += f\"User: {new_message}\\n\"\n    s += \"Assistant: \"\n    s += sgl.gen(\"response\", max_tokens=200)\n\n# Turn 1\nhistory = []\nstate = multi_turn_chat.run(history=history, new_message=\"Hi there!\")\nhistory.append({\"role\": \"User\", \"content\": \"Hi there!\"})\nhistory.append({\"role\": \"Assistant\", \"content\": state[\"response\"]})\n\n# Turn 2 (reuses Turn 1 KV cache)\nstate = multi_turn_chat.run(history=history, new_message=\"What's 2+2?\")\n# Only computes new message (much faster!)\n\n# Turn 3 (reuses Turn 1 + Turn 2 KV cache)\nstate = multi_turn_chat.run(history=history, new_message=\"Tell me a joke\")\n# Progressively faster as history grows\n```\n\n## Advanced features\n\n### Speculative decoding\n\n```bash\n# Launch with draft model (2-3× faster)\npython -m sglang.launch_server \\\n    --model-path meta-llama/Meta-Llama-3-70B-Instruct \\\n    --speculative-model meta-llama/Meta-Llama-3-8B-Instruct \\\n    --speculative-num-steps 5\n```\n\n### Multi-modal (vision models)\n\n```python\n@sgl.function\ndef describe_image(s, image_path):\n    s += sgl.image(image_path)\n    s += \"Describe this image in detail: \"\n    s += sgl.gen(\"description\", max_tokens=200)\n\nstate = describe_image.run(image_path=\"photo.jpg\")\nprint(state[\"description\"])\n```\n\n### Batching and parallel requests\n\n```python\n# Automatic batching (continuous batching)\nstates = sgl.run_batch(\n    [\n        simple_gen.bind(question=\"What is AI?\"),\n        simple_gen.bind(question=\"What is ML?\"),\n        simple_gen.bind(question=\"What is DL?\"),\n    ]\n)\n\n# All 3 processed in single batch (efficient)\n```\n\n## OpenAI-compatible API\n\n```bash\n# Start server with OpenAI API\npython -m sglang.launch_server \\\n    --model-path meta-llama/Meta-Llama-3-8B-Instruct \\\n    --port 30000\n\n# Use with OpenAI client\ncurl http://localhost:30000/v1/chat/completions \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"model\": \"default\",\n    \"messages\": [\n      {\"role\": \"system\", \"content\": \"You are helpful\"},\n      {\"role\": \"user\", \"content\": \"Hello\"}\n    ],\n    \"temperature\": 0.7,\n    \"max_tokens\": 100\n  }'\n\n# Works with OpenAI Python SDK\nfrom openai import OpenAI\nclient = OpenAI(base_url=\"http://localhost:30000/v1\", api_key=\"EMPTY\")\n\nresponse = client.chat.completions.create(\n    model=\"default\",\n    messages=[{\"role\": \"user\", \"content\": \"Hello\"}]\n)\n```\n\n## Supported models\n\n**Text models**:\n- Llama 2, Llama 3, Llama 3.1, Llama 3.2\n- Mistral, Mixtral\n- Qwen, Qwen2, QwQ\n- DeepSeek-V2, DeepSeek-V3\n- Gemma, Phi-3\n\n**Vision models**:\n- LLaVA, LLaVA-OneVision\n- Phi-3-Vision\n- Qwen2-VL\n\n**100+ models** from HuggingFace\n\n## Hardware support\n\n**NVIDIA**: A100, H100, L4, T4 (CUDA 11.8+)\n**AMD**: MI300, MI250 (ROCm 6.0+)\n**Intel**: Xeon with GPU (coming soon)\n**Apple**: M1/M2/M3 via MPS (experimental)\n\n## References\n\n- **[Structured Generation Guide](references/structured-generation.md)** - JSON schemas, regex, grammars, validation\n- **[RadixAttention Deep Dive](references/radix-attention.md)** - How it works, optimization, benchmarks\n- **[Production Deployment](references/deployment.md)** - Multi-GPU, monitoring, autoscaling\n\n## Resources\n\n- **GitHub**: https://github.com/sgl-project/sglang\n- **Docs**: https://sgl-project.github.io/\n- **Paper**: RadixAttention (arXiv:2312.07104)\n- **Discord**: https://discord.gg/sglang","author":"@Orchestra-Research","ownerProfile":null,"authorContacts":null,"sourceUrl":"https://github.com/Orchestra-Research/AI-Research-SKILLs/tree/main/12-inference-serving/sglang","license":"MIT","category":"coding","lang":"en","tokens":3036,"stars":0,"calls30d":2,"claimed":false,"visibility":"public","origin":"crawler","version":"0.1.0","createdAt":"2026-08-22","updatedAt":"2026-08-22","files":[{"path":"references/deployment.md","size":10020,"sha256":"e5400d1e6c79d3e95eed16f9d44c7d87595350a9f56a65869c64eec287ebd46e"},{"path":"references/radix-attention.md","size":11005,"sha256":"c47e5a9adfa0b7904373e15e9af5c26dbfc9d4967d0ea1d73d644b4b27e770ba"},{"path":"references/structured-generation.md","size":13468,"sha256":"e5bade39d37dccc2cdd85da8c16bf46e924ba168292271c4b2007c8b472696f1"}],"requires":{"mcp":[],"tools":[]},"safety":{"flags":[],"scannedAt":"2026-08-22","hasScripts":false,"networkEndpoints":["discord.gg","flashinfer.ai","sgl-project.github.io"]}}