"scripts/killall_sglang.sh" did not exist on "7023f413c6c57cf29c20a7b28582fa01398de1b6"
tool_parser.ipynb 30.4 KB
Newer Older
Tanjiro's avatar
Tanjiro committed
1
2
3
4
5
6
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
7
    "# Tool Parser\n",
Tanjiro's avatar
Tanjiro committed
8
    "\n",
9
    "This guide demonstrates how to use SGLang’s [Function calling](https://platform.openai.com/docs/guides/function-calling) functionality."
Tanjiro's avatar
Tanjiro committed
10
11
   ]
  },
12
13
14
15
16
17
18
19
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Currently supported parsers:\n",
    "\n",
    "| Parser | Supported Models | Notes |\n",
    "|---|---|---|\n",
20
21
22
23
24
    "| `deepseekv3` | DeepSeek-v3 (e.g., `deepseek-ai/DeepSeek-V3-0324`) | Recommend adding `--chat-template ./examples/chat_template/tool_chat_template_deepseekv3.jinja` to launch command. |\n",
    "| `deepseekv31` | DeepSeek-V3.1 and DeepSeek-V3.2 (e.g. `deepseek-ai/DeepSeek-V3.1`, `deepseek-ai/DeepSeek-V3.2-Exp`) | Recommend adding `--chat-template ./examples/chat_template/tool_chat_template_deepseekv31.jinja` (Or ..deepseekv32.jinja for DeepSeek-V3.2) to launch command. |\n",
    "| `glm` | GLM series (e.g. `zai-org/GLM-4.6`) | |\n",
    "| `gpt-oss` | GPT-OSS (e.g., `openai/gpt-oss-120b`, `openai/gpt-oss-20b`, `lmsys/gpt-oss-120b-bf16`, `lmsys/gpt-oss-20b-bf16`) | The gpt-oss tool parser filters out analysis channel events and only preserves normal text. This can cause the content to be empty when explanations are in the analysis channel. To work around this, complete the tool round by returning tool results as `role=\"tool\"` messages, which enables the model to generate the final content. |\n",
    "| `kimi_k2` | `moonshotai/Kimi-K2-Instruct` | |\n",
25
26
27
    "| `llama3` | Llama 3.1 / 3.2 / 3.3 (e.g. `meta-llama/Llama-3.1-8B-Instruct`, `meta-llama/Llama-3.2-1B-Instruct`, `meta-llama/Llama-3.3-70B-Instruct`) | |\n",
    "| `llama4` | Llama 4 (e.g. `meta-llama/Llama-4-Scout-17B-16E-Instruct`) | |\n",
    "| `mistral` | Mistral (e.g. `mistralai/Mistral-7B-Instruct-v0.3`, `mistralai/Mistral-Nemo-Instruct-2407`, `mistralai/Mistral-7B-v0.3`) | |\n",
28
29
30
31
    "| `pythonic` | Llama-3.2 / Llama-3.3 / Llama-4 | Model outputs function calls as Python code. Requires `--tool-call-parser pythonic` and is recommended to use with a specific chat template. |\n",
    "| `qwen` | Qwen series (e.g. `Qwen/Qwen3-Next-80B-A3B-Instruct`, `Qwen/Qwen3-VL-30B-A3B-Thinking`) except Qwen3-Coder| |\n",
    "| `qwen3_coder` | Qwen3-Coder (e.g. `Qwen/Qwen3-Coder-30B-A3B-Instruct`) | |\n",
    "| `step3` | Step-3 | |\n"
32
33
   ]
  },
Tanjiro's avatar
Tanjiro committed
34
35
36
37
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
YAMY's avatar
YAMY committed
38
39
40
41
42
43
44
45
    "## OpenAI Compatible API"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Launching the Server"
Tanjiro's avatar
Tanjiro committed
46
47
48
49
50
51
52
53
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
YAMY's avatar
YAMY committed
54
    "import json\n",
Lianmin Zheng's avatar
Lianmin Zheng committed
55
    "from sglang.test.doc_patch import launch_server_cmd\n",
56
    "from sglang.utils import wait_for_server, print_highlight, terminate_process\n",
Lianmin Zheng's avatar
Lianmin Zheng committed
57
    "from openai import OpenAI\n",
Tanjiro's avatar
Tanjiro committed
58
    "\n",
59
    "server_process, port = launch_server_cmd(\n",
