<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"><channel><title>RadixAttention | 林子杨的个人网站</title><link>https://ziyanglin.netlify.app/zh/tags/radixattention/</link><atom:link href="https://ziyanglin.netlify.app/zh/tags/radixattention/index.xml" rel="self" type="application/rss+xml"/><description>RadixAttention</description><generator>Source Themes Academic (https://sourcethemes.com/academic/)</generator><language>zh-Hans</language><lastBuildDate>Thu, 26 Jun 2025 01:07:00 +0000</lastBuildDate><image><url>https://ziyanglin.netlify.app/img/icon-192.png</url><title>RadixAttention</title><link>https://ziyanglin.netlify.app/zh/tags/radixattention/</link></image><item><title>SGLang 技术指南：高性能结构化生成语言框架</title><link>https://ziyanglin.netlify.app/zh/post/sglang-documentation/</link><pubDate>Thu, 26 Jun 2025 01:07:00 +0000</pubDate><guid>https://ziyanglin.netlify.app/zh/post/sglang-documentation/</guid><description>&lt;h2 id="1-sglang-">1. SGLang 简介&lt;/h2>
&lt;p>SGLang (Structured Generation Language) 是一个为大型语言模型（LLM）和视觉语言模型（VLM）设计的高性能服务框架。它的核心目标是解决在实际应用中常见的复杂 LLM 程序所面临的挑战，即在保持灵活性的同时，最大化推理过程的性能。&lt;/p>
&lt;p>传统的 LLM 服务框架（如 vLLM）在处理简单的、一次性的提示（one-shot prompting）时表现出色，但在需要多轮交互、结构化输出、函数调用或控制流的复杂场景下，其性能和易用性会受到限制。SGLang 通过引入一种新颖的前端语言和高效的后端运行时，有效地弥补了这一差距。&lt;/p>
&lt;p>&lt;strong>SGLang 的核心优势包括：&lt;/strong>&lt;/p>
&lt;ul>
&lt;li>&lt;strong>卓越的性能：&lt;/strong> SGLang 引入了 &lt;strong>RadixAttention&lt;/strong>，这是一种创新的注意力机制，可以自动、无损地复用键值缓存（KV Cache），从而显著提升了具有复杂提示（如 CoT、ReAct）或多轮对话场景下的推理速度。与 vLLM 等领先框架相比，SGLang 在这些场景下可以实现数倍的吞吐量提升。&lt;/li>
&lt;li>&lt;strong>强大的编程能力：&lt;/strong> SGLang 提供了一种直观的前端语言（DSL），允许开发者使用 Pythonic 的方式来编排复杂的生成任务。你可以轻松地定义变量、使用循环和条件判断、调用外部工具，并将这些逻辑与 LLM 的生成过程无缝集成。这使得构建复杂的 AI Agent、多轮对话系统和结构化数据提取任务变得前所未有的简单。&lt;/li>
&lt;li>&lt;strong>统一的前后端接口：&lt;/strong> SGLang 将前端的编程逻辑与后端的推理服务解耦。前端负责定义&amp;quot;生成什么&amp;rdquo;，后端负责&amp;quot;如何高效生成&amp;rdquo;。这种设计不仅简化了开发流程，还使得 SGLang 能够兼容 OpenAI 的 API 标准，让用户可以轻松地将现有应用迁移到 SGLang 上，立即享受性能红利。&lt;/li>
&lt;li>&lt;strong>灵活的结构化输出：&lt;/strong> SGLang 提供了强大的结构化输出约束功能。无论是通过正则表达式、EBNF 文法还是 JSON Schema，你都可以精确地控制 LLM 的输出格式，确保生成的内容符合预期的结构，这对于需要可靠数据格式的应用至关重要。&lt;/li>
&lt;/ul>
&lt;p>总而言之，SGLang 不仅仅是一个 LLM 推理加速引擎，更是一个完整的、面向复杂生成任务的编程和执行框架。它旨在让开发者能够以一种既高效又直观的方式，充分释放大型语言模型的潜力。&lt;/p>
&lt;h2 id="2-">2. 核心特性&lt;/h2>
&lt;p>SGLang 的强大之处在于其独特的设计，它将直观的前端编程模型与高效的后端执行引擎相结合。以下是其几个核心特性的详细介绍。&lt;/p>
&lt;h3 id="21-radixattention-kv-">2.1 RadixAttention：为复杂提示而生的 KV 缓存优化&lt;/h3>
&lt;p>在处理复杂的 LLM 程序时，例如思维链（Chain-of-Thought）、多轮对话或需要调用工具的 Agent，提示（Prompt）中往往包含大量共享的前缀。传统的注意力机制在处理这些共享前缀时会产生冗余的计算和存储。&lt;/p>
&lt;p>SGLang 引入了 &lt;strong>RadixAttention&lt;/strong>，这是一种新颖的 KV 缓存优化技术。其核心思想是将提示组织成一棵基数树（Radix Tree），并在这个树上执行注意力计算。&lt;/p>
&lt;ul>
&lt;li>&lt;strong>自动共享与复用&lt;/strong>：RadixAttention 能够自动识别并共享不同请求之间的公共前缀，从而避免了重复计算和存储。例如，在多轮对话中，每一轮的对话历史都可以被后续轮次无损地复用。&lt;/li>
&lt;li>&lt;strong>性能提升&lt;/strong>：通过最大化 KV 缓存的复用，RadixAttention 显著减少了内存占用和计算量，从而将吞吐量提升了2到5倍，尤其是在处理长提示或高并发请求时效果更为明显。&lt;/li>
&lt;/ul>
&lt;p>下面是一个 Mermaid 图，用于直观地展示 RadixAttention 如何处理共享前缀的请求：&lt;/p>
&lt;pre>&lt;code class="language-mermaid">graph TD
subgraph &amp;quot;传统方法 (无共享)&amp;quot;
req1[&amp;quot;请求1: 'A B C D'&amp;quot;]
req2[&amp;quot;请求2: 'A B E F'&amp;quot;]
kv1[&amp;quot;KV 缓存: [A, B, C, D]&amp;quot;]
kv2[&amp;quot;KV 缓存: [A, B, E, F]&amp;quot;]
req1 --&amp;gt; kv1
req2 --&amp;gt; kv2
end
subgraph &amp;quot;SGLang RadixAttention&amp;quot;
Root(&amp;quot;Root&amp;quot;) --&amp;gt; A(&amp;quot;Token 'A'&amp;quot;);
A --&amp;gt; B(&amp;quot;Token 'B'&amp;quot;);
B --&amp;gt; C(&amp;quot;Token 'C'&amp;quot;);
B --&amp;gt; E(&amp;quot;Token 'E'&amp;quot;);
C --&amp;gt; D(&amp;quot;Token 'D'&amp;quot;);
E --&amp;gt; F(&amp;quot;Token 'F'&amp;quot;);
style A fill:#9f9
style B fill:#9f9
end
&lt;/code>&lt;/pre>
&lt;p>在上图中，对于两个请求 &lt;code>'A B C D'&lt;/code> 和 &lt;code>'A B E F'&lt;/code>，传统方法会创建两个独立的 KV 缓存。而 RadixAttention 将它们组织成一棵树，共享了公共前缀 &lt;code>'A B'&lt;/code>（绿色节点）的计算和存储，只为不同的部分（C, D, E, F）创建新的分支。这极大地提高了内存和计算效率。&lt;/p>
&lt;h3 id="22-dsl">2.2 统一的前端编程语言（DSL）&lt;/h3>
&lt;p>SGLang 提供了一种富有表现力的领域特定语言（DSL），它深度集成在 Python 中，使得开发者可以用非常自然和直观的方式来构建复杂的生成逻辑。&lt;/p>
&lt;h3 id="sglang-">SGLang 架构概览&lt;/h3>
&lt;p>为了更好地理解 SGLang 的工作方式，我们可以通过下面的流程图来观察其核心架构：&lt;/p>
&lt;pre>&lt;code class="language-mermaid">graph TD
subgraph 用户侧
A[开发者定义 SGLang 程序&amp;lt;br&amp;gt;使用 function 装饰器] --&amp;gt; B{调用 run 方法};
end
subgraph SGLang 前端
B --&amp;gt; C[1. 解析 Python AST&amp;lt;br&amp;gt;分离确定性逻辑和生成指令];
C --&amp;gt; D[2. 构建可移植的&amp;lt;br&amp;gt;SGLang IR 中间表示];
end
subgraph 网络通信
D -- HTTP Request --&amp;gt; E[SGLang 后端服务 SRT];
end
subgraph SGLang 后端 SRT
E --&amp;gt; F[3. 接收 IR 并调度];
F --&amp;gt; G{RadixAttention 引擎};
G --&amp;gt; H[4. 高效执行&amp;lt;br&amp;gt;KV 缓存复用];
H --&amp;gt; I[LLM/VLM 模型];
I --&amp;gt; J[5. 生成结果];
end
subgraph 返回路径
J -- HTTP Response --&amp;gt; K[返回结果给前端];
K --&amp;gt; L[6. 填充状态对象 `s`];
L --&amp;gt; M[用户获得最终结果];
end
style B fill:#f9f,stroke:#333,stroke-width:2px
style E fill:#ccf,stroke:#333,stroke-width:2px
style G fill:#9cf,stroke:#333,stroke-width:2px
&lt;/code>&lt;/pre>
&lt;p>这个图表清晰地展示了 SGLang 如何将前端的编程便利性与后端的高性能执行引擎解耦并结合起来。&lt;/p>
&lt;ul>
&lt;li>&lt;strong>Pythonic 控制流&lt;/strong>：你可以在 SGLang 函数中直接使用 &lt;code>if/else&lt;/code>、&lt;code>for&lt;/code> 循环等标准的 Python 控制流语句，来动态地构建提示。&lt;/li>
&lt;li>&lt;strong>生成与逻辑的结合&lt;/strong>：通过 &lt;code>@function&lt;/code> 装饰器和 &lt;code>gen()&lt;/code> 指令，SGLang 将 LLM 的生成过程（&amp;ldquo;不确定性&amp;quot;部分）与程序的确定性逻辑无缝地结合在一起。&lt;/li>
&lt;/ul>
&lt;p>&lt;strong>示例：根据条件生成不同的内容&lt;/strong>&lt;/p>
&lt;pre>&lt;code class="language-python">from sglang import function, system, user, assistant, gen
@function
def tool_use(s, question):
s += system(&amp;quot;You are a helpful assistant.&amp;quot;)
s += user(question)
s += assistant(
&amp;quot;To answer this question, I need to use a &amp;quot;
+ gen(&amp;quot;tool&amp;quot;, choices=[&amp;quot;calculator&amp;quot;, &amp;quot;search engine&amp;quot;])
+ &amp;quot;. &amp;quot;
)
if s[&amp;quot;tool&amp;quot;] == &amp;quot;calculator&amp;quot;:
s += assistant(&amp;quot;The math expression is: &amp;quot; + gen(&amp;quot;expression&amp;quot;))
elif s[&amp;quot;tool&amp;quot;] == &amp;quot;search engine&amp;quot;:
s += assistant(&amp;quot;The key word to search is: &amp;quot; + gen(&amp;quot;word&amp;quot;))
state = tool_use.run(&amp;quot;What is the population of London?&amp;quot;)
print(state[&amp;quot;tool&amp;quot;])
# Output: search engine
print(state[&amp;quot;word&amp;quot;])
# Output: population of London
&lt;/code>&lt;/pre>
&lt;p>在这个例子中，程序首先让 LLM 在 &amp;ldquo;calculator&amp;rdquo; 和 &amp;ldquo;search engine&amp;rdquo; 中选择一个工具，然后根据 LLM 的选择，执行不同的逻辑分支，引导 LLM 生成下一步的内容。&lt;/p>
&lt;h3 id="23-">2.3 强大的结构化输出&lt;/h3>
&lt;p>为了确保 LLM 生成的内容能够被下游程序可靠地解析和使用，SGLang 提供了多种强大的结构化输出约束机制。&lt;/p>
&lt;ul>
&lt;li>
&lt;p>&lt;strong>正则表达式（Regex）&lt;/strong>：你可以提供一个正则表达式，强制模型的输出严格匹配该模式。这对于生成特定格式的标识符、数字或简单的文本片段非常有用。&lt;/p>
&lt;pre>&lt;code class="language-python">response = client.chat.completions.create(
model=&amp;quot;deepseek-ai/DeepSeek-R1-Distill-Qwen-7B&amp;quot;,
messages=[{&amp;quot;role&amp;quot;: &amp;quot;assistant&amp;quot;, &amp;quot;content&amp;quot;: &amp;quot;What is the capital of France?&amp;quot;}],
extra_body={&amp;quot;regex&amp;quot;: &amp;quot;(Paris|London)&amp;quot;},
)
# response.choices[0].message.content 将必然是 &amp;quot;Paris&amp;quot; 或 &amp;quot;London&amp;quot;
&lt;/code>&lt;/pre>
&lt;/li>
&lt;li>
&lt;p>&lt;strong>EBNF 文法&lt;/strong>：对于更复杂的语法结构，你可以使用扩展巴科斯范式（EBNF）来定义一个完整的文法。这使得你可以生成严格遵守特定语法的代码、DSL 或其他结构化文本。&lt;/p>
&lt;pre>&lt;code class="language-python">ebnf_grammar = &amp;quot;&amp;quot;&amp;quot;
root ::= city &amp;quot; is the capital of &amp;quot; country
city ::= &amp;quot;London&amp;quot; | &amp;quot;Paris&amp;quot; | &amp;quot;Berlin&amp;quot; | &amp;quot;Rome&amp;quot;
country ::= &amp;quot;England&amp;quot; | &amp;quot;France&amp;quot; | &amp;quot;Germany&amp;quot; | &amp;quot;Italy&amp;quot;
&amp;quot;&amp;quot;&amp;quot;
response = client.chat.completions.create(
model=&amp;quot;meta-llama/Meta-Llama-3.1-8B-Instruct&amp;quot;,
messages=[{&amp;quot;role&amp;quot;: &amp;quot;user&amp;quot;, &amp;quot;content&amp;quot;: &amp;quot;Give me the information of the capital of France.&amp;quot;}],
extra_body={&amp;quot;ebnf&amp;quot;: ebnf_grammar},
)
# response.choices[0].message.content 将会是 &amp;quot;Paris is the capital of France&amp;quot;
&lt;/code>&lt;/pre>
&lt;/li>
&lt;li>
&lt;p>&lt;strong>JSON Schema&lt;/strong>：SGLang 支持使用 JSON Schema 来约束模型生成结构化的 JSON 对象。你可以直接定义 JSON Schema，或者使用 Pydantic 模型来自动生成。这对于需要可靠、可验证的 JSON 输出的 API 和数据处理任务至关重要。&lt;/p>
&lt;pre>&lt;code class="language-python">from pydantic import BaseModel
class CapitalInfo(BaseModel):
name: str
population: int
response = client.chat.completions.create(
model=&amp;quot;deepseek-ai/DeepSeek-R1-Distill-Qwen-7B&amp;quot;,
messages=[{&amp;quot;role&amp;quot;: &amp;quot;assistant&amp;quot;, &amp;quot;content&amp;quot;: &amp;quot;Give me the information and population of the capital of France in the JSON format.&amp;quot;}],
response_format={
&amp;quot;type&amp;quot;: &amp;quot;json_schema&amp;quot;,
&amp;quot;json_schema&amp;quot;: {
&amp;quot;name&amp;quot;: &amp;quot;capital_info&amp;quot;,
&amp;quot;schema&amp;quot;: CapitalInfo.model_json_schema(),
},
},
)
# response.choices[0].message.content 将会是一个符合 CapitalInfo 结构的 JSON 字符串
&lt;/code>&lt;/pre>
&lt;/li>
&lt;/ul>
&lt;h2 id="3-">3. 快速入门&lt;/h2>
&lt;p>本章节将指导你完成 SGLang 的安装、服务启动和基本使用，让你在几分钟内体验到 SGLang 的强大功能。&lt;/p>
&lt;h3 id="31-">3.1 安装&lt;/h3>
&lt;p>SGLang 可以通过 &lt;code>pip&lt;/code> 或更快的 &lt;code>uv&lt;/code> 进行安装。为了获得最佳体验和全部功能，推荐安装 &lt;code>all&lt;/code> 版本。&lt;/p>
&lt;p>&lt;strong>使用 pip:&lt;/strong>&lt;/p>
&lt;pre>&lt;code class="language-bash">pip install --upgrade pip
pip install &amp;quot;sglang[all]&amp;quot;
&lt;/code>&lt;/pre>
&lt;p>&lt;strong>使用 uv (推荐，速度更快):&lt;/strong>&lt;/p>
&lt;pre>&lt;code class="language-bash">pip install uv
uv pip install &amp;quot;sglang[all]&amp;quot;
&lt;/code>&lt;/pre>
&lt;blockquote>
&lt;p>&lt;strong>注意&lt;/strong>: 安装过程可能需要编译 CUDA 内核（如 &lt;code>flashinfer&lt;/code>），请确保你的环境中已正确配置 &lt;code>CUDA_HOME&lt;/code> 环境变量，并且 CUDA 版本与 PyTorch 版本兼容。&lt;/p>
&lt;/blockquote>
&lt;h3 id="32--srt">3.2 启动后端服务 (SRT)&lt;/h3>
&lt;p>安装完成后，下一步是启动 SGLang 的后端服务（SRT, SGLang Runtime）。该服务将加载指定的语言模型，并提供一个与 OpenAI API 兼容的接口。&lt;/p>
&lt;p>在你的终端中运行以下命令：&lt;/p>
&lt;pre>&lt;code class="language-bash">python -m sglang.launch_server --model-path meta-llama/Meta-Llama-3.1-8B-Instruct --host 0.0.0.0 --port 30000
&lt;/code>&lt;/pre>
&lt;p>&lt;strong>参数说明:&lt;/strong>&lt;/p>
&lt;ul>
&lt;li>&lt;code>--model-path&lt;/code>: 指定要加载的模型的路径。可以是 Hugging Face Hub 上的模型名称（如本例所示），也可以是本地的模型路径。&lt;/li>
&lt;li>&lt;code>--host&lt;/code>: 服务监听的主机地址。&lt;code>0.0.0.0&lt;/code> 表示允许从任何网络接口访问。&lt;/li>
&lt;li>&lt;code>--port&lt;/code>: 服务监听的端口号。&lt;/li>
&lt;/ul>
&lt;p>服务成功启动后，你将看到类似以下的输出，表示模型已加载并准备好接收请求。&lt;/p>
&lt;pre>&lt;code>INFO: Uvicorn running on http://0.0.0.0:30000 (Press CTRL+C to quit)
INFO: Started server process [12345]
INFO: Waiting for application startup.
INFO: Application startup complete.
&lt;/code>&lt;/pre>
&lt;h3 id="33-">3.3 发送第一个请求&lt;/h3>
&lt;p>服务正在运行，现在我们可以通过 OpenAI 的 Python 客户端库来与之交互。&lt;/p>
&lt;p>创建一个名为 &lt;code>test_sglang.py&lt;/code> 的 Python 文件，并填入以下内容：&lt;/p>
&lt;pre>&lt;code class="language-python">import openai
# 初始化客户端，指向我们本地启动的 SGLang 服务
client = openai.Client(
base_url=&amp;quot;http://127.0.0.1:30000/v1&amp;quot;,
api_key=&amp;quot;EMPTY&amp;quot; # SGLang 服务不需要 API Key
)
# 创建一个聊天补全请求
response = client.chat.completions.create(
model=&amp;quot;meta-llama/Meta-Llama-3.1-8B-Instruct&amp;quot;, # 必须与服务加载的模型一致
messages=[
{&amp;quot;role&amp;quot;: &amp;quot;system&amp;quot;, &amp;quot;content&amp;quot;: &amp;quot;You are a helpful assistant.&amp;quot;},
{&amp;quot;role&amp;quot;: &amp;quot;user&amp;quot;, &amp;quot;content&amp;quot;: &amp;quot;What is the capital of France and why is it famous?&amp;quot;},
],
temperature=0.7,
max_tokens=150,
)
# 打印模型的回复
print(response.choices[0].message.content)
&lt;/code>&lt;/pre>
&lt;p>运行这个脚本：&lt;/p>
&lt;pre>&lt;code class="language-bash">python test_sglang.py
&lt;/code>&lt;/pre>
&lt;p>你将看到模型生成的关于巴黎的详细回答。至此，你已经成功地使用 SGLang 完成了一次从服务部署到推理请求的全过程！&lt;/p>
&lt;h2 id="4--sglang-dsl">4. 前端语言 (SGLang DSL)&lt;/h2>
&lt;p>SGLang 的前端语言（DSL）是其易用性的核心。它允许你以声明式的方式定义复杂的生成流程，将 Python 的灵活性与 LLM 的生成能力完美结合。&lt;/p>
&lt;h3 id="41-function-">4.1 &lt;code>@function&lt;/code> 装饰器&lt;/h3>
&lt;p>所有 SGLang 程序都始于一个由 &lt;code>@function&lt;/code> 装饰的 Python 函数。这个装饰器会将一个普通的 Python 函数转换成一个可执行的 SGLang 程序模板。&lt;/p>
&lt;ul>
&lt;li>&lt;strong>状态管理&lt;/strong>：函数的第一个参数（通常命名为 &lt;code>s&lt;/code>）代表了当前的生成状态（state）。它是一个类似字典的对象，用于存储和传递生成过程中产生的所有变量。&lt;/li>
&lt;li>&lt;strong>延迟执行&lt;/strong>：被 &lt;code>@function&lt;/code> 装饰的函数在定义时不会立即执行。相反，它会创建一个可重用的模板。只有当调用 &lt;code>.run()&lt;/code> 或 &lt;code>.run_batch()&lt;/code> 方法时，程序才会真正执行。&lt;/li>
&lt;/ul>
&lt;p>&lt;strong>交互流程&lt;/strong>&lt;/p>
&lt;p>整个函数调用的交互流程可以用下面的序列图来表示：&lt;/p>
&lt;pre>&lt;code class="language-mermaid">sequenceDiagram
participant User as 用户
participant App as 应用 (Python)
participant SGLang as SGLang 服务
participant Tool as 外部工具 (e.g., 天气API)
User-&amp;gt;&amp;gt;+App: &amp;quot;波士顿的天气怎么样？&amp;quot;
App-&amp;gt;&amp;gt;+SGLang: 发送包含 messages 和 tools 的请求
SGLang-&amp;gt;&amp;gt;SGLang: 模型决定调用 get_current_weather
SGLang--&amp;gt;&amp;gt;-App: 返回 tool_calls，包含函数名和参数
App-&amp;gt;&amp;gt;App: 解析 tool_calls
App-&amp;gt;&amp;gt;+Tool: 调用 get_current_weather(city=&amp;quot;Boston&amp;quot;, unit=&amp;quot;fahrenheit&amp;quot;)
Tool--&amp;gt;&amp;gt;-App: 返回天气结果: &amp;quot;68°F&amp;quot;
App-&amp;gt;&amp;gt;+SGLang: 发送包含天气结果的新一轮请求
SGLang-&amp;gt;&amp;gt;SGLang: 模型根据天气结果生成最终回复
SGLang--&amp;gt;&amp;gt;-App: 返回最终的自然语言回复
App--&amp;gt;&amp;gt;-User: &amp;quot;波士顿现在是 68°F。&amp;quot;
&lt;/code>&lt;/pre>
&lt;p>这个序列图清晰地展示了从用户提问到模型决策、工具调用、结果整合，再到最终回复的完整闭环。&lt;/p>
&lt;h3 id="42-">4.2 核心指令&lt;/h3>
&lt;p>在 SGLang 函数内部，你使用一系列指令来构建提示和控制生成流程。&lt;/p>
&lt;ul>
&lt;li>&lt;strong>角色指令&lt;/strong>: &lt;code>system()&lt;/code>, &lt;code>user()&lt;/code>, &lt;code>assistant()&lt;/code>
这些指令用于定义对话的不同部分，符合标准的多轮对话格式。你可以将字符串直接传递给它们。&lt;/li>
&lt;li>&lt;strong>生成指令&lt;/strong>: &lt;code>gen()&lt;/code>
这是 SGLang 中最重要的指令。它告诉 LLM 在当前位置生成文本。
&lt;ul>
&lt;li>&lt;code>s += gen(&amp;quot;variable_name&amp;quot;, ...)&lt;/code>: &lt;code>gen()&lt;/code> 的第一个参数是必需的，它指定了生成结果将存储在状态 &lt;code>s&lt;/code> 中的变量名。&lt;/li>
&lt;li>&lt;code>max_tokens&lt;/code>: 限制生成的最大 token 数量。&lt;/li>
&lt;li>&lt;code>stop&lt;/code>: 定义一个或多个停止字符串。当模型生成这些字符串时，生成过程会提前结束。&lt;/li>
&lt;li>&lt;code>choices&lt;/code>: 提供一个字符串列表，强制模型从这些选项中选择一个进行生成。&lt;/li>
&lt;/ul>
&lt;/li>
&lt;/ul>
&lt;p>&lt;strong>示例：一个完整的前端函数&lt;/strong>&lt;/p>
&lt;pre>&lt;code class="language-python">from sglang import function, system, user, assistant, gen, set_default_backend, OpenAI
# 设置后端为 SGLang 提供的 OpenAI 兼容服务
set_default_backend(OpenAI(&amp;quot;meta-llama/Meta-Llama-3.1-8B-Instruct&amp;quot;))
@function
def multi_turn_qa(s, question1, question2):
s += system(&amp;quot;You are a helpful assistant.&amp;quot;)
s += user(question1)
s += assistant(gen(&amp;quot;answer1&amp;quot;, max_tokens=128))
s += user(question2)
s += assistant(gen(&amp;quot;answer2&amp;quot;, max_tokens=128))
# 执行 SGLang 程序
state = multi_turn_qa.run(
question1=&amp;quot;What is the capital of the UK?&amp;quot;,
question2=&amp;quot;What is its population?&amp;quot;,
temperature=0.1
)
print(&amp;quot;Answer 1:&amp;quot;, state[&amp;quot;answer1&amp;quot;])
print(&amp;quot;Answer 2:&amp;quot;, state[&amp;quot;answer2&amp;quot;])
&lt;/code>&lt;/pre>
&lt;h3 id="43-">4.3 流式输出&lt;/h3>
&lt;p>对于需要实时反馈的应用，SGLang 支持流式输出。只需在 &lt;code>.run()&lt;/code> 方法中设置 &lt;code>stream=True&lt;/code>，然后迭代返回的状态对象的 &lt;code>.text_iter()&lt;/code> 方法即可。&lt;/p>
&lt;pre>&lt;code class="language-python">state = multi_turn_qa.run(
question1=&amp;quot;Write a short story about a robot.&amp;quot;,
question2=&amp;quot;Continue the story.&amp;quot;,
stream=True
)
for out in state.text_iter(&amp;quot;answer2&amp;quot;):
print(out, end=&amp;quot;&amp;quot;, flush=True)
&lt;/code>&lt;/pre>
&lt;h2 id="5--srt--api-">5. 后端服务 (SRT) 与 API 参考&lt;/h2>
&lt;p>SGLang 的后端，即 SGLang Runtime (SRT)，是一个用 Python 实现的高性能推理服务器。它负责加载模型、管理 KV 缓存（通过 RadixAttention），并处理来自客户端的请求。SRT 提供了两种主要的 API 端点。&lt;/p>
&lt;h3 id="51--api-generate">5.1 原生 API: &lt;code>/generate&lt;/code>&lt;/h3>
&lt;p>这是一个更底层的 API，提供了对生成过程最精细的控制。&lt;/p>
&lt;ul>
&lt;li>&lt;strong>Endpoint&lt;/strong>: &lt;code>POST /generate&lt;/code>&lt;/li>
&lt;li>&lt;strong>描述&lt;/strong>: 从给定的文本提示开始生成文本。&lt;/li>
&lt;li>&lt;strong>核心参数&lt;/strong>:
&lt;ul>
&lt;li>&lt;code>text&lt;/code> (string, required): 输入的文本提示。&lt;/li>
&lt;li>&lt;code>sampling_params&lt;/code> (object, optional): 一个包含采样参数的 JSON 对象。
&lt;ul>
&lt;li>&lt;code>temperature&lt;/code> (float): 采样温度。&lt;/li>
&lt;li>&lt;code>max_new_tokens&lt;/code> (int): 最大新生成 token 数。&lt;/li>
&lt;li>&lt;code>stop&lt;/code> (string or list[string]): 停止符。&lt;/li>
&lt;li>&lt;code>json_schema&lt;/code> (string): JSON Schema 字符串，用于约束输出。&lt;/li>
&lt;li>&lt;code>regex&lt;/code> (string): 正则表达式，用于约束输出。&lt;/li>
&lt;li>&lt;code>ebnf&lt;/code> (string): EBNF 文法，用于约束输出。&lt;/li>
&lt;/ul>
&lt;/li>
&lt;li>&lt;code>stream&lt;/code> (boolean, optional): 是否使用流式传输。&lt;/li>
&lt;/ul>
&lt;/li>
&lt;/ul>
&lt;p>&lt;strong>示例 (使用 &lt;code>requests&lt;/code>)&lt;/strong>:&lt;/p>
&lt;pre>&lt;code class="language-python">import requests
import json
url = &amp;quot;http://127.0.0.1:30000/generate&amp;quot;
data = {
&amp;quot;text&amp;quot;: &amp;quot;The capital of France is&amp;quot;,
&amp;quot;sampling_params&amp;quot;: {
&amp;quot;temperature&amp;quot;: 0,
&amp;quot;max_new_tokens&amp;quot;: 16,
}
}
response = requests.post(url, json=data)
print(response.json())
# {'text': ' Paris.\n\nThe capital of France is Paris. It is the most populous city in', 'meta': ...}
&lt;/code>&lt;/pre>
&lt;h3 id="52-openai--api-v1chatcompletions">5.2 OpenAI 兼容 API: &lt;code>/v1/chat/completions&lt;/code>&lt;/h3>
&lt;p>为了方便迁移和集成，SGLang 提供了与 OpenAI 完全兼容的聊天补全 API。你可以无缝地使用 OpenAI 的官方客户端库。&lt;/p>
&lt;ul>
&lt;li>&lt;strong>Endpoint&lt;/strong>: &lt;code>POST /v1/chat/completions&lt;/code>&lt;/li>
&lt;li>&lt;strong>描述&lt;/strong>: 执行聊天式文本生成。&lt;/li>
&lt;li>&lt;strong>核心参数&lt;/strong>:
&lt;ul>
&lt;li>&lt;code>model&lt;/code> (string, required): 模型的名称。&lt;/li>
&lt;li>&lt;code>messages&lt;/code> (list[object], required): 对话消息列表。&lt;/li>
&lt;li>&lt;code>temperature&lt;/code>, &lt;code>max_tokens&lt;/code>, &lt;code>stream&lt;/code>, etc.&lt;/li>
&lt;li>&lt;code>response_format&lt;/code> (object, optional): 用于指定结构化输出，如 &lt;code>{&amp;quot;type&amp;quot;: &amp;quot;json_schema&amp;quot;, &amp;quot;json_schema&amp;quot;: ...}&lt;/code>。&lt;/li>
&lt;li>&lt;code>extra_body&lt;/code> (object, optional): SGLang 特有的扩展参数，如 &lt;code>{&amp;quot;regex&amp;quot;: &amp;quot;...&amp;quot;}&lt;/code> 或 &lt;code>{&amp;quot;ebnf&amp;quot;: &amp;quot;...&amp;quot;}&lt;/code>。&lt;/li>
&lt;/ul>
&lt;/li>
&lt;/ul>
&lt;p>&lt;strong>示例 (使用 &lt;code>openai&lt;/code> 库)&lt;/strong>:&lt;/p>
&lt;pre>&lt;code class="language-python">import openai
client = openai.Client(base_url=&amp;quot;http://127.0.0.1:30000/v1&amp;quot;, api_key=&amp;quot;EMPTY&amp;quot;)
response = client.chat.completions.create(
model=&amp;quot;meta-llama/Meta-Llama-3.1-8B-Instruct&amp;quot;,
messages=[{&amp;quot;role&amp;quot;: &amp;quot;user&amp;quot;, &amp;quot;content&amp;quot;: &amp;quot;List 3 countries and their capitals.&amp;quot;}],
temperature=0,
max_tokens=64,
)
print(response.choices[0].message.content)
&lt;/code>&lt;/pre>
&lt;h2 id="6-">6. 高级用法：函数调用/工具使用&lt;/h2>
&lt;p>SGLang 强大的编程模型使其非常适合构建能够调用外部工具的 AI Agent。这通常通过结构化输出来实现，模型被引导生成一个描述函数调用的特定格式的文本（通常是 JSON）。&lt;/p>
&lt;p>以下是构建一个简单天气查询 Agent 的步骤：&lt;/p>
&lt;p>&lt;strong>1. 定义工具 Schema&lt;/strong>&lt;/p>
&lt;p>首先，使用 JSON Schema 定义你的工具。这告诉模型工具的名称、目的以及需要哪些参数。&lt;/p>
&lt;pre>&lt;code class="language-python">tools = [
{
&amp;quot;type&amp;quot;: &amp;quot;function&amp;quot;,
&amp;quot;function&amp;quot;: {
&amp;quot;name&amp;quot;: &amp;quot;get_current_weather&amp;quot;,
&amp;quot;description&amp;quot;: &amp;quot;Get the current weather in a given location&amp;quot;,
&amp;quot;parameters&amp;quot;: {
&amp;quot;type&amp;quot;: &amp;quot;object&amp;quot;,
&amp;quot;properties&amp;quot;: {
&amp;quot;city&amp;quot;: {&amp;quot;type&amp;quot;: &amp;quot;string&amp;quot;, &amp;quot;description&amp;quot;: &amp;quot;The city name&amp;quot;},
&amp;quot;unit&amp;quot;: {&amp;quot;type&amp;quot;: &amp;quot;string&amp;quot;, &amp;quot;enum&amp;quot;: [&amp;quot;celsius&amp;quot;, &amp;quot;fahrenheit&amp;quot;]},
},
&amp;quot;required&amp;quot;: [&amp;quot;city&amp;quot;, &amp;quot;unit&amp;quot;],
},
},
}
]
&lt;/code>&lt;/pre>
&lt;p>&lt;strong>2. 引导模型进行函数调用&lt;/strong>&lt;/p>
&lt;p>在发送给模型的 &lt;code>messages&lt;/code> 中，包含一个系统提示，指示模型可以使用这些工具。然后，在 API 调用中传入 &lt;code>tools&lt;/code> 和 &lt;code>tool_choice=&amp;quot;auto&amp;quot;&lt;/code>。&lt;/p>
&lt;pre>&lt;code class="language-python">import json
messages = [
{&amp;quot;role&amp;quot;: &amp;quot;system&amp;quot;, &amp;quot;content&amp;quot;: &amp;quot;You are a helpful assistant that can access external tools.&amp;quot;},
{&amp;quot;role&amp;quot;: &amp;quot;user&amp;quot;, &amp;quot;content&amp;quot;: &amp;quot;What's the weather like in Boston in fahrenheit?&amp;quot;}
]
response = client.chat.completions.create(
model=&amp;quot;meta-llama/Meta-Llama-3.1-8B-Instruct&amp;quot;,
messages=messages,
tools=tools,
tool_choice=&amp;quot;auto&amp;quot;,
)
# 检查模型是否决定调用工具
response_message = response.choices[0].message
tool_calls = response_message.tool_calls
if tool_calls:
# 模型决定调用工具
for tool_call in tool_calls:
function_name = tool_call.function.name
function_args = json.loads(tool_call.function.arguments)
print(f&amp;quot;Function Call: {function_name}&amp;quot;)
print(f&amp;quot;Arguments: {function_args}&amp;quot;)
# 在这里，你可以实际执行函数调用
# e.g., result = get_current_weather(**function_args)
&lt;/code>&lt;/pre>
&lt;p>&lt;strong>输出:&lt;/strong>&lt;/p>
&lt;pre>&lt;code>Function Call: get_current_weather
Arguments: {'city': 'Boston', 'unit': 'fahrenheit'}
&lt;/code>&lt;/pre>
&lt;p>通过这种方式，你可以构建出能够与外部世界交互的、功能强大的 AI 应用。&lt;/p></description></item></channel></rss>