Skip to content

Commit d76e81c

Browse files
authored
Add SRT json decode example (sgl-project#2)
1 parent 4473776 commit d76e81c

File tree

4 files changed

+33
-2
lines changed

4 files changed

+33
-2
lines changed

python/pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ dependencies = [
1919

2020
[project.optional-dependencies]
2121
srt = ["fastapi", "psutil", "rpyc", "torch", "uvloop", "uvicorn", "zmq", "vllm>=0.2.5",
22-
"interegular", "lark"]
22+
"interegular", "lark", "numba"]
2323
openai = ["openai>=1.0"]
2424
anthropic = ["anthropic"]
2525
all = ["sglang[srt]", "sglang[openai]", "sglang[anthropic]"]

python/sglang/lang/ir.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,11 @@
66

77
from sglang.global_config import global_config
88

9+
REGEX_INT = r"[-+]?[0-9]+"
10+
REGEX_FLOAT = r"[-+]?[0-9]*\.?[0-9]+"
11+
REGEX_BOOL = r"(True|False)"
12+
REGEX_STRING = r"\"[\w\d\s]*\"" # bugs with regex r"\".*\"" in interegular pkg
13+
914

1015
@dataclasses.dataclass
1116
class SamplingParams:

python/sglang/test/test_programs.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,29 @@ def decode_int(s):
102102
assert int(ret["days"]) == 365, ret.text
103103

104104

105+
def test_decode_json_regex():
106+
@sgl.function
107+
def decode_json(s):
108+
from sglang.lang.ir import REGEX_FLOAT, REGEX_INT, REGEX_STRING
109+
110+
s += "Generate a JSON object to describe the basic information of a city.\n"
111+
112+
with s.var_scope("json_output"):
113+
s += "{\n"
114+
s += ' "name": ' + sgl.gen(regex=REGEX_STRING + ",") + "\n"
115+
s += ' "population": ' + sgl.gen(regex=REGEX_INT + ",") + "\n"
116+
s += ' "area": ' + sgl.gen(regex=REGEX_INT + ",") + "\n"
117+
s += ' "latitude": ' + sgl.gen(regex=REGEX_FLOAT + ",") + "\n"
118+
s += ' "country": ' + sgl.gen(regex=REGEX_STRING + ",") + "\n"
119+
s += ' "timezone": ' + sgl.gen(regex=REGEX_STRING) + "\n"
120+
s += "}"
121+
122+
ret = decode_json.run()
123+
js_obj = json.loads(ret["json_output"])
124+
assert isinstance(js_obj["name"], str)
125+
assert isinstance(js_obj["population"], int)
126+
127+
105128
def test_decode_json():
106129
@sgl.function
107130
def decode_json(s):

test/lang/test_srt_backend.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77
from sglang.test.test_programs import (
88
test_decode_int,
9-
test_decode_json,
9+
test_decode_json_regex,
1010
test_expert_answer,
1111
test_few_shot_qa,
1212
test_mt_bench,
@@ -44,6 +44,9 @@ def test_select(self):
4444
def test_decode_int(self):
4545
test_decode_int()
4646

47+
def test_decode_json_regex(self):
48+
test_decode_json_regex()
49+
4750
def test_expert_answer(self):
4851
test_expert_answer()
4952

0 commit comments

Comments
 (0)