60
    "    \"python3 -m sglang.launch_server --model-path Qwen/Qwen2.5-7B-Instruct --tool-call-parser qwen25 --host 0.0.0.0 --log-level warning\"  # qwen25\n",
Tanjiro's avatar
Tanjiro committed
61
    ")\n",
62
    "wait_for_server(f\"http://localhost:{port}\")"
YAMY's avatar
YAMY committed
63
64
65
66
67
68
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
69
    "Note that `--tool-call-parser` defines the parser used to interpret responses."
Tanjiro's avatar
Tanjiro committed
70
71
72
73
74
75
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
YAMY's avatar
YAMY committed
76
77
    "### Define Tools for Function Call\n",
    "Below is a Python snippet that shows how to define a tool as a dictionary. The dictionary includes a tool name, a description, and property defined Parameters."
Tanjiro's avatar
Tanjiro committed
78
79
80
81
82
83
84
85
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
YAMY's avatar
YAMY committed
86
    "# Define tools\n",
Tanjiro's avatar
Tanjiro committed
87
88
89
90
91
92
93
94
95
    "tools = [\n",
    "    {\n",
    "        \"type\": \"function\",\n",
    "        \"function\": {\n",
    "            \"name\": \"get_current_weather\",\n",
    "            \"description\": \"Get the current weather in a given location\",\n",
    "            \"parameters\": {\n",
    "                \"type\": \"object\",\n",
    "                \"properties\": {\n",
YAMY's avatar
YAMY committed
96
97
98
99
100
    "                    \"city\": {\n",
    "                        \"type\": \"string\",\n",
    "                        \"description\": \"The city to find the weather for, e.g. 'San Francisco'\",\n",
    "                    },\n",
    "                    \"state\": {\n",
Tanjiro's avatar
Tanjiro committed
101
    "                        \"type\": \"string\",\n",
YAMY's avatar
YAMY committed
102
103
104
105
106
107
108
    "                        \"description\": \"the two-letter abbreviation for the state that the city is\"\n",
    "                        \" in, e.g. 'CA' which would mean 'California'\",\n",
    "                    },\n",
    "                    \"unit\": {\n",
    "                        \"type\": \"string\",\n",
    "                        \"description\": \"The unit to fetch the temperature in\",\n",
    "                        \"enum\": [\"celsius\", \"fahrenheit\"],\n",
Tanjiro's avatar
Tanjiro committed
109
110
    "                    },\n",
    "                },\n",
YAMY's avatar
YAMY committed
111
    "                \"required\": [\"city\", \"state\", \"unit\"],\n",
Tanjiro's avatar
Tanjiro committed
112
113
114
    "            },\n",
    "        },\n",
    "    }\n",
YAMY's avatar
YAMY committed
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
    "]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Define Messages"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_messages():\n",
    "    return [\n",
    "        {\n",
    "            \"role\": \"user\",\n",
135
    "            \"content\": \"What's the weather like in Boston today? Output a reasoning before act, then use the tools to help you.\",\n",
YAMY's avatar
YAMY committed
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
    "        }\n",
    "    ]\n",
    "\n",
    "\n",
    "messages = get_messages()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Initialize the Client"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Initialize OpenAI-like client\n",
157
    "client = OpenAI(api_key=\"None\", base_url=f\"http://0.0.0.0:{port}/v1\")\n",
YAMY's avatar
YAMY committed
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
    "model_name = client.models.list().data[0].id"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "###  Non-Streaming Request"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Non-streaming mode test\n",
    "response_non_stream = client.chat.completions.create(\n",
    "    model=model_name,\n",
    "    messages=messages,\n",
178
    "    temperature=0,\n",
179
180
    "    top_p=0.95,\n",
    "    max_tokens=1024,\n",
YAMY's avatar
YAMY committed
181
182
183
184
    "    stream=False,  # Non-streaming\n",
    "    tools=tools,\n",
    ")\n",
    "print_highlight(\"Non-stream response:\")\n",
185
    "print_highlight(response_non_stream)\n",
186
    "print_highlight(\"==== content ====\")\n",
187
    "print_highlight(response_non_stream.choices[0].message.content)\n",
188
    "print_highlight(\"==== tool_calls ====\")\n",
189
    "print_highlight(response_non_stream.choices[0].message.tool_calls)"
