[ SKILL_DOCUMENTATION ]
# 结构化生成指南
使用 SGLang 生成结构化输出的完整指南。
## JSON 生成
### 基础 JSON 输出
python
import sglang as sgl
@sgl.function
def basic_json(s, text):
s += f"Extract person info from: {text}n"
s += "Output as JSON:n"
# JSON 对象的简单正则表达式
s += sgl.gen(
"json",
max_tokens=150,
regex=r'{[^}]+}' # 基础 JSON 模式
)
state = basic_json.run(text="Alice is a 28-year-old doctor")
print(state["json"])
# 输出: {"name": "Alice", "age": 28, "profession": "doctor"}
### 带模式验证的 JSON
python
@sgl.function
def schema_json(s, description):
s += f"Create a product from: {description}n"
# 详细的 JSON 模式
schema = {
"type": "object",
"properties": {
"name": {"type": "string"},
"price": {"type": "number", "minimum": 0},
"category": {
"type": "string",
"enum": ["electronics", "clothing", "food", "books"]
},
"in_stock": {"type": "boolean"},
"tags": {
"type": "array",
"items": {"type": "string"},
"minItems": 1,
"maxItems": 5
}
},
"required": ["name", "price", "category", "in_stock"]
}
s += sgl.gen("product", max_tokens=300, json_schema=schema)
state = schema_json.run(
description="Wireless headphones, $79.99, currently available, audio"
)
print(state["product"])
# 输出: 完全匹配模式的有效 JSON
**输出示例**:
{
"name": "Wireless Headphones",
"price": 79.99,
"category": "electronics",
"in_stock": true,
"tags": ["audio", "wireless", "bluetooth"]
}
### 嵌套 JSON 结构
python
schema = {
"type": "object",
"properties": {
"user": {
"type": "object",
"properties": {
"id": {"type": "integer"},
"name": {"type": "string"},
"email": {"type": "string", "format": "email"}
},
"required": ["id", "name", "email"]
},
"orders": {
"type": "array",
"items": {
"type": "object",
"properties": {
"order_id": {"type": "string"},
"total": {"type": "number"},
"items": {
"type": "array",