YAMY's avatar
YAMY committed
190
191
192
193
194
195
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
196
197
    "#### Handle Tools\n",
    "When the engine determines it should call a particular tool, it will return arguments or partial arguments through the response. You can parse these arguments and later invoke the tool accordingly."
YAMY's avatar
YAMY committed
198
199
200
201
202
203
204
205
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
206
207
208
    "name_non_stream = response_non_stream.choices[0].message.tool_calls[0].function.name\n",
    "arguments_non_stream = (\n",
    "    response_non_stream.choices[0].message.tool_calls[0].function.arguments\n",
YAMY's avatar
YAMY committed
209
210
    ")\n",
    "\n",
211
212
    "print_highlight(f\"Final streamed function call name: {name_non_stream}\")\n",
    "print_highlight(f\"Final streamed function call arguments: {arguments_non_stream}\")"
YAMY's avatar
YAMY committed
213
214
215
216
217
218
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
219
    "### Streaming Request"
YAMY's avatar
YAMY committed
220
221
222
223
224
225
226
227
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
228
229
230
231
232
    "# Streaming mode test\n",
    "print_highlight(\"Streaming response:\")\n",
    "response_stream = client.chat.completions.create(\n",
    "    model=model_name,\n",
    "    messages=messages,\n",
233
    "    temperature=0,\n",
234
235
236
237
    "    top_p=0.95,\n",
    "    max_tokens=1024,\n",
    "    stream=True,  # Enable streaming\n",
    "    tools=tools,\n",
YAMY's avatar
YAMY committed
238
239
    ")\n",
    "\n",
240
241
242
243
244
245
246
247
248
249
    "texts = \"\"\n",
    "tool_calls = []\n",
    "name = \"\"\n",
    "arguments = \"\"\n",
    "for chunk in response_stream:\n",
    "    if chunk.choices[0].delta.content:\n",
    "        texts += chunk.choices[0].delta.content\n",
    "    if chunk.choices[0].delta.tool_calls:\n",
    "        tool_calls.append(chunk.choices[0].delta.tool_calls[0])\n",
    "print_highlight(\"==== Text ====\")\n",
250
    "print_highlight(texts)\n",
251
252
253
    "\n",
    "print_highlight(\"==== Tool Call ====\")\n",
    "for tool_call in tool_calls:\n",
254
    "    print_highlight(tool_call)"
YAMY's avatar
YAMY committed
255
256
257
258
259
260
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
261
262
    "#### Handle Tools\n",
    "When the engine determines it should call a particular tool, it will return arguments or partial arguments through the response. You can parse these arguments and later invoke the tool accordingly."
YAMY's avatar
YAMY committed
263
264
265
266
267
268
269
270
271
272
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Parse and combine function call arguments\n",
    "arguments = []\n",
273
274
275
276
277
278
    "for tool_call in tool_calls:\n",
    "    if tool_call.function.name:\n",
    "        print_highlight(f\"Streamed function call name: {tool_call.function.name}\")\n",
    "\n",
    "    if tool_call.function.arguments:\n",
    "        arguments.append(tool_call.function.arguments)\n",
YAMY's avatar
YAMY committed
279
280
281
    "\n",
    "# Combine all fragments into a single JSON string\n",
    "full_arguments = \"\".join(arguments)\n",
282
    "print_highlight(f\"streamed function call arguments: {full_arguments}\")"
YAMY's avatar
YAMY committed
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Define a Tool Function"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# This is a demonstration, define real function according to your usage.\n",
    "def get_current_weather(city: str, state: str, unit: \"str\"):\n",
    "    return (\n",
    "        f\"The weather in {city}, {state} is 85 degrees {unit}. It is \"\n",
    "        \"partly cloudly, with highs in the 90's.\"\n",
    "    )\n",
    "\n",
    "\n",
    "available_tools = {\"get_current_weather\": get_current_weather}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
Lianmin Zheng's avatar
Lianmin Zheng committed
314
    "### Execute the Tool"
YAMY's avatar
YAMY committed
315
316
317
318
319
320
321
322
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
323
    "messages.append(response_non_stream.choices[0].message)\n",
YAMY's avatar
YAMY committed
324
    "\n",
325
326
327
328
329
330
331
    "# Call the corresponding tool function\n",
    "tool_call = messages[-1].tool_calls[0]\n",
    "tool_name = tool_call.function.name\n",
    "tool_to_call = available_tools[tool_name]\n",
    "result = tool_to_call(**(json.loads(tool_call.function.arguments)))\n",
    "print_highlight(f\"Function call result: {result}\")\n",
    "# messages.append({\"role\": \"tool\", \"content\": result, \"name\": tool_name})\n",
YAMY's avatar
YAMY committed
332
333
    "messages.append(\n",
    "    {\n",
334
335
336
337
    "        \"role\": \"tool\",\n",
    "        \"tool_call_id\": tool_call.id,\n",
    "        \"content\": str(result),\n",
    "        \"name\": tool_name,\n",
YAMY's avatar
YAMY committed
338
339
    "    }\n",
    ")\n",
Tanjiro's avatar
Tanjiro committed
340
    "\n",
YAMY's avatar
YAMY committed
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
    "print_highlight(f\"Updated message history: {messages}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Send Results Back to Model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "final_response = client.chat.completions.create(\n",
Tanjiro's avatar
Tanjiro committed
358
359
    "    model=model_name,\n",
    "    messages=messages,\n",
360
    "    temperature=0,\n",
361
    "    top_p=0.95,\n",
Tanjiro's avatar
Tanjiro committed
362
363
364
    "    stream=False,\n",
    "    tools=tools,\n",
    ")\n",
YAMY's avatar
YAMY committed
365
    "print_highlight(\"Non-stream response:\")\n",
366
    "print_highlight(final_response)\n",
367
368
    "\n",
    "print_highlight(\"==== Text ====\")\n",
369
    "print_highlight(final_response.choices[0].message.content)"
YAMY's avatar
YAMY committed
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Native API and SGLang Runtime (SRT)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from transformers import AutoTokenizer\n",
    "import requests\n",
    "\n",
    "# generate an answer\n",
389
    "tokenizer = AutoTokenizer.from_pretrained(\"Qwen/Qwen2.5-7B-Instruct\")\n",
YAMY's avatar
YAMY committed
390
391
392
393
394
395
396
397
398
    "\n",
    "messages = get_messages()\n",
    "\n",
    "input = tokenizer.apply_chat_template(\n",
    "    messages,\n",
    "    tokenize=False,\n",
    "    add_generation_prompt=True,\n",
    "    tools=tools,\n",
    ")\n",
Tanjiro's avatar
Tanjiro committed
399
    "\n",
400
    "gen_url = f\"http://localhost:{port}/generate\"\n",
401
402
403
404
405
    "gen_data = {\n",
    "    \"text\": input,\n",
    "    \"sampling_params\": {\n",
    "        \"skip_special_tokens\": False,\n",
    "        \"max_new_tokens\": 1024,\n",
406
    "        \"temperature\": 0,\n",
407
408
409
    "        \"top_p\": 0.95,\n",
    "    },\n",
    "}\n",
YAMY's avatar
YAMY committed
410
    "gen_response = requests.post(gen_url, json=gen_data).json()[\"text\"]\n",
411
    "print_highlight(\"==== Response ====\")\n",
412
    "print_highlight(gen_response)\n",
Tanjiro's avatar
Tanjiro committed
413
    "\n",
YAMY's avatar
YAMY committed
414
    "# parse the response\n",
415
    "parse_url = f\"http://localhost:{port}/parse_function_call\"\n",
Tanjiro's avatar
Tanjiro committed
416
    "\n",
YAMY's avatar
YAMY committed
417
418
    "function_call_input = {\n",
    "    \"text\": gen_response,\n",
419
    "    \"tool_call_parser\": \"qwen25\",\n",
YAMY's avatar
YAMY committed
420
421
    "    \"tools\": tools,\n",
    "}\n",
Tanjiro's avatar
Tanjiro committed
422
    "\n",
YAMY's avatar
YAMY committed
423
424
    "function_call_response = requests.post(parse_url, json=function_call_input)\n",
    "function_call_response_json = function_call_response.json()\n",
425
426
427
428
    "\n",
    "print_highlight(\"==== Text ====\")\n",
    "print(function_call_response_json[\"normal_text\"])\n",
    "print_highlight(\"==== Calls ====\")\n",
YAMY's avatar
YAMY committed
429
430
    "print(\"function name: \", function_call_response_json[\"calls\"][0][\"name\"])\n",
    "print(\"function arguments: \", function_call_response_json[\"calls\"][0][\"parameters\"])"
Tanjiro's avatar
Tanjiro committed
431
432
433
434
435
436
437
438
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
439
    "terminate_process(server_process)"
Tanjiro's avatar
Tanjiro committed
440
441
442
443
444
445
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
YAMY's avatar
YAMY committed
446
447
448
449
450
451
452
453
454
455
    "## Offline Engine API"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import sglang as sgl\n",
456
    "from sglang.srt.function_call.function_call_parser import FunctionCallParser\n",
YAMY's avatar
YAMY committed
457
458
    "from sglang.srt.managers.io_struct import Tool, Function\n",
    "\n",
459
    "llm = sgl.Engine(model_path=\"Qwen/Qwen2.5-7B-Instruct\")\n",
460
    "tokenizer = llm.tokenizer_manager.tokenizer\n",
YAMY's avatar
YAMY committed
461
462
463
464
    "input_ids = tokenizer.apply_chat_template(\n",
    "    messages, tokenize=True, add_generation_prompt=True, tools=tools\n",
    ")\n",
    "\n",
465
466
467
    "# Note that for gpt-oss tool parser, adding \"no_stop_trim\": True\n",
    "# to make sure the tool call token <call> is not trimmed.\n",
    "\n",
YAMY's avatar
YAMY committed
468
    "sampling_params = {\n",
469
    "    \"max_new_tokens\": 1024,\n",
470
    "    \"temperature\": 0,\n",
YAMY's avatar
YAMY committed
471
472
473
474
475
476
477
478
    "    \"top_p\": 0.95,\n",
    "    \"skip_special_tokens\": False,\n",
    "}\n",
    "\n",
    "# 1) Offline generation\n",
    "result = llm.generate(input_ids=input_ids, sampling_params=sampling_params)\n",
    "generated_text = result[\"text\"]  # Assume there is only one prompt\n",
    "\n",
479
480
    "print_highlight(\"=== Offline Engine Output Text ===\")\n",
    "print_highlight(generated_text)\n",
YAMY's avatar
YAMY committed
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
    "\n",
    "\n",
    "# 2) Parse using FunctionCallParser\n",
    "def convert_dict_to_tool(tool_dict: dict) -> Tool:\n",
    "    function_dict = tool_dict.get(\"function\", {})\n",
    "    return Tool(\n",
    "        type=tool_dict.get(\"type\", \"function\"),\n",
    "        function=Function(\n",
    "            name=function_dict.get(\"name\"),\n",
    "            description=function_dict.get(\"description\"),\n",
    "            parameters=function_dict.get(\"parameters\"),\n",
    "        ),\n",
    "    )\n",
    "\n",
    "\n",
    "tools = [convert_dict_to_tool(raw_tool) for raw_tool in tools]\n",
    "\n",
498
    "parser = FunctionCallParser(tools=tools, tool_call_parser=\"qwen25\")\n",
YAMY's avatar
YAMY committed
499
500
    "normal_text, calls = parser.parse_non_stream(generated_text)\n",
    "\n",
501
    "print_highlight(\"=== Parsing Result ===\")\n",
YAMY's avatar
YAMY committed
502
    "print(\"Normal text portion:\", normal_text)\n",
503
    "print_highlight(\"Function call portion:\")\n",
YAMY's avatar
YAMY committed
504
505
    "for call in calls:\n",
    "    # call: ToolCallItem\n",
506
507
    "    print_highlight(f\"  - tool name: {call.name}\")\n",
    "    print_highlight(f\"    parameters: {call.parameters}\")\n",
Tanjiro's avatar
Tanjiro committed
508
    "\n",
YAMY's avatar
YAMY committed
509
510
511
512
513
514
515
516
517
518
519
520
    "# 3) If needed, perform additional logic on the parsed functions, such as automatically calling the corresponding function to obtain a return value, etc."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "llm.shutdown()"
   ]
  },
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Tool Choice Mode\n",
    "\n",
    "SGLang supports OpenAI's `tool_choice` parameter to control when and which tools the model should call. This feature is implemented using EBNF (Extended Backus-Naur Form) grammar to ensure reliable tool calling behavior.\n",
    "\n",
    "### Supported Tool Choice Options\n",
    "\n",
    "- **`tool_choice=\"required\"`**: Forces the model to call at least one tool\n",
    "- **`tool_choice={\"type\": \"function\", \"function\": {\"name\": \"specific_function\"}}`**: Forces the model to call a specific function\n",
    "\n",
    "### Backend Compatibility\n",
    "\n",
    "Tool choice is fully supported with the **Xgrammar backend**, which is the default grammar backend (`--grammar-backend xgrammar`). However, it may not be fully supported with other backends such as `outlines`.\n",
    "\n",
    "### Example: Required Tool Choice"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from openai import OpenAI\n",
    "from sglang.utils import wait_for_server, print_highlight, terminate_process\n",
    "from sglang.test.doc_patch import launch_server_cmd\n",
    "\n",
    "# Start a new server session for tool choice examples\n",
    "server_process_tool_choice, port_tool_choice = launch_server_cmd(\n",
553
    "    \"python3 -m sglang.launch_server --model-path Qwen/Qwen2.5-7B-Instruct --tool-call-parser qwen25 --host 0.0.0.0  --log-level warning\"\n",
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
    ")\n",
    "wait_for_server(f\"http://localhost:{port_tool_choice}\")\n",
    "\n",
    "# Initialize client for tool choice examples\n",
    "client_tool_choice = OpenAI(\n",
    "    api_key=\"None\", base_url=f\"http://0.0.0.0:{port_tool_choice}/v1\"\n",
    ")\n",
    "model_name_tool_choice = client_tool_choice.models.list().data[0].id\n",
    "\n",
    "# Example with tool_choice=\"required\" - forces the model to call a tool\n",
    "messages_required = [\n",
    "    {\"role\": \"user\", \"content\": \"Hello, what is the capital of France?\"}\n",
    "]\n",
    "\n",
    "# Define tools\n",
    "tools = [\n",
    "    {\n",
    "        \"type\": \"function\",\n",
    "        \"function\": {\n",
    "            \"name\": \"get_current_weather\",\n",
    "            \"description\": \"Get the current weather in a given location\",\n",
    "            \"parameters\": {\n",
    "                \"type\": \"object\",\n",
    "                \"properties\": {\n",
    "                    \"city\": {\n",
    "                        \"type\": \"string\",\n",
    "                        \"description\": \"The city to find the weather for, e.g. 'San Francisco'\",\n",
    "                    },\n",
    "                    \"unit\": {\n",
    "                        \"type\": \"string\",\n",
    "                        \"description\": \"The unit to fetch the temperature in\",\n",
    "                        \"enum\": [\"celsius\", \"fahrenheit\"],\n",
    "                    },\n",
    "                },\n",
    "                \"required\": [\"city\", \"unit\"],\n",
    "            },\n",
    "        },\n",
    "    }\n",
    "]\n",
    "\n",
    "response_required = client_tool_choice.chat.completions.create(\n",
    "    model=model_name_tool_choice,\n",
    "    messages=messages_required,\n",
    "    temperature=0,\n",
    "    max_tokens=1024,\n",
    "    tools=tools,\n",
    "    tool_choice=\"required\",  # Force the model to call a tool\n",
    ")\n",
    "\n",
    "print_highlight(\"Response with tool_choice='required':\")\n",
    "print(\"Content:\", response_required.choices[0].message.content)\n",
    "print(\"Tool calls:\", response_required.choices[0].message.tool_calls)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Example: Specific Function Choice\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Example with specific function choice - forces the model to call a specific function\n",
    "messages_specific = [\n",
    "    {\"role\": \"user\", \"content\": \"What are the most attactive places in France?\"}\n",
    "]\n",
    "\n",
    "response_specific = client_tool_choice.chat.completions.create(\n",
    "    model=model_name_tool_choice,\n",
    "    messages=messages_specific,\n",
    "    temperature=0,\n",
    "    max_tokens=1024,\n",
    "    tools=tools,\n",
    "    tool_choice={\n",
    "        \"type\": \"function\",\n",
    "        \"function\": {\"name\": \"get_current_weather\"},\n",
    "    },  # Force the model to call the specific get_current_weather function\n",
    ")\n",
    "\n",
    "print_highlight(\"Response with specific function choice:\")\n",
    "print(\"Content:\", response_specific.choices[0].message.content)\n",
    "print(\"Tool calls:\", response_specific.choices[0].message.tool_calls)\n",
    "\n",
    "if response_specific.choices[0].message.tool_calls:\n",
    "    tool_call = response_specific.choices[0].message.tool_calls[0]\n",
644
645
    "    print_highlight(f\"Called function: {tool_call.function.name}\")\n",
    "    print_highlight(f\"Arguments: {tool_call.function.arguments}\")"
646
647
648
649
650
651
652
653
654
655
656
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "terminate_process(server_process_tool_choice)"
   ]
  },
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Pythonic Tool Call Format (Llama-3.2 / Llama-3.3 / Llama-4)\n",
    "\n",
    "Some Llama models (such as Llama-3.2-1B, Llama-3.2-3B, Llama-3.3-70B, and Llama-4) support a \"pythonic\" tool call format, where the model outputs function calls as Python code, e.g.:\n",
    "\n",
    "```python\n",
    "[get_current_weather(city=\"San Francisco\", state=\"CA\", unit=\"celsius\")]\n",
    "```\n",
    "\n",
    "- The output is a Python list of function calls, with arguments as Python literals (not JSON).\n",
    "- Multiple tool calls can be returned in the same list:\n",
    "```python\n",
    "[get_current_weather(city=\"San Francisco\", state=\"CA\", unit=\"celsius\"),\n",
    " get_current_weather(city=\"New York\", state=\"NY\", unit=\"fahrenheit\")]\n",
    "```\n",
    "\n",
    "For more information, refer to Meta’s documentation on  [Zero shot function calling](https://github.com/meta-llama/llama-models/blob/main/models/llama4/prompt_format.md#zero-shot-function-calling---system-message).\n",
    "\n",
678
679
    "Note that this feature is still under development on Blackwell.\n",
    "\n",
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
    "### How to enable\n",
    "- Launch the server with `--tool-call-parser pythonic`\n",
    "- You may also specify --chat-template with the improved template for the model (e.g., `--chat-template=examples/chat_template/tool_chat_template_llama4_pythonic.jinja`).\n",
    "This is recommended because the model expects a special prompt format to reliably produce valid pythonic tool call outputs. The template ensures that the prompt structure (e.g., special tokens, message boundaries like `<|eom|>`, and function call delimiters) matches what the model was trained or fine-tuned on. If you do not use the correct chat template, tool calling may fail or produce inconsistent results.\n",
    "\n",
    "#### Forcing Pythonic Tool Call Output Without a Chat Template\n",
    "If you don't want to specify a chat template, you must give the model extremely explicit instructions in your messages to enforce pythonic output. For example, for `Llama-3.2-1B-Instruct`, you need:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import openai\n",
    "\n",
    "server_process, port = launch_server_cmd(\n",
698
    "    \" python3 -m sglang.launch_server --model-path meta-llama/Llama-3.2-1B-Instruct --tool-call-parser pythonic --tp 1  --log-level warning\"  # llama-3.2-1b-instruct\n",
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
    ")\n",
    "wait_for_server(f\"http://localhost:{port}\")\n",
    "\n",
    "tools = [\n",
    "    {\n",
    "        \"type\": \"function\",\n",
    "        \"function\": {\n",
    "            \"name\": \"get_weather\",\n",
    "            \"description\": \"Get the current weather for a given location.\",\n",
    "            \"parameters\": {\n",
    "                \"type\": \"object\",\n",
    "                \"properties\": {\n",
    "                    \"location\": {\n",
    "                        \"type\": \"string\",\n",
    "                        \"description\": \"The name of the city or location.\",\n",
    "                    }\n",
    "                },\n",
    "                \"required\": [\"location\"],\n",
    "            },\n",
    "        },\n",
    "    },\n",
    "    {\n",
    "        \"type\": \"function\",\n",
    "        \"function\": {\n",
    "            \"name\": \"get_tourist_attractions\",\n",
    "            \"description\": \"Get a list of top tourist attractions for a given city.\",\n",
    "            \"parameters\": {\n",
    "                \"type\": \"object\",\n",
    "                \"properties\": {\n",
    "                    \"city\": {\n",
    "                        \"type\": \"string\",\n",
    "                        \"description\": \"The name of the city to find attractions for.\",\n",
    "                    }\n",
    "                },\n",
    "                \"required\": [\"city\"],\n",
    "            },\n",
    "        },\n",
    "    },\n",
    "]\n",
    "\n",
    "\n",
    "def get_messages():\n",
    "    return [\n",
    "        {\n",
    "            \"role\": \"system\",\n",
    "            \"content\": (\n",
    "                \"You are a travel assistant. \"\n",
    "                \"When asked to call functions, ALWAYS respond ONLY with a python list of function calls, \"\n",
    "                \"using this format: [func_name1(param1=value1, param2=value2), func_name2(param=value)]. \"\n",
    "                \"Do NOT use JSON, do NOT use variables, do NOT use any other format. \"\n",
    "                \"Here is an example:\\n\"\n",
    "                '[get_weather(location=\"Paris\"), get_tourist_attractions(city=\"Paris\")]'\n",
    "            ),\n",
    "        },\n",
    "        {\n",
    "            \"role\": \"user\",\n",
    "            \"content\": (\n",
    "                \"I'm planning a trip to Tokyo next week. What's the weather like and what are some top tourist attractions? \"\n",
    "                \"Propose parallel tool calls at once, using the python list of function calls format as shown above.\"\n",
    "            ),\n",
    "        },\n",
    "    ]\n",
    "\n",
    "\n",
    "messages = get_messages()\n",
    "\n",
    "client = openai.Client(base_url=f\"http://localhost:{port}/v1\", api_key=\"xxxxxx\")\n",
    "model_name = client.models.list().data[0].id\n",
    "\n",
    "\n",
    "response_non_stream = client.chat.completions.create(\n",
    "    model=model_name,\n",
    "    messages=messages,\n",
772
773
    "    temperature=0,\n",
    "    top_p=0.9,\n",
774
775
776
777
    "    stream=False,  # Non-streaming\n",
    "    tools=tools,\n",
    ")\n",
    "print_highlight(\"Non-stream response:\")\n",
778
    "print_highlight(response_non_stream)\n",
779
780
781
782
    "\n",
    "response_stream = client.chat.completions.create(\n",
    "    model=model_name,\n",
    "    messages=messages,\n",
783
784
    "    temperature=0,\n",
    "    top_p=0.9,\n",
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
    "    stream=True,\n",
    "    tools=tools,\n",
    ")\n",
    "texts = \"\"\n",
    "tool_calls = []\n",
    "name = \"\"\n",
    "arguments = \"\"\n",
    "\n",
    "for chunk in response_stream:\n",
    "    if chunk.choices[0].delta.content:\n",
    "        texts += chunk.choices[0].delta.content\n",
    "    if chunk.choices[0].delta.tool_calls:\n",
    "        tool_calls.append(chunk.choices[0].delta.tool_calls[0])\n",
    "\n",
    "print_highlight(\"Streaming Response:\")\n",
    "print_highlight(\"==== Text ====\")\n",
801
    "print_highlight(texts)\n",
802
803
804
    "\n",
    "print_highlight(\"==== Tool Call ====\")\n",
    "for tool_call in tool_calls:\n",
805
    "    print_highlight(tool_call)\n",
806
807
808
809
810
811
812
813
814
815
816
817
    "\n",
    "terminate_process(server_process)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> **Note:**  \n",
    "> The model may still default to JSON if it was heavily finetuned on that format. Prompt engineering (including examples) is the only way to increase the chance of pythonic output if you are not using a chat template."
   ]
  },
YAMY's avatar
YAMY committed
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## How to support a new model?\n",
    "1. Update the TOOLS_TAG_LIST in sglang/srt/function_call_parser.py with the model’s tool tags. Currently supported tags include:\n",
    "```\n",
    "\tTOOLS_TAG_LIST = [\n",
    "\t    “<|plugin|>“,\n",
    "\t    “<function=“,\n",
    "\t    “<tool_call>“,\n",
    "\t    “<|python_tag|>“,\n",
    "\t    “[TOOL_CALLS]”\n",
    "\t]\n",
    "```\n",
    "2. Create a new detector class in sglang/srt/function_call_parser.py that inherits from BaseFormatDetector. The detector should handle the model’s specific function call format. For example:\n",
    "```\n",
    "    class NewModelDetector(BaseFormatDetector):\n",
    "```\n",
    "3. Add the new detector to the MultiFormatParser class that manages all the format detectors."
Tanjiro's avatar
Tanjiro committed
838
839
840
841
842
   ]
  }
 ],
 "metadata": {
  "language_info": {
843
844
845
846
847
848
849
850
851
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3"
Tanjiro's avatar
Tanjiro committed
852
853
854
  }
 },
 "nbformat": 4,
855
 "nbformat_minor": 4
Tanjiro's avatar
Tanjiro committed
856